import { Dispatcher } from 'undici'; import type { OAuthClientInformationMixed } from '@modelcontextprotocol/sdk/shared/auth.js'; import type { OAuthClientMetadata } from '@modelcontextprotocol/sdk/shared/auth.js'; import type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js'; import type { OAuthDiscoveryState } from '@modelcontextprotocol/sdk/client/auth.js'; import type { OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js'; import type { Readable } from 'node:stream'; import type { Writable } from 'node:stream'; import { z } from 'zod'; declare interface ActivatePluginCommandPayload { readonly pluginId: string; readonly commandName: string; readonly args?: string | undefined; } declare interface ActivatePluginCommandRpcInput extends SessionIdRpcInput { readonly pluginId: string; readonly commandName: string; readonly args?: string | undefined; } declare interface ActivateSkillPayload { readonly name: string; readonly args?: string | undefined; } declare interface ActivateSkillRpcInput extends SessionIdRpcInput { readonly name: string; readonly args?: string | undefined; } export declare interface AddAdditionalDirInput { readonly id: string; readonly path: string; readonly persist: boolean; } export declare interface AddAdditionalDirOptions { /** When true, share the directory through workspace local config. When false, * keep it scoped to this session while still restoring it on session resume. */ readonly persist: boolean; } declare interface AddAdditionalDirPayload { readonly path: string; readonly persist: boolean; } export declare interface AddAdditionalDirResult { readonly additionalDirs: readonly string[]; readonly projectRoot: string; readonly configPath: string; readonly persisted: boolean; } declare interface AddAdditionalDirResult_2 { readonly additionalDirs: readonly string[]; readonly projectRoot: string; readonly configPath: string; readonly persisted: boolean; } declare class Agent { readonly type: AgentType; private _kaos; get kaos(): Kaos; readonly kimiConfig?: KimiConfig; readonly homedir?: string; readonly mediaOriginalsDir?: string; readonly rpc?: Partial; readonly toolServices?: ToolServices; readonly pluginSessionStarts: readonly EnabledPluginSessionStart[]; readonly pluginCommands: readonly PluginCommandDef[]; readonly rawGenerate: typeof generate; readonly modelProvider?: ModelProvider; readonly subagentHost?: SessionSubagentHost; readonly mcp?: McpConnectionManager; readonly hooks?: HookEngine; readonly log: Logger; readonly telemetry: TelemetryClient; readonly experimentalFlags: ExperimentalFlagResolver; readonly imageLimits: ImageLimits; readonly llmRequestLogger: LlmRequestLogger; readonly llmRequestRecorder: LlmRequestRecorder; readonly blobStore: BlobStore | undefined; readonly records: AgentRecords; readonly fullCompaction: FullCompaction; readonly microCompaction: MicroCompaction; readonly context: ContextMemory; readonly config: ConfigState; readonly turn: TurnFlow; readonly injection: InjectionManager; readonly permission: PermissionManager; readonly planMode: PlanMode; readonly swarmMode: SwarmMode; readonly usage: UsageRecorder; readonly skills: SkillManager | null; readonly tools: ToolManager; readonly background: BackgroundManager; readonly cron: CronManager | null; readonly goal: GoalMode; readonly replayBuilder: ReplayBuilder; /** * Print-mode (`kimi -p`) only: when true and the agent ends a turn while * background subagents (`kind === 'agent'`) are still running, the turn loop * holds the turn open and idle-waits until they finish, flushing their * completions into the turn so the model can react before the run exits. Set * by the session for print runs; defaults to false everywhere else. */ printDrainAgentTasksOnStop: boolean; private additionalDirs; private roleAdditional?; private activeProfile?; private brandHome?; private readonly emittedThinkingEffortWarnings; private readonly pendingThinkingEffortWarnings; private readonly systemPromptContextProvider?; constructor(options: AgentOptions); setKaos(kaos: Kaos): void; getAdditionalDirs(): readonly string[]; setAdditionalDirs(additionalDirs: readonly string[]): void; /** * Single decision point for select_tools progressive disclosure. All three * gates must be open: the model has the `dynamically_loaded_tools` * capability (message-level tool declarations), the model declares * `tool_use` (a model without tool use loading tools dynamically is a * contradiction), and the `tool-select` experimental flag is on. Every * consumer — top-level tools[] convergence, select_tools registration, * manifest announcements, projection shaping — reads this instead of * re-deriving the conditions, so degradation is lossless: any closed gate * reproduces the inline behavior byte-for-byte. */ get toolSelectEnabled(): boolean; get generate(): typeof generate; private warnAboutAnthropicThinkingEffort; private publishAnthropicThinkingEffortWarning; private flushPendingAnthropicThinkingEffortWarnings; warnAboutCurrentAnthropicThinkingEffort(): void; get llm(): KosongLLM; useProfile(profile: ResolvedAgentProfile, context?: PreparedSystemPromptContext, brandHome?: string): void; setActiveProfile(profile: ResolvedAgentProfile, brandHome?: string): void; /** * Re-render the system prompt with freshly gathered runtime context (cwd * listing, AGENTS.md, additional-dirs info, skill list). Called after * compaction so the post-compaction turns do not keep a snapshot captured * at session bootstrap. Invalidates the prompt-cache prefix by design. */ refreshSystemPrompt(): Promise; private updateSystemPromptFromProfile; resume(options?: AgentRecordsReplayOptions): Promise<{ warning?: string; }>; get rpcMethods(): PromisableMethods; emitEvent(event: AgentEvent): void; emitStatusUpdated(includeThinkingEffort?: boolean): void; private emitRecordsWriteError; } declare interface AgentAPI { prompt: (payload: PromptPayload) => void; runShellCommand: (payload: RunShellCommandPayload) => Promise; cancelShellCommand: (payload: CancelShellCommandPayload) => void; steer: (payload: SteerPayload) => void; cancel: (payload: CancelPayload) => void; undoHistory: (payload: UndoHistoryPayload) => void; setThinking: (payload: SetThinkingPayload) => void; setPermission: (payload: SetPermissionPayload) => void; setModel: (payload: SetModelPayload) => SetModelResult; getModel: (payload: EmptyPayload) => string; enterPlan: (payload: EmptyPayload) => void; cancelPlan: (payload: CancelPlanPayload) => void; clearPlan: (payload: EmptyPayload) => void; enterSwarm: (payload: EnterSwarmPayload) => void; exitSwarm: (payload: EmptyPayload) => void; getSwarmMode: (payload: EmptyPayload) => boolean; beginCompaction: (payload: BeginCompactionPayload) => void; cancelCompaction: (payload: EmptyPayload) => void; registerTool: (payload: RegisterToolPayload) => void; unregisterTool: (payload: UnregisterToolPayload) => void; setActiveTools: (payload: SetActiveToolsPayload) => void; stopBackground: (payload: StopBackgroundPayload) => void; detachBackground: (payload: DetachBackgroundPayload) => BackgroundTaskInfo | undefined; clearContext: (payload: EmptyPayload) => void; importContext: (payload: ImportContextPayload) => void; activateSkill: (payload: ActivateSkillPayload) => void; activatePluginCommand: (payload: ActivatePluginCommandPayload) => void; startBtw: (payload: EmptyPayload) => string; createGoal: (payload: CreateGoalPayload) => GoalSnapshot; getGoal: (payload: EmptyPayload) => GoalToolResult; pauseGoal: (payload: EmptyPayload) => GoalSnapshot; resumeGoal: (payload: EmptyPayload) => GoalSnapshot; cancelGoal: (payload: EmptyPayload) => GoalSnapshot; getCronTasks: (payload: EmptyPayload) => GetCronTasksResult; getBackgroundOutput: (payload: GetBackgroundOutputPayload) => string; getContext: (payload: EmptyPayload) => AgentContextData; getConfig: (payload: EmptyPayload) => AgentConfigData; getPermission: (payload: EmptyPayload) => PermissionData; getPlan: (payload: EmptyPayload) => PlanData; getUsage: (payload: EmptyPayload) => UsageStatus; getTools: (payload: EmptyPayload) => readonly ToolInfo[]; getBackground: (payload: GetBackgroundPayload) => readonly BackgroundTaskInfo[]; } declare type AgentAPIWithId = WithAgentId; export declare interface AgentBackgroundTaskInfo extends BackgroundTaskInfoBase { readonly kind: 'agent'; /** Subagent identifier accepted by Agent(resume=...). */ readonly agentId?: string; /** Subagent profile name. */ readonly subagentType?: string; } declare interface AgentConfigData { cwd: string; provider?: ProviderConfig_2; modelAlias?: string; modelCapabilities: ModelCapability; profileName?: string; thinkingEffort: string; systemPrompt: string; } declare type AgentConfigUpdateData = Partial<{ cwd: string; modelAlias: string; profileName: string; thinkingEffort: string; systemPrompt: string; }>; declare interface AgentContextData { history: readonly ContextMessage[]; tokenCount: number; } declare type AgentEntry = Agent | Promise; declare type AgentEvent = ErrorEvent | WarningEvent | AgentStatusUpdatedEvent | SessionMetaUpdatedEvent | SessionCreatedEvent | WorkspaceCreatedEvent | WorkspaceUpdatedEvent | WorkspaceDeletedEvent | SessionWorkChangedEvent | SessionStatusChangedEvent | ConfigChangedEvent | ModelCatalogChangedEvent | GoalUpdatedEvent | SkillActivatedEvent | PluginCommandActivatedEvent | TurnStartedEvent | TurnEndedEvent | TurnStepStartedEvent | TurnStepCompletedEvent | TurnStepRetryingEvent | TurnStepInterruptedEvent | AssistantDeltaEvent | HookResultEvent | ThinkingDeltaEvent | ToolCallDeltaEvent | ToolCallStartedEvent | ToolProgressEvent | ShellOutputEvent | ShellStartedEvent | ToolResultEvent | ToolListUpdatedEvent | McpServerStatusEvent | SubagentSpawnedEvent | SubagentStartedEvent | SubagentSuspendedEvent | SubagentCompletedEvent | SubagentFailedEvent | CompactionStartedEvent | CompactionBlockedEvent | CompactionCancelledEvent | CompactionCompletedEvent | TaskStartedEvent | TaskTerminatedEvent | BackgroundTaskStartedEvent | BackgroundTaskTerminatedEvent | CronFiredEvent | PromptSubmittedEvent | PromptCompletedEvent | PromptAbortedEvent | PromptSteeredEvent; declare interface AgentMeta { readonly homedir?: string; readonly type: AgentType; readonly parentAgentId?: string | null; readonly swarmItem?: string; } declare interface AgentOptions { readonly kaos: Kaos; readonly config?: KimiConfig; readonly homedir?: string; /** * Session-owned directory for pre-compression image originals * (`sessionMediaOriginalsDir(sessionDir)`), threaded to media-producing * paths (MCP tool results) so readback originals live with the session * rather than in the shared temp-dir fallback. */ readonly mediaOriginalsDir?: string; readonly rpc?: Partial; readonly persistence?: AgentRecordPersistence; readonly type?: AgentType; readonly generate?: typeof generate; readonly toolServices?: ToolServices; readonly compactionStrategy?: CompactionStrategy; readonly microCompaction?: Partial; readonly modelProvider?: ModelProvider | undefined; readonly subagentHost?: SessionSubagentHost | undefined; readonly skills?: SkillRegistry; readonly mcp?: McpConnectionManager; readonly hookEngine?: HookEngine; readonly permission?: PermissionManagerOptions | undefined; readonly log?: Logger; readonly telemetry?: TelemetryClient | undefined; readonly pluginSessionStarts?: readonly EnabledPluginSessionStart[]; readonly pluginCommands?: readonly PluginCommandDef[]; readonly experimentalFlags?: ExperimentalFlagResolver; /** Owner-scoped [image] limits; a standalone Agent gets env/built-in defaults. */ readonly imageLimits?: ImageLimits; readonly replay?: ReplayBuilderOptions; readonly additionalDirs?: readonly string[]; /** Botiverse mirror: standing-prompt (Raft role/context) → ROLE_ADDITIONAL. */ readonly roleAdditional?: string; readonly systemPromptContextProvider?: (() => Promise) | undefined; } declare type AgentPhase = { readonly kind: 'idle'; } | { readonly kind: 'running'; readonly turnId: number; readonly step: number; readonly stepId: string; readonly since: number; } | { readonly kind: 'streaming'; readonly turnId: number; readonly step: number; readonly stepId: string; readonly stream: 'assistant' | 'thinking' | 'tool_call'; readonly toolCallId?: string; readonly toolName?: string; readonly since: number; } | { readonly kind: 'tool_call'; readonly turnId: number; readonly step: number; readonly toolCallId: string; readonly name: string; readonly since: number; } | { readonly kind: 'retrying'; readonly turnId: number; readonly step: number; readonly stepId: string; readonly failedAttempt: number; readonly nextAttempt: number; readonly maxAttempts: number; readonly delayMs: number; readonly errorName?: string; readonly statusCode?: number; readonly since: number; } | { readonly kind: 'awaiting_approval'; readonly turnId: number; readonly step?: number; readonly approval?: unknown; readonly since: number; } | { readonly kind: 'interrupted'; readonly turnId: number; readonly step?: number; readonly reason: 'aborted' | 'max_steps' | 'error'; readonly message?: string; readonly at: number; } | { readonly kind: 'ended'; readonly turnId: number; readonly reason: TurnEndReason; readonly durationMs?: number; readonly at: number; }; declare type AgentRecord = { [K in keyof AgentRecordEvents]: Readonly & { readonly type: K; readonly time?: number; }; }[keyof AgentRecordEvents]; declare interface AgentRecordEvents { metadata: { protocol_version: string; created_at: number; }; forked: {}; 'turn.prompt': { input: readonly ContentPart[]; origin: PromptOrigin; }; 'turn.steer': { input: readonly ContentPart[]; origin: PromptOrigin; }; 'turn.cancel': { turnId?: number; }; 'config.update': AgentConfigUpdateData; 'permission.set_mode': { mode: PermissionMode_2; }; 'permission.record_approval_result': PermissionApprovalResultRecord; 'full_compaction.begin': CompactionBeginData; 'plan_mode.enter': { id: string; }; 'plan_mode.cancel': { id?: string; }; 'plan_mode.exit': { id?: string; }; 'swarm_mode.enter': { trigger: SwarmModeTrigger; }; 'swarm_mode.exit': {}; 'tools.register_user_tool': UserToolRegistration; 'tools.unregister_user_tool': { name: string; }; 'tools.set_active_tools': { names: readonly string[]; }; 'usage.record': { model: string; usage: TokenUsage_3; usageScope?: UsageRecordScope | undefined; }; 'full_compaction.cancel': {}; 'full_compaction.complete': {}; 'micro_compaction.apply': { cutoff: number; }; 'context.append_message': { message: ContextMessage; }; 'context.append_loop_event': { event: LoopRecordedEvent; }; 'context.update_token_count': { tokenCount: number; }; 'context.clear': {}; 'context.apply_compaction': CompactionResult; 'context.undo': { count: number; }; 'tools.update_store': ToolStoreUpdate; 'goal.create': { goalId: string; objective: string; completionCriterion?: string; }; 'goal.update': { status?: GoalStatus; tokensUsed?: number; turnsUsed?: number; wallClockMs?: number; budgetLimits?: GoalBudgetLimits; reason?: string; actor?: GoalActor; }; 'goal.clear': {}; /** * Content-addressed snapshot of a request's top-level `tools[]` (after the * `deferred` strip — exactly what the provider receives). Written once per * unique table; `llm.request.toolsHash` points here. */ 'llm.tools_snapshot': { hash: string; tools: readonly LlmRequestToolSchema[]; }; /** * One record per outbound model request (every retry attempt, strict * resend, and compaction round included). Together with `config.update` * (system prompt full text), context records (messages), and * `llm.tools_snapshot` (tool schemas), this makes each request * reconstructable from the wire log at the logical-request level. */ 'llm.request': { kind: 'loop' | 'compaction'; provider: string; model: string; modelAlias?: string; /** * Provider-effective thinking effort — for Kimi providers this is derived * from the request body's thinking payload, so env overrides * (`KIMI_MODEL_THINKING_EFFORT`) are already reflected. */ thinkingEffort?: ThinkingEffort; /** * Kimi preserved-thinking passthrough (`thinking.keep`) in effect for * this request — resolved from env, config, and the default, none of * which are otherwise recorded. */ thinkingKeep?: string; /** Effective env-driven sampling overrides (Kimi provider only). */ temperature?: number; topP?: number; /** * Effective completion-token cap the provider sends on the wire — read * from the effective provider, so provider-side clamping (remaining * context window, transport ceilings) and provider-level defaults (e.g. * Anthropic's required `max_tokens`) are included. */ maxTokens?: number; betaApi?: boolean; /** Progressive tool disclosure in effect (env flag × model capability). */ toolSelect: boolean; systemPromptHash: string; /** * Inlined only when the request's system prompt differs from the current * `config.update` value (no such caller today; defensive for future ones). */ systemPrompt?: string; toolsHash: string; messageCount: number; turnStep?: string; attempt?: string; /** Set when this request is a fallback resend (strict rebuild, * media-degraded rebuild, or media-stripped rebuild). */ projection?: 'strict' | 'media-degraded' | 'media-stripped'; /** Compaction only: messages dropped so far by overflow/empty shrinking. */ droppedCount?: number; }; /** * Raw MCP `tools/list` result as advertised by the server, plus how this * agent gated it (allow-list, name collisions). Written on registration, * deduplicated per server by content hash. */ 'mcp.tools_discovered': { serverName: string; hash: string; tools: readonly MCPToolDefinition[]; enabledNames: readonly string[]; collisions?: readonly McpToolCollision[]; }; } declare type AgentRecordOf = Extract; declare interface AgentRecordPersistence { read(): AsyncIterable; append(input: AgentRecord): void; rewrite(records: readonly AgentRecord[]): void; flush(): Promise; close(): Promise; } declare class AgentRecords { private readonly agent; private readonly persistence?; private _restoring; private metadataInitialized; private _replaying; /** * One-shot latch: the durable log is "open" once replay has completed (the * write-dedup cursors of observability records are restored) or, for agents * that never resume, once the first record has been logged live. Producers * of observability records (MCP discovery) park their writes until then — * logging earlier would both duplicate records that replay is about to * dedupe and append a stray metadata record ahead of replay. */ private _opened; private readonly onOpenedCallbacks; constructor(agent: Agent, persistence?: AgentRecordPersistence | undefined); get restoring(): RestoringContext | null; /** * Whether observability records may be written directly. False before the * log is opened (see `_opened`); producers should park and re-attempt from * an `onOpened` callback. Always true without persistence — there is no * durable log to protect. */ get observabilityReady(): boolean; /** * Register a callback fired once, when the log opens. Not fired for a * range-limited (frozen) replay — those agents are transient previews and * must not append new records. */ onOpened(callback: () => void): void; private markOpened; logRecord(record: AgentRecord): void; restore(record: AgentRecord): boolean; replay(options?: AgentRecordsReplayOptions): Promise<{ warning?: string; }>; flush(): Promise; } declare interface AgentRecordsReplayOptions { readonly rewriteMigratedRecords?: boolean; } export declare type AgentReplayRecord = { readonly time: number; } & AgentReplayRecordPayload; declare type AgentReplayRecordPayload = { type: 'message'; message: ContextMessage; } | { type: 'compaction'; result?: CompactionResult | 'cancelled'; instruction?: string; } | { type: 'goal_updated'; snapshot: GoalSnapshot; change: GoalChange | { readonly kind: 'created'; }; } | { type: 'plan_updated'; enabled: boolean; } | { type: 'config_updated'; config: AgentConfigUpdateData; } | { type: 'permission_updated'; mode: PermissionMode_2; } | { type: 'approval_result'; record: PermissionApprovalResultRecord; }; declare type AgentScopedPayload = T & { readonly agentId: string; }; export declare interface AgentStatusUpdatedEvent { readonly type: 'agent.status.updated'; readonly model?: string; readonly thinkingEffort?: string; readonly contextTokens?: number; readonly maxContextTokens?: number; readonly contextUsage?: number; readonly planMode?: boolean; readonly swarmMode?: boolean; readonly permission?: PermissionMode_3; readonly usage?: UsageStatus; readonly phase?: AgentPhase; } declare interface AgentTaskInfo extends TaskInfoBase { readonly kind: 'agent'; readonly agentId?: string; readonly subagentType?: string; } declare type AgentType = 'main' | 'sub' | 'independent'; declare interface Anthropic {} declare interface AnthropicOptions { apiKey?: string | undefined; baseUrl?: string | undefined; model: string; defaultMaxTokens?: number | undefined; betaFeatures?: string[] | undefined; defaultHeaders?: Record; metadata?: Record | undefined; /** Use streaming API. Defaults to true. Set to false for non-streaming (test/fallback). */ stream?: boolean | undefined; /** * Explicitly declare whether the model supports adaptive thinking * (`thinking: { type: 'adaptive' }`), overriding the model-name version * inference. Useful for custom-named endpoints whose model name does not * encode a parseable Claude version. Leave undefined to infer from the name. */ adaptiveThinking?: boolean | undefined; /** * Concrete thinking efforts declared by the model catalog. When omitted, * the provider infers a Claude profile from the model name and falls back to * the latest Opus profile for unrecognized Anthropic-compatible models. */ supportEfforts?: readonly string[] | undefined; kimiThinking?: boolean | undefined; /** * Use the Anthropic **beta** Messages API (`client.beta.messages.create`, * `POST /v1/messages?beta=true`) instead of the standard Messages API. * * Beta features (`betaFeatures`) are then sent via the request `betas` * field rather than the `anthropic-beta` header. Defaults to false, which * keeps the standard endpoint + header behavior. */ betaApi?: boolean | undefined; clientFactory?: (auth: ProviderRequestAuth) => Anthropic; } /** * Writes a catalog-selected provider and its model aliases into `config` and * marks it the default. Model metadata (context, output limit, capabilities) * comes from the catalog, so the user does not hand-write it. Returns the * default model key. * * NOTE: the same-provider cleanup below mutates the passed-in `config` only. * It clears stale aliases on disk solely when the caller overwrites the whole * config. Callers persisting via `setConfig` — a deep-merge patch that cannot * delete keys — must call `removeProvider` first, or removed aliases reappear * after the merge. */ export declare function applyCatalogProvider(config: KimiConfig, options: ApplyCatalogProviderOptions): { defaultModel: string; }; export declare interface ApplyCatalogProviderOptions { readonly providerId: string; readonly wire: ProviderType_2; readonly baseUrl?: string; readonly apiKey: string; readonly models: readonly CatalogModel[]; readonly selectedModelId: string; readonly thinking: boolean; } export declare type ApprovalDecision = 'approved' | 'rejected' | 'cancelled'; export declare type ApprovalHandler = (request: ApprovalRequest) => MaybePromise; export declare interface ApprovalRequest { readonly turnId?: number | undefined; readonly toolCallId: string; readonly toolName: string; readonly action: string; readonly display: ToolInputDisplay; } export declare interface ApprovalResponse { readonly decision: ApprovalDecision; readonly scope?: ApprovalScope | undefined; readonly feedback?: string | undefined; readonly selectedLabel?: string | undefined; } declare interface ApprovalResponse_2 { decision: 'approved' | 'rejected' | 'cancelled'; scope?: 'session'; feedback?: string; selectedLabel?: string; } export declare type ApprovalScope = 'session'; declare interface ArchiveSessionPayload { readonly sessionId: string; } export declare interface AssistantDeltaEvent { readonly type: 'assistant.delta'; readonly turnId: number; readonly delta: string; } declare interface AudioURLPart { type: 'audio_url'; audioUrl: { url: string; id?: string; }; } export declare interface AuthenticateMcpServerOptions { readonly onAuthorizationUrl: (url: string) => void | boolean | PromiseLike; readonly signal?: AbortSignal; readonly timeoutMs?: number; } declare type AuthManagedUsageResult = { readonly kind: 'ok'; readonly summary: ParsedManagedUsage['summary']; readonly limits: ParsedManagedUsage['limits']; readonly extraUsage: ParsedManagedUsage['extraUsage']; } | FetchManagedUsageError; declare type AuthorizedRequest = (request: (auth: ProviderRequestAuth) => Promise) => Promise; declare interface AuthorizeToolExecutionResult { readonly block?: boolean | undefined; readonly reason?: string | undefined; readonly syntheticResult?: ExecutableToolResult | undefined; readonly executionMetadata?: unknown; } declare interface AuthProviderStatus { readonly providerName: string; readonly hasToken: boolean; } declare interface AuthStatus { readonly providers: readonly AuthProviderStatus[]; } export declare type BackgroundConfig = z.infer; declare const BackgroundConfigSchema: z.ZodObject<{ maxRunningTasks: z.ZodOptional; keepAliveOnExit: z.ZodOptional; bashAutoBackgroundOnTimeout: z.ZodOptional; bashTaskTimeoutS: z.ZodOptional; killGracePeriodMs: z.ZodOptional; printWaitCeilingS: z.ZodOptional; printBackgroundMode: z.ZodOptional>; printMaxTurns: z.ZodOptional; }, z.core.$strip>; declare class BackgroundManager { private readonly agent; private readonly persistence?; private readonly tasks; /** * Ghosts: tasks loaded from disk during reconcile that have no live * KaosProcess. They appear in `list()` / `getTask()` with status * `lost` so users see what was running before the crash/restart. */ private readonly ghosts; private readonly scheduledNotificationKeys; private readonly deliveredNotificationKeys; constructor(agent: Agent, persistence?: BackgroundTaskPersistence | undefined); private fireTerminalEffects; private emitTaskStarted; private emitTaskTerminated; private assertCanRegister; private activeBackgroundAdmissionCount; private startedInBackground; private isDetached; /** * Foreground tasks opted into auto-background survive their first deadline * by detaching to the background instead of being killed. */ private canAutoBackgroundOnTimeout; registerTask(task: BackgroundTask, options?: RegisterBackgroundTaskOptions): string; /** Get info about a specific task. Falls back to reconcile ghosts. */ getTask(taskId: string): BackgroundTaskInfo | undefined; /** * List tasks, optionally filtering to active-only. * * When `activeOnly=false`, includes reconcile ghosts (lost tasks * from a prior CLI process) so the user sees what survived the * restart. Active-only mode never shows ghosts (they're terminal). */ list(activeOnly?: boolean, limit?: number): BackgroundTaskInfo[]; private shouldListTask; /** * Return the output snapshot used by TaskOutput. * * Persisted logs are preferred when the task was registered with an * output session directory and `output.log` has actually been created, * because they are the complete, never-truncated source. Detached managers, * tasks registered before a session dir was attached, and silent tasks with * no persisted log fall back to the live ring buffer. */ getOutputSnapshot(taskId: string, maxPreviewBytes: number): Promise; readOutput(taskId: string, tail?: number): Promise; suppressTerminalNotification(taskId: string): Promise; /** * Move a foreground task to the background, releasing its tool-call waiter. * `viaTimeout` marks an automatic detach triggered by the task deadline (vs. * an explicit user/RPC detach) so the waiter can word its result. */ detach(taskId: string, viaTimeout?: boolean): BackgroundTaskInfo | undefined; persistOutput(taskId: string): void; /** Stop a running task. SIGTERM → 5s grace → SIGKILL. */ stop(taskId: string, reason?: string): Promise; stopAll(reason?: string): Promise; /** * Wait for a task to reach a terminal state. * Returns immediately if already terminal. Times out after `timeoutMs`. */ wait(taskId: string, timeoutMs?: number): Promise; /** * Wait until no active (non-terminal) task matching `predicate` remains. * * Used by print-mode (`kimi -p`) turn draining to hold a turn open while * background subagents are still running. Re-enumerates after each batch * settles so tasks registered during the wait (fan-out) are picked up. * Resolves immediately when nothing matches. Bounded by `timeoutMs`; once * the deadline passes the method returns without waiting for stragglers. * Rejects with the abort reason when `signal` is aborted. */ waitForActiveTasks(predicate: (info: BackgroundTaskInfo) => boolean, options?: { timeoutMs?: number; signal?: AbortSignal; }): Promise; /** * Wait until a foreground task either detaches from the current tool call or * reaches a terminal state. Detached tasks return immediately. */ waitForForegroundRelease(taskId: string): Promise; /** * Load persisted task records into the ghost map. Does NOT reconcile * (call `reconcile()` after `loadFromDisk()`). Idempotent; subsequent * calls overwrite the ghost map. */ loadFromDisk(): Promise; /** * Reconcile loaded ghost tasks. Any ghost with status `running` is * reclassified as `lost` (its previous CLI process died without * writing a terminal state). Updates the on-disk record and returns * the lost task snapshots so the caller can emit user-facing notifications. */ private markLoadedTasksLost; reconcile(): Promise; /** * Persist the current state of a live ManagedTask. Called from * `registerTask()` and the lifecycle finally block. No-op unless attached. */ private persistLive; private appendOutput; /** Enqueue an `output.log` append, serialized per task. No-op when detached managers omit persistence. */ private appendTaskOutput; /** * Begin persisting `output.log` for a task that buffered while foreground. * Flushes the buffered pre-detach output first (in order, ahead of the live * stream) so the on-disk log stays complete, then releases the buffer. * Idempotent. */ private startOutputPersist; private restoreBackgroundTaskNotifications; private notifyBackgroundTask; private restoreBackgroundTaskNotification; private buildBackgroundTaskNotificationContext; private fireNotificationHook; markDeliveredNotification(origin: BackgroundTaskOrigin): void; private isTerminalNotificationSuppressed; private runTaskLifecycle; private signalOutcome; private settlementForOutcome; private finalizeTask; private toInfo; } declare interface BackgroundTask { readonly idPrefix: string; readonly kind: BackgroundTaskInfo['kind']; readonly description: string; readonly timeoutMs?: number; start(sink: BackgroundTaskSink): void | Promise; onDetach?(): void; forceStop?(): Promise; toInfo(base: BackgroundTaskInfoBase): BackgroundTaskInfo; } export declare type BackgroundTaskInfo = ProcessBackgroundTaskInfo | AgentBackgroundTaskInfo | QuestionBackgroundTaskInfo; declare interface BackgroundTaskInfoBase { readonly taskId: string; readonly description: string; readonly status: BackgroundTaskStatus; /** * `false` means a tool call is still waiting on this task in the * foreground. Omitted legacy records should be treated as detached. */ readonly detached?: boolean; readonly startedAt: number; readonly endedAt: number | null; /** Human-readable reason for the terminal status, when available. */ readonly stopReason?: string; /** Suppress automatic terminal notifications/reminders for this task. */ readonly terminalNotificationSuppressed?: boolean; /** Deadline supplied at registration; surfaced via task info. */ readonly timeoutMs?: number; } declare interface BackgroundTaskOrigin { readonly kind: 'background_task'; readonly taskId: string; readonly status: BackgroundTaskStatus; readonly notificationId: string; } /** * Legacy spelling of `TaskOrigin` emitted by the pre-v2 agent core, which * identifies background-task notifications with `kind: 'background_task'`. * Retained so the wire `PromptOrigin` accepts turns steered by the legacy * engine; new code should emit `TaskOrigin` (`kind: 'task'`). */ declare interface BackgroundTaskOrigin_2 { readonly kind: 'background_task'; readonly taskId: string; readonly status: TaskLifecycleStatus; readonly notificationId: string; } declare interface BackgroundTaskOutputSnapshot { readonly outputPath?: string; readonly outputSizeBytes: number; readonly previewBytes: number; readonly truncated: boolean; readonly fullOutputAvailable: boolean; readonly preview: string; } declare class BackgroundTaskPersistence { private readonly sessionDir; private readonly store; constructor(sessionDir: string); taskOutputFile(taskId: string): string; /** Atomically write a task's persisted state. Creates dirs as needed. */ writeTask(task: PersistedTask): Promise; /** Read a single task file. Returns undefined when missing/corrupt/unrecognized. */ readTask(taskId: string): Promise; appendTaskOutput(taskId: string, chunk: string): Promise; /** * Total byte size of a task's `output.log`. Returns 0 when the log does * not exist yet (the task has produced no output, or is unknown). * * This is the authoritative full-output size — unlike the in-memory ring * buffer it is never truncated, so callers can report how much output a * task has actually produced. */ taskOutputSizeBytes(taskId: string): Promise; taskOutputExists(taskId: string): Promise; /** * Read a byte window of a task's `output.log`. * * Reads at most `maxBytes` bytes starting at byte `offset`. A window that * runs past EOF is clamped to whatever remains; an `offset` at/after EOF * yields an empty string. Returns an empty string when the log is absent. * * Byte-level (not line-level) paging mirrors how the full log is stored * on disk, so callers can page arbitrarily large logs without loading the * whole file into memory. */ readTaskOutputBytes(taskId: string, offset: number, maxBytes: number): Promise; /** * Enumerate all persisted tasks for a session. * * Skips, silently: * - basenames that don't match `VALID_TASK_ID` (stray files, legacy * `bg_*` leftovers, partially-written temp files); * - files that fail to read / parse; * - records that are neither identifiable as the current camelCase * shape nor the previous snake_case task shape. * * Legacy snake_case records are normalized to current `BackgroundTaskInfo` * in memory. The next lifecycle/reconcile write stores them back in the * current format, so compatibility is read-only and opportunistically * migrates without a separate migration step. * * `writeTask` uses atomic temp+rename so a genuinely truncated file in * production is rare; if it happens we accept the loss rather than * emit a ghost with no recoverable metadata beyond the filename. */ listTasks(): Promise; } declare interface BackgroundTaskSettlement { readonly status: BackgroundTaskSettlementStatus; /** Human-readable reason for the terminal status, when available. */ readonly stopReason?: string; } declare type BackgroundTaskSettlementStatus = 'completed' | 'failed' | 'timed_out' | 'killed'; declare interface BackgroundTaskSink { readonly signal: AbortSignal; appendOutput(chunk: string): void; settle(settlement: BackgroundTaskSettlement): Promise; } /** * Legacy background-task lifecycle events emitted by the pre-v2 agent core * (`background.task.started` / `background.task.terminated`). The v2 engine * emits `task.started` / `task.terminated` instead; both spellings are kept in * the union so clients see a consistent event stream across engines. */ export declare interface BackgroundTaskStartedEvent { readonly type: 'background.task.started'; readonly info: TaskInfo; } export declare type BackgroundTaskStatus = 'running' | 'completed' | 'failed' | 'timed_out' | 'killed' | 'lost'; export declare interface BackgroundTaskTerminatedEvent { readonly type: 'background.task.terminated'; readonly info: TaskInfo; } declare type BaseQueuedSubagentTask = { readonly data: T; readonly profileName: string; readonly parentToolCallId: string; readonly parentToolCallUuid?: string; readonly prompt: string; readonly description: string; readonly swarmIndex?: number; readonly swarmItem?: string; readonly runInBackground: boolean; readonly timeout?: number; readonly signal?: AbortSignal; }; declare interface BearerTokenProvider { getAccessToken(options?: { readonly force?: boolean | undefined; }): Promise; } declare interface BearerTokenProvider_2 { getAccessToken(options?: { readonly force?: boolean; }): Promise; } declare interface BeginAuthorizationOptions { /** Override the `client_name` embedded in the DCR registration request. */ readonly clientLabel?: string; } declare interface BeginAuthorizationResult { /** The authorization URL the user must open in their browser. */ readonly authorizationUrl: URL; /** * Awaits the OAuth callback, validates `state`, exchanges the code for * tokens, and persists them via the provider. Resolves on success; * rejects on abort, timeout, or auth-server error. */ complete(opts?: { signal?: AbortSignal; timeoutMs?: number; }): Promise; /** * Tears down the callback listener without finishing the flow. Safe to * call repeatedly; called automatically by `complete()`. */ cancel(): Promise; } declare interface BeginCompactionPayload { readonly instruction?: string; } declare type BeginGlobalMcpServerAuthResult = { readonly status: 'already-authorized'; } | { readonly status: 'authorization-required'; readonly flowId: string; readonly authorizationUrl: string; }; declare class BlobStore { private readonly blobsDir; private readonly threshold; private readonly maxCacheSize; private readonly cache; private readonly cacheSizes; private currentCacheSize; constructor(options: BlobStoreOptions); offload(record: AgentRecord): Promise; private offloadParts; rehydrate(record: AgentRecord): Promise; rehydrateParts(parts: readonly ContentPart[]): Promise; private offloadContentPart; private rehydrateContentPart; private rehydrateBlobRefUrl; private readBlob; private maybeOffloadString; private writeBlob; private setCache; private evictLRU; } declare interface BlobStoreOptions { readonly blobsDir: string; readonly threshold?: number; readonly maxCacheSize?: number; } declare interface BoosterWalletInfo { /** Remaining balance in whole cents (from balance.amountLeft). */ readonly balanceCents: number; /** Total balance in whole cents (from balance.amount). */ readonly totalCents: number; /** Whether the user enabled a monthly spending cap. */ readonly monthlyChargeLimitEnabled: boolean; /** Monthly spending cap in whole cents; 0 means unlimited. */ readonly monthlyChargeLimitCents: number; /** Monthly spend so far in whole cents. */ readonly monthlyUsedCents: number; /** ISO currency code, e.g. USD / CNY. */ readonly currency: string; } /** * Render the shared `` note placed next to a compressed image so the * model knows it is looking at a downsampled copy: what the original was, what * was actually sent, and — when the original is on disk — where to read it * back (via ReadMediaFile `region`) for full-fidelity detail. * * Two channels consume this note differently: * - Tool results (MCP images): {@link compressImageContentParts} returns * the captions as data and the MCP output pipeline joins them into the * result's `note` side channel (rendered to the model at projection * time, never to UIs). * - User prompts must not render raw `` markup in the UI, so the * context layer detects the caption via * {@link extractImageCompressionCaptions} and reroutes it through the * built-in system-reminder injection (hidden by its `injection` origin). */ export declare function buildImageCompressionCaption(input: ImageCompressionCaptionInput): string; /** * Short notice standing in for an unsupported image where there is no file * path to point at (MCP tool results, prompt uploads): the image part is * dropped and this text replaces it, so the model knows what happened and * the session history stays free of formats the provider rejects. */ export declare function buildUnsupportedImageNotice(mimeType: string, name?: string): string; declare type BuiltinTool = ExecutableTool; declare interface CancelGlobalMcpServerAuthPayload { readonly flowId: string; } declare interface CancelPayload { readonly turnId?: number; } declare interface CancelPlanPayload { readonly id?: string; } declare interface CancelShellCommandPayload { readonly commandId: string; } /** Top-level catalog: `{ [providerId]: ProviderEntry }` (e.g. models.dev/api.json). */ export declare type Catalog = Record; /** * Resolves the base URL to store for a catalog provider, adapting the catalog's * `api` to the wire's SDK convention. * * models.dev `api` URLs are written for the SDK named in `npm` (e.g. * `@ai-sdk/anthropic`), whose base already includes the `/v1` version segment. * We route the `anthropic` wire through the official `@anthropic-ai/sdk`, which * appends `/v1/messages` itself — so a catalog `api` ending in `/v1` would POST * to `/v1/v1/messages` (404). Strip the trailing `/v1` for anthropic. OpenAI * family SDKs append `/chat/completions` to a `/v1` base, so those pass through. */ export declare function catalogBaseUrl(entry: CatalogProviderEntry, wire: ProviderType_2): string | undefined; export declare class CatalogFetchError extends Error { readonly status: number; constructor(message: string, status: number); } /** A normalized catalog model: identity plus its {@link ModelCapability}. */ export declare interface CatalogModel { readonly id: string; readonly name?: string; readonly maxOutputSize?: number; readonly reasoningKey?: string; readonly capability: ModelCapability; } /** * models.dev-style catalog: a public map of provider/model metadata. Callers * consume a snapshot of this shape to populate provider + model configuration * without hand-writing context windows or capabilities. */ declare interface CatalogModelEntry { readonly id?: string; readonly name?: string; readonly family?: string; readonly limit?: { readonly context?: number; readonly output?: number; }; readonly tool_call?: boolean; readonly reasoning?: boolean; /** Accepts message-level tool declarations (`messages[].tools`). Defaults to false. */ readonly dynamically_loaded_tools?: boolean; readonly interleaved?: boolean | { readonly field?: string; }; readonly modalities?: { readonly input?: readonly string[]; readonly output?: readonly string[]; }; } /** Builds a kimi-code model alias from a normalized catalog model. */ export declare function catalogModelToAlias(providerId: string, model: CatalogModel): ModelAlias; export declare interface CatalogProviderEntry { readonly id?: string; readonly name?: string; /** Base URL for the provider; may be empty (some SDKs hardcode it). */ readonly api?: string; /** Env var names carrying credentials — surfaced as a hint by callers. */ readonly env?: readonly string[]; /** models.dev SDK package id; used to infer the wire type when `type` is absent. */ readonly npm?: string; /** Explicit wire type extension; inferred from `npm`/`id` when absent. */ readonly type?: string; readonly models?: Record; } /** Extracts the valid, normalized models from a catalog provider entry. */ export declare function catalogProviderModels(entry: CatalogProviderEntry): CatalogModel[]; /** * Unified interface for an LLM chat provider. * * Each provider implementation (Kimi, OpenAI, Anthropic, Google GenAI, etc.) * converts the common {@link Message} / {@link Tool} types into the * provider-specific wire format, streams back a {@link StreamedMessage}, and * exposes configuration helpers such as {@link withThinking}. */ declare interface ChatProvider { /** Short identifier for the provider backend (e.g. `"kimi"`, `"anthropic"`). */ readonly name: string; /** Model name passed to the upstream API (e.g. `"moonshot-v1-auto"`). */ readonly modelName: string; /** Current thinking effort, or `null` if thinking is not configured. */ readonly thinkingEffort: ThinkingEffort | null; /** * The effective completion-token cap this instance will send on the wire, * derived from its generation kwargs — covering constructor defaults (e.g. * Anthropic's required `max_tokens`), direct kwargs configuration, and * {@link withMaxCompletionTokens} (after any implementation-side clamping: * remaining context window, transport ceilings, model-default resolution). * `undefined` when the instance sends no cap. Read by hosts that record * the outbound request, so the recorded value matches what the provider * actually sends. */ readonly maxCompletionTokens?: number; /** * Send a conversation to the LLM and return a streamed response. * * @param systemPrompt - System-level instruction prepended to the request. * @param tools - Tool definitions the model may invoke. * @param history - The conversation history (user, assistant, tool messages). * @param options - Optional per-call settings such as an {@link AbortSignal}. */ generate(systemPrompt: string, tools: Tool[], history: Message[], options?: GenerateOptions): Promise; /** Return a shallow copy of this provider with the given thinking effort. */ withThinking(effort: ThinkingEffort): ChatProvider; /** * Return a shallow copy of this provider with the per-request completion * budget clamped to `maxCompletionTokens`. Optional because not every * backend benefits from a client-computed cap. * * When `options` are provided, implementations may further tighten the cap * based on their own transport constraints — e.g. chat-completions * endpoints size the cap to the remaining context window * (`maxContextTokens - usedContextTokens`) and/or clamp to a fixed ceiling. * * Implementations MUST NOT mutate or replace internal HTTP clients on the * returned clone — the clone is expected to share transport state with the * original. See `KimiChatProvider._clone()` for the rationale. */ withMaxCompletionTokens?(maxCompletionTokens: number, options?: MaxCompletionTokensOptions): ChatProvider; /** Upload a video and return a content part that can be sent to this provider. */ uploadVideo?(input: string | VideoUploadInput, options?: GenerateOptions): Promise; } declare interface ClientTelemetryInfo { readonly id?: string | undefined; readonly name?: string | undefined; readonly version?: string | undefined; readonly uiMode?: string | undefined; } declare interface ClockSources { /** * Wall-clock epoch milliseconds. May be overridden in tests / bench * via `KIMI_CRON_CLOCK`. Used for cron matching, `createdAt`, stale * judgment. */ wallNow(): number; /** * Strictly monotonic millisecond counter. Never overridden. Used for * the 1-second poll cadence and the lock-heartbeat liveness window. */ monoNowMs(): number; } declare interface CloseSessionPayload { readonly sessionId: string; } declare interface CompactionBeginData { instruction?: string; source: CompactionSource; } export declare interface CompactionBlockedEvent { readonly type: 'compaction.blocked'; readonly turnId?: number; } export declare interface CompactionCancelledEvent { readonly type: 'compaction.cancelled'; } export declare interface CompactionCompletedEvent { readonly type: 'compaction.completed'; readonly result: CompactionResult_2; } /** * Inputs `ContextMemory.applyCompaction` needs to derive a `CompactionResult`. * `tokensAfter` / `keptUserMessageCount` / `droppedCount` are optional: the live * path fills in what it knows, while restore passes the persisted record so its * historical values are preserved verbatim. */ declare type CompactionInput = Pick & Partial>; export declare interface CompactionResult { /** Human-facing summary text produced by the compaction model. */ summary: string; /** * Exact summary message stored in the live model context. It includes the * compaction prefix that tells the next model this is handoff context rather * than a real user prompt. Optional for backward compatibility with older * wire records, where `summary` was also the model-context text. */ contextSummary?: string; compactedCount: number; tokensBefore: number; tokensAfter: number; /** * Number of real user messages kept verbatim ahead of the summary in the * post-compaction live context. Written by `ContextMemory.applyCompaction` * (the single derivation point for the post-compaction shape) so the * wire-transcript reducer can reproduce the live folded length without * re-deriving it from the full transcript. Optional for backward * compatibility with older wire records. */ keptUserMessageCount?: number; /** * Of `keptUserMessageCount`, how many messages form the HEAD segment (the * oldest user input kept when the pool overflowed the budget). Present iff * the selection split into head + tail, in which case the live context also * holds one elision-marker message between the segments (so its length is * `keptUserMessageCount + 2` including the summary). Its presence is also * what tells restore to use the head/tail selection; records without it * restore with the pre-split tail-only selection that produced them. */ keptHeadUserMessageCount?: number; /** * Number of oldest messages trimmed from the summarizer input when the * compaction request itself overflowed the model window. These messages are * not covered by the produced summary — a real-user message among them may * still be retained verbatim in the live context via `keptUserMessageCount`, * but assistant/tool messages are lost. Surfacing the count lets records and * telemetry report the summary's blind spot honestly. Optional for backward * compatibility with older wire records. */ droppedCount?: number; } declare interface CompactionResult_2 { readonly summary: string; readonly compactedCount: number; readonly tokensBefore: number; readonly tokensAfter: number; /** * Number of real user messages kept verbatim ahead of the summary in the * post-compaction live context. Recorded so the wire-transcript reducer can * reproduce the live folded length without re-deriving it from the full * transcript (which still holds the untruncated originals of messages the * live context may have truncated, so the two would otherwise diverge). * Optional for backward compatibility with older wire records. */ readonly keptUserMessageCount?: number; /** * Of `keptUserMessageCount`, how many messages form the head segment (the * oldest user input kept when the pool overflowed the budget). Present iff * the selection split into head + tail, in which case the live context also * holds one elision-marker message between the segments. Optional for * backward compatibility with older wire records. */ readonly keptHeadUserMessageCount?: number; /** * Oldest messages trimmed from the summarizer input when the compaction * request overflowed the model window; not covered by the produced summary. * Mirrors agent-core's `CompactionResult.droppedCount`; optional for backward * compatibility. */ readonly droppedCount?: number; } declare type CompactionSource = 'manual' | 'auto'; export declare interface CompactionStartedEvent { readonly type: 'compaction.started'; readonly trigger: 'manual' | 'auto'; readonly instruction?: string; } declare interface CompactionStrategy { shouldCompact(usedSize: number): boolean; shouldBlock(usedSize: number): boolean; readonly checkAfterStep: boolean; readonly maxCompactionPerTurn: number; readonly maxOverflowCompactionAttempts: number; } declare interface CompactionSummaryOrigin { readonly kind: 'compaction_summary'; } declare interface CompactionSummaryOrigin_2 { readonly kind: 'compaction_summary'; } export declare interface CompactOptions { readonly instruction?: string | undefined; } declare interface CompleteGlobalMcpServerAuthPayload { readonly flowId: string; readonly timeoutMs?: number; } /** Completion-token budget for the next LLM request. */ declare interface CompletionBudgetConfig { /** Explicit user-configured maximum. */ readonly hardCap?: number; /** Conservative cap for providers/models whose context window is unknown. */ readonly fallback?: number; } /** * Convenience wrapper for call sites that already hold base64 (MCP results, * data URLs). Decodes, compresses, and re-encodes to base64. Best effort: * returns the original base64 unchanged on any failure — including formats it * cannot re-encode, so callers must refuse MIME types outside the * provider-accepted set (`isModelAcceptedImageMime`) before building an * image part from the result. */ export declare function compressBase64ForModel(base64: string, mimeType: string, options?: CompressImageOptions): Promise; export declare interface CompressBase64Result { readonly base64: string; readonly mimeType: string; /** Pixel width of the (possibly re-encoded) payload; 0 when unknown. */ readonly width: number; /** Pixel height of the (possibly re-encoded) payload; 0 when unknown. */ readonly height: number; /** * Pixel width of the input image, in display space (EXIF orientation * applied): the decoded width when re-encoded, the header sniff on * passthrough (0 when it cannot be determined). */ readonly originalWidth: number; /** Pixel height of the input image; see {@link originalWidth}. */ readonly originalHeight: number; readonly changed: boolean; readonly originalByteLength: number; readonly finalByteLength: number; } /** * Downsample/re-encode `bytes` to fit the pixel + byte budget. * * Never throws: on any failure (unsupported format, decode error, a result * that would be larger than the input) the original bytes are returned with * `changed: false`. */ export declare function compressImageForModel(bytes: Uint8Array, mimeType: string, options?: CompressImageOptions): Promise; export declare interface CompressImageOptions { /** * Override the longest-edge ceiling (px). When omitted, owned call sites * pass their {@link ImageLimits.maxEdgePx}; ownerless ones fall back to * {@link resolveMaxImageEdgePx} (env var, then built-in). */ readonly maxEdge?: number; /** Override the raw-byte budget. */ readonly byteBudget?: number; /** Override the raw-byte ceiling above which compression is skipped. */ readonly maxDecodeBytes?: number; /** * Report an `image_compress` event per compression call (and an * `image_crop` event per {@link cropImageForModel} call). Absent → silent. */ readonly telemetry?: ImageCompressionTelemetry; } export declare interface CompressImageResult { /** Bytes to send: the re-encoded image, or the original when unchanged. */ readonly data: Uint8Array; /** MIME of `data`. May differ from the input (e.g. png → jpeg). */ readonly mimeType: string; /** Pixel width of `data`; falls back to the input size when unknown. */ readonly width: number; /** Pixel height of `data`; falls back to the input size when unknown. */ readonly height: number; /** * Pixel width of the input image, in display space (EXIF orientation * applied): the decoded width when re-encoded, the header sniff on * passthrough (0 when it cannot be determined). */ readonly originalWidth: number; /** Pixel height of the input image; see {@link originalWidth}. */ readonly originalHeight: number; /** True only when `data` differs from the input bytes. */ readonly changed: boolean; readonly originalByteLength: number; readonly finalByteLength: number; } declare interface ConfigChangedEvent { readonly type: 'event.config.changed'; readonly changedFields: string[]; readonly config: ConfigResponse; } export declare interface ConfigDiagnostics { /** Warnings from the most recent config.toml load attempt; empty when the config is fully valid. */ readonly warnings: readonly string[]; } declare type ConfigResponse = z.infer; declare const configResponseSchema: z.ZodObject<{ providers: z.ZodDefault; default_model: z.ZodOptional; has_api_key: z.ZodBoolean; }, z.core.$strip>>>; default_provider: z.ZodOptional; default_model: z.ZodOptional; models: z.ZodOptional>; thinking: z.ZodOptional; plan_mode: z.ZodOptional; yolo: z.ZodOptional; default_permission_mode: z.ZodOptional; default_plan_mode: z.ZodOptional; permission: z.ZodOptional; hooks: z.ZodOptional>; services: z.ZodOptional; merge_all_available_skills: z.ZodOptional; extra_skill_dirs: z.ZodOptional>; loop_control: z.ZodOptional; background: z.ZodOptional; experimental: z.ZodOptional>; telemetry: z.ZodOptional; raw: z.ZodOptional>; }, z.core.$strip>; declare class ConfigState { protected readonly agent: Agent; private _cwd; private _modelAlias; private _profileName; private _unforcedThinkingEffort; private _thinkingEffort; private _systemPrompt; constructor(agent: Agent); update(changed: AgentConfigUpdateData): void; setThinkingEffort(effort: ThinkingEffort): void; data(): AgentConfigData; get cwd(): string; get hasModel(): boolean; get hasProvider(): boolean; get providerConfig(): ProviderConfig_2; get provider(): ChatProvider; get model(): string; get modelAlias(): string | undefined; get thinkingEffort(): ThinkingEffort; private get currentModel(); private modelForThinking; get profileName(): string | undefined; get systemPrompt(): string; get modelCapabilities(): ModelCapability; get maxOutputSize(): number | undefined; private get resolvedProviderConfig(); private tryResolvedProviderConfig; private tryResolvedProviderConfigFor; } /** * A single piece of content within a {@link Message}. * * The union covers text, model reasoning ("think"), images, audio, and video. * Providers convert these to their native content-block format during * {@link ChatProvider.generate}. */ export declare type ContentPart = TextPart | ThinkPart | ImageURLPart | AudioURLPart | VideoURLPart; declare class ContextMemory { protected readonly agent: Agent; private _history; private _tokenCount; private tokenCountCoveredMessageCount; private openSteps; private pendingToolResultIds; private deferredMessages; private _lastAssistantAt; private lastProjectionRepairSignature; constructor(agent: Agent); get lastAssistantAt(): number | null; appendUserMessage(content: readonly ContentPart[], origin?: PromptOrigin): void; appendSystemReminder(content: string, origin: PromptOrigin): void; /** * Inject a user-invisible message and immediately send it to the model by * launching/steering a turn. The content is used as-is (no wrapper tag), so * callers can pass raw tool-result-style text or wrap it themselves. The * message is skipped on replay / transcript (so the user never sees it) but * is included in the context sent to the model. Use this for events the * model must react to right away without surfacing a user-visible message. */ injectAndNotify(content: string, origin?: PromptOrigin): void; appendLocalCommandStdout(content: string): void; appendBashInput(command: string): void; appendBashOutput(stdout: string, stderr: string, isError?: boolean): void; popMatchedMessage(matcher: (origin: PromptOrigin | undefined) => boolean): boolean; clear(): void; importContext(content: string, source: string): void; updateTokenCount(tokenCount: number): void; undo(count: number): void; applyCompaction(input: CompactionInput): CompactionResult; data(): AgentContextData; get tokenCount(): number; get tokenCountWithPending(): number; get history(): readonly ContextMessage[]; project(messages: readonly ContextMessage[], options?: ProjectOptions): Message[]; private reportProjectionRepairs; get messages(): Message[]; get strictMessages(): Message[]; get mediaDegradedMessages(): Message[]; /** * Compatibility projection that strips every media part visible now. Turn * recovery uses its own captured snapshot so newly produced media can pass; * direct callers retain the historical all-current-media behavior here. */ get mediaStrippedMessages(): Message[]; useProjectedHistoryFrom(source: ContextMemory): void; finishResume(): void; private closePendingToolResults; /** * Defensive teardown for a live turn that ended — normally, cancelled, or * failed — while recorded tool calls were still awaiting results (e.g. the * batch's result dispatch died after a `tool.call` was already recorded). * Synthesizes an error result for each dangling call so the exchange closes: * left open, it would keep `hasOpenToolExchange` true and strand every later * message in `deferredMessages`, silently swallowing user input. No-op when * the exchange is already closed. Returns the number of calls it closed. */ closeAbandonedToolExchange(output: string): number; appendLoopEvent(event: LoopRecordedEvent): void; appendMessage(message: ContextMessage): void; private flushDeferredMessagesIfToolExchangeClosed; private hasOpenToolExchange; private pushHistory; } export declare type ContextMessage = Message & { readonly origin?: PromptOrigin | undefined; readonly isError?: boolean; /** * UI-only input displays keyed by tool call id. These are rebuilt from the * persisted loop events for resume/replay and stripped before provider calls. */ toolCallDisplays?: Record; /** * Tool-result side channel rendered to the model but never to UIs; see * `ExecutableToolResult.note`. Appended to the projected tool message at * the provider boundary and stripped from the wire message itself. */ readonly note?: string; }; declare interface CoreAPI extends SessionAPIWithId { getCoreInfo: (payload: EmptyPayload) => CoreInfo; getExperimentalFeatures: (payload: EmptyPayload) => readonly ExperimentalFeatureState[]; getKimiConfig: (payload: GetKimiConfigPayload) => KimiConfig; getConfigDiagnostics: (payload: EmptyPayload) => ConfigDiagnostics; setKimiConfig: (payload: SetKimiConfigPayload) => KimiConfig; removeKimiProvider: (payload: RemoveKimiProviderPayload) => KimiConfig; listGlobalMcpServers: (payload: EmptyPayload) => readonly McpServerConfig[]; addGlobalMcpServer: (payload: PutGlobalMcpServerPayload) => readonly McpServerConfig[]; updateGlobalMcpServer: (payload: PutGlobalMcpServerPayload) => readonly McpServerConfig[]; removeGlobalMcpServer: (payload: GlobalMcpServerNamePayload) => readonly McpServerConfig[]; beginGlobalMcpServerAuth: (payload: GlobalMcpServerNamePayload) => BeginGlobalMcpServerAuthResult; completeGlobalMcpServerAuth: (payload: CompleteGlobalMcpServerAuthPayload) => void; cancelGlobalMcpServerAuth: (payload: CancelGlobalMcpServerAuthPayload) => void; resetGlobalMcpServerAuth: (payload: GlobalMcpServerNamePayload) => void; testGlobalMcpServer: (payload: TestGlobalMcpServerPayload) => McpTestResult; createSession: (payload: CreateSessionPayload) => SessionSummary_2; closeSession: (payload: CloseSessionPayload) => void; archiveSession: (payload: ArchiveSessionPayload) => void; deleteSession: (payload: DeleteSessionPayload) => void; resumeSession: (payload: ResumeSessionPayload) => ResumeSessionResult; reloadSession: (payload: ReloadSessionPayload) => ResumeSessionResult; forkSession: (payload: ForkSessionPayload) => ResumeSessionResult; listSessions: (payload: ListSessionsPayload) => readonly SessionSummary_2[]; exportSession: (payload: ExportSessionPayload) => ExportSessionResult_2; listWorkspaceSkills: (payload: ListWorkspaceSkillsPayload) => Promise; listPlugins: (payload: EmptyPayload) => readonly PluginSummary[]; installPlugin: (payload: InstallPluginPayload) => PluginSummary; setPluginEnabled: (payload: SetPluginEnabledPayload) => void; setPluginMcpServerEnabled: (payload: SetPluginMcpServerEnabledPayload) => void; removePlugin: (payload: RemovePluginPayload) => void; reloadPlugins: (payload: EmptyPayload) => ReloadPluginsResult; getPluginInfo: (payload: GetPluginInfoPayload) => PluginInfo; } declare interface CoreInfo { readonly version: string; } declare type CoreRPCClient = RPCClient; declare interface CreateAgentOptions { readonly profile?: ResolvedAgentProfile; readonly parentAgentId?: string; readonly swarmItem?: string; readonly persistMetadata?: boolean; } export declare interface CreateGoalInput { readonly objective: string; readonly replace?: boolean; } declare interface CreateGoalInput_2 { readonly objective: string; readonly completionCriterion?: string; readonly replace?: boolean; } declare interface CreateGoalPayload { readonly objective: string; readonly replace?: boolean; } export declare function createKimiConfigRpc(): KimiConfigRpc; export declare function createKimiHarness(options: KimiHarnessOptions): KimiHarness; export declare interface CreateSessionOptions { readonly id?: string | undefined; readonly workDir: string; readonly model?: string | undefined; readonly thinking?: string | undefined; readonly permission?: PermissionMode | undefined; readonly planMode?: boolean; readonly metadata?: JsonObject | undefined; readonly kaos?: Kaos | undefined; readonly persistenceKaos?: Kaos | undefined; readonly additionalDirs?: readonly string[]; /** * Botiverse mirror: extra standing-prompt text (Raft agent role/context) * threaded into the resolved profile's ROLE_ADDITIONAL slot. Flows via the * createSession spread → session config → Agent → updateSystemPromptFromProfile. */ readonly roleAdditional?: string; readonly sessionStartedProperties?: TelemetryProperties; /** * Print-mode (`kimi -p`) only: when the main agent ends a turn while * background subagents (`kind === 'agent'`) are still running, hold the turn * open and idle-wait until they all finish, flushing their completions into * the turn so the model can react before the run exits. Ignored by * interactive / SDK sessions. */ readonly drainAgentTasksOnStop?: boolean; } declare interface CreateSessionPayload { readonly id?: string | undefined; readonly workDir: string; readonly model?: string | undefined; readonly thinking?: string | undefined; readonly permission?: PermissionMode_2 | undefined; readonly metadata?: JsonObject_2 | undefined; readonly mcpServers?: Readonly>; readonly additionalDirs?: readonly string[]; /** Botiverse mirror: standing-prompt (Raft role/context) → ROLE_ADDITIONAL. */ readonly roleAdditional?: string; readonly client?: ClientTelemetryInfo | undefined; readonly drainAgentTasksOnStop?: boolean; } export declare interface CronFiredEvent { readonly type: 'cron.fired'; readonly origin: CronJobOrigin_2; readonly prompt: string; } declare interface CronJobOrigin { readonly kind: 'cron_job'; readonly jobId: string; readonly cron: string; readonly recurring: boolean; /** Number of theoretical fires that were collapsed into this single delivery (>= 1). */ readonly coalescedCount: number; /** True for recurring tasks past the 7-day age threshold. */ readonly stale: boolean; } declare interface CronJobOrigin_2 { readonly kind: 'cron_job'; readonly jobId: string; readonly cron: string; readonly recurring: boolean; readonly coalescedCount: number; readonly stale: boolean; } declare class CronManager { /** In-memory task store. Empty at construction; populated by * {@link addTask} (and {@link loadFromDisk} on resume). */ readonly store: SessionCronStore; /** * Clock source used for the stale judgment. Also passed to the * scheduler so the entire stack shares one notion of "now". */ readonly clocks: ClockSources; private readonly scheduler; private readonly agent; /** * Tracks whether `start()` has been called without a matching `stop()`. * Used to keep `start()` / `stop()` idempotent and — more importantly * for P1.8 — to gate SIGUSR1 binding so we don't accumulate handlers * across repeated start() calls. */ private started; /** * Reference to the bound SIGUSR1 listener while the manager is * running. Held so `stop()` can call `process.off('SIGUSR1', handler)` * with the same function reference and not leak handlers across vitest * files. `null` whenever the manager is not started, or when running * on a platform that does not support SIGUSR1 (Windows). */ private sigusr1Handler; /** * File-backed mirror of {@link store}. `undefined` when no * `sessionDir` was supplied — the manager then behaves as pure * in-memory, matching pre-persistence semantics. When defined, * `addTask` / `removeTasks` schedule fire-and-forget writes so a * later `kimi resume` can reload via {@link loadFromDisk}. */ private readonly persistStore; /** * Per-id serializer for persistence writes. Prevents a fast * `add` → `remove` sequence on the same id from racing each other on * the rename — the rm must observe the prior write's renamed file. * Empty between bursts; entries are deleted once their tail promise * settles so the map cannot grow unboundedly with churn. */ private readonly persistQueues; constructor(agent: Agent, opts?: CronManagerOptions); /** * Add a fresh task to the in-memory store and, when persistence is * attached, mirror the new record to `/cron/.json`. * * The store call is synchronous (CronCreate needs the id for its * response); the on-disk write is fire-and-forget so a slow disk * never blocks the tool's reply. Per-id queueing serializes * concurrent writes on the same id (e.g. add → stale auto-expire) so * the rm cannot race the rename. * * Persistence failures are logged via `agent.log.warn` and swallowed * — a flaky disk drops cross-resume durability but must not crash * the agent loop. */ addTask(init: SessionCronTaskInit): CronTask; /** * Remove a batch of tasks from the in-memory store and mirror each * deletion to disk (when persistence is attached). Returns the * subset of ids that were actually present, matching * `SessionCronStore.remove`'s contract — callers (CronDelete / * scheduler one-shot cleanup / stale auto-expire) read this to * decide whether to emit telemetry. * * Persistence failures are logged and swallowed; cross-resume the * worst case is a ghost entry that gets dropped on the next * `list()` shape-guard pass. */ removeTasks(ids: readonly string[]): readonly string[]; /** * Persist the scheduler's `lastFiredAt` cursor for a recurring task * so a `kimi resume` does not coalesce-replay an already-delivered * fire. Called by the scheduler's `onAdvanceCursor` callback after a * successful recurring fire. * * No-op when the task has already been removed between fire and * callback (concurrent CronDelete is the canonical case). When * persistence is detached (subagent / ephemeral session) we still * update the in-memory record — same-session stale checks read off * the in-memory store. The on-disk write is fire-and-forget via * `persistEnqueue`; a flaky disk drops cross-resume durability but * never blocks the scheduler. */ private advanceCursor; /** * Rehydrate the in-memory store from `/cron/` after * `kimi resume`. No-op when persistence is not attached. Idempotent: * clears the in-memory map and re-inserts every record on disk. * * Tasks are inserted via {@link SessionCronStore.adopt} so the * original `id` and `createdAt` survive — `createdAt` is the * scheduler's recurring baseline and the 7-day stale judgment's * input, so a regenerated value would corrupt both. */ loadFromDisk(): Promise; /** * Serialize per-id persistence writes. Concurrent mutations on the * same id (uncommon but reachable via `add` immediately followed by * stale auto-expire) would otherwise race on the rename — atomicWrite * is per-call atomic, not per-id ordered. Each id's chain is dropped * from the map once it settles so the map size tracks live in-flight * writes, not lifetime churn. */ private persistEnqueue; /** * Wait for every pending persistence write / remove scheduled via * {@link addTask} / {@link removeTasks} to settle. Called from * {@link stop} for graceful session shutdown and exposed publicly so * tests can synchronise on disk-visible state without polling. * * Errors are already swallowed by `persistEnqueue`, so this never * rejects. */ flushPersist(): Promise; /** * Begin the scheduler's auto-tick loop and bind the SIGUSR1 manual-tick * hook (P1.8). Idempotent: a second call is a no-op so the boot * sequence and tests can opt into "ensure started" without bookkeeping. */ start(): void; /** * Stop the scheduler, drain pending persistence writes, clear * in-flight bookkeeping, and unbind the SIGUSR1 handler. Idempotent * and signal-handler-safe — multiple vitest files exercising the * manager must not leave a SIGUSR1 listener dangling on the shared * process. * * Draining persistence on shutdown matters for production: a session * `close()` immediately after a CronCreate would otherwise tear the * process down before the JSON file lands on disk, and the task * would be missing from the resume's `loadFromDisk()`. */ stop(): Promise; /** Drive one scheduler tick synchronously. Used by tests + P1.8 SIGUSR1. */ tick(): void; /** * Earliest theoretical (post-jitter) next-fire across all tasks, or * null if there are no tasks / none have a future fire. Used by the * `/cron` slash command and external monitoring. */ getNextFireTime(): number | null; /** * Per-task post-jitter next-fire. Forwards to the scheduler so * CronList renders the same instant the scheduler will fire — even * when an already-past ideal still has a pending jittered delivery * in the current period. */ getNextFireForTask(taskId: string): number | null; /** * Enumerate every scheduled task with its post-jitter next fire time. * Unlike the CronList tool (which renders for the model), this returns * structured data for host applications polling for pending work. */ listTaskSnapshots(): readonly CronTaskSnapshot[]; /** * Stale judgment. * * - `KIMI_CRON_NO_STALE=1` short-circuits to false (bench). * - One-shot tasks (`recurring === false`) are never stale — they * fire at most once by construction; flagging them stale would be * a noisy false positive on every backlog wakeup. * - Otherwise: `wallNow() - createdAt >= 7 days`. * * `Number.isFinite` guards against the wall clock being broken (e.g. * a mis-set bench env that returns `NaN`); a non-finite age is * treated as "we don't know, don't claim stale". */ isStale(task: CronTask): boolean; /** * Translate a scheduler fire into a steer + telemetry event. * * `agent.turn.steer` returns the new turnId, or `null` when the input * was buffered because a turn is in flight (see turn/index.ts:84). * We propagate that as `buffered` on the telemetry props so dashboards * can distinguish "fired into a fresh turn" from "fired into a steer * buffer that may not run until the user's turn ends". * * Honours the documented 7-day auto-expire contract for recurring * tasks: a stale recurring task gets exactly one final delivery * (already issued above) and is then removed from the store. The * scheduler picks up the deletion on its next tick via `source()` * and stops re-firing the task. One-shots are not affected — they * are deleted by the scheduler immediately after delivery via the * `removeOneShot` callback. */ private handleFire; /** * Reserved hook for an explicit "you missed N fires while offline" * banner. Today the scheduler's `coalescedCount` semantics already * communicate missed fires inside the `cron_job` envelope (and * recurring tasks past 7 days arrive with `stale: true`), so the * resume path does NOT invoke this from the framework. The method * stays exposed because adding a separate user-facing banner later * — e.g. for one-shots whose fire times all landed during a long * outage — should not require an API change here. * * The `renderMissedNotification` callback is supplied by the caller * (rather than imported here) so this module stays free of UI / copy * coupling; the same manager works for tests that want to inject a * trivial renderer. * * `count: 0` is a no-op — the scheduler-side missed-task detector * filters empties before calling us, but defending here keeps the * contract simple ("safe to call with anything, no-op when empty"). */ handleMissed(tasks: readonly CronTask[], renderMissedNotification: (tasks: readonly CronTask[]) => readonly ContentPart[]): void; /** * Emit `cron_scheduled` for a freshly-added task. Called by * `CronCreate` after a successful `store.add(...)`. Kept as an * explicit method so the tool layer never reaches into * `manager.agent.telemetry` — preserves the "tools see the manager, * the manager sees the agent" layering and matches the symmetric * `emitDeleted` used by `CronDelete` (P1.6). */ emitScheduled(task: CronTask): void; /** * Emit `cron_deleted` for a removed task. Wired up here so P1.6 can * land without touching this file again. `task_id` matches the field * naming used elsewhere in the telemetry surface (snake_case). */ emitDeleted(taskId: string): void; /** * Wire `SIGUSR1` to a manual `tick()` so bench scripts can advance the * scheduler with `kill -USR1 ` without a custom RPC. * * Gated on `KIMI_CRON_MANUAL_TICK=1` for two reasons: * * 1. SIGUSR1 only makes sense when auto-tick is off. When the 1s * interval is running, it already advances the scheduler — a * manual signal is redundant. * 2. In production a single CLI process can host one main agent plus * many subagents. Each Agent unconditionally binding a SIGUSR1 * listener would put us over Node's 10-listener default cap and * print a `MaxListenersExceededWarning`. Coupling the binding to * the same env that disables auto-tick keeps the production path * at zero listeners while still giving benches the affordance. * * Skipped on Windows because Node's signal layer does not deliver * POSIX signals there; attempting to `process.on('SIGUSR1', ...)` is a * silent no-op but we avoid the call entirely so the bookkeeping * (`sigusr1Handler !== null` means "we did bind") stays accurate. * * Idempotent — repeated calls keep the same listener registered once, * so `start() → start()` does not stack handlers. * * The handler swallows any throw from `tick()` because a signal-driven * bench tool must never crash the host process; the tick failure mode * is already surfaced via telemetry / logs inside the scheduler. * Set `KIMI_CRON_DEBUG=1` to surface the swallowed error to stderr — * mirrors `scheduler.ts`'s debugLog pattern so bench debugging can * see a bad tick. */ private bindSigusr1; /** * Detach the SIGUSR1 listener registered by `bindSigusr1`. Safe to * call when nothing is bound (no-op). Pair this with `stop()` so * vitest files don't leak signal handlers across the shared process — * `process.listenerCount('SIGUSR1')` should return to its pre-`start()` * value once `stop()` resolves. */ private unbindSigusr1; } declare interface CronManagerOptions { /** * Override for tests / bench. Defaults to * `resolveClockSources(process.env.KIMI_CRON_CLOCK)` so production * picks up `KIMI_CRON_CLOCK=file:...` automatically. * When unset, falls through to {@link SYSTEM_CLOCKS}. */ readonly clocks?: ClockSources; /** * Override scheduler poll interval. Defaults handled by the scheduler * (1000ms unless `KIMI_CRON_MANUAL_TICK=1`, which forces `null` here * so the auto-tick `setInterval` is never installed). `null` or `0` * means "no automatic timer — caller drives `tick()` manually". */ readonly pollIntervalMs?: number | null; } declare interface CronMissedOrigin { readonly kind: 'cron_missed'; /** Number of one-shot tasks bundled into this missed-fire notification. */ readonly count: number; } declare interface CronMissedOrigin_2 { readonly kind: 'cron_missed'; readonly count: number; } /** * Persistent representation of a cron task. * * - `id` — 8-hex; jitter is keyed off this hash, so stable id == stable * jitter across schedule rewrites. * - `cron` — 5-field expression, evaluated in local time. * - `createdAt` — wall-clock epoch ms at original scheduling. NOT updated * when the scheduler fires; recurring uses it as the baseline floor * when no `lastFiredAt` has been recorded. Also the input to the * 7-day stale judgment. * - `recurring` — undefined / true means "fire repeatedly until deleted * or auto-expired"; false means "fire once then auto-delete". * - `lastFiredAt` — wall-clock epoch ms of the last ideal occurrence * whose jittered delivery has actually completed. Persisted so a * `kimi resume` does not replay already-delivered recurring fires: * without it, the scheduler would fall back to `createdAt` and * coalesce yesterday's already-fired 09:00 into today's tick. A * value greater than the current wall clock is treated as corrupt * and the scheduler falls back to `createdAt` for that task. */ declare interface CronTask { readonly id: string; readonly cron: string; readonly prompt: string; readonly createdAt: number; readonly recurring?: boolean; readonly lastFiredAt?: number; } /** * Point-in-time view of a scheduled cron task, exposed over RPC so host * applications (e.g. the `kimi -p` flow deciding whether pending work * remains before exit) can enumerate scheduled tasks without going * through the model-facing CronList tool. */ export declare interface CronTaskSnapshot { readonly id: string; readonly cron: string; readonly recurring: boolean; readonly createdAt: number; readonly lastFiredAt: number | undefined; /** Post-jitter next fire (epoch ms), or null when no future fire exists. */ readonly nextFireAt: number | null; } export declare const DEFAULT_CATALOG_URL = "https://models.dev/api.json"; declare interface DeleteSessionPayload { readonly sessionId: string; } declare interface DetachBackgroundPayload { readonly taskId: string; } /** RFC 8628 §3.2 device authorization response. */ declare interface DeviceAuthorization { readonly userCode: string; readonly deviceCode: string; readonly verificationUri: string; readonly verificationUriComplete: string; /** Seconds until device_code expires (server-reported). May be null. */ readonly expiresIn: number | null; /** Polling interval in seconds. */ readonly interval: number; } declare function discoverSkills(options: DiscoverSkillsOptions): Promise; declare interface DiscoverSkillsOptions { readonly roots: readonly SkillRoot[]; readonly onWarning?: (message: string, cause?: unknown) => void; readonly onSkippedByPolicy?: (skill: SkippedSkill) => void; readonly onDiscoveredSkill?: (skill: SkillDefinition) => void; readonly readdir?: (p: string) => Promise; readonly isFile?: (p: string) => Promise; readonly isDir?: (p: string) => Promise; readonly parse?: (input: { readonly skillMdPath: string; readonly skillDirName: string; readonly source: SkillSource; }) => Promise; } export declare function effectiveModelAlias(alias: ModelAlias, providerType?: ProviderType): ModelAlias; declare type EmptyPayload = {}; declare interface EnabledPluginSessionStart { readonly pluginId: string; readonly skillName: string; } declare interface EnterSwarmPayload { readonly trigger: SwarmModeTrigger; } declare type Env = Readonly>; declare interface Environment { readonly osKind: OsKind; readonly osArch: string; readonly osVersion: string; readonly shellName: ShellName; readonly shellPath: string; } /** * Error codes for Kimi Core's public error protocol. * * `ErrorCodes` is the source of truth for every code Kimi Core may emit. * Downstream consumers (SDK, RPC clients, telemetry, agent-facing docs) * should depend on these string values rather than on class identity. * * Codes follow `domain.reason`. Adding a code is a minor change; renaming * or removing one is a major change. */ export declare const ErrorCodes: { readonly CONFIG_INVALID: "config.invalid"; readonly SESSION_NOT_FOUND: "session.not_found"; readonly SESSION_ALREADY_EXISTS: "session.already_exists"; readonly SESSION_ID_INVALID: "session.id_invalid"; readonly SESSION_ID_REQUIRED: "session.id_required"; readonly SESSION_ID_EMPTY: "session.id_empty"; readonly SESSION_TITLE_EMPTY: "session.title_empty"; readonly SESSION_STATE_NOT_FOUND: "session.state_not_found"; readonly SESSION_STATE_INVALID: "session.state_invalid"; readonly SESSION_FORK_ACTIVE_TURN: "session.fork_active_turn"; readonly SESSION_EXPORT_NOT_FOUND: "session.export_not_found"; readonly SESSION_EXPORT_MISSING_VERSION: "session.export_missing_version"; readonly SESSION_CLOSED: "session.closed"; readonly SESSION_PERMISSION_MODE_INVALID: "session.permission_mode_invalid"; readonly SESSION_THINKING_EMPTY: "session.thinking_empty"; readonly SESSION_MODEL_EMPTY: "session.model_empty"; readonly SESSION_PLAN_MODE_INVALID: "session.plan_mode_invalid"; readonly SESSION_APPROVAL_HANDLER_ERROR: "session.approval_handler_error"; readonly SESSION_QUESTION_HANDLER_ERROR: "session.question_handler_error"; readonly SESSION_INIT_FAILED: "session.init_failed"; readonly AGENT_NOT_FOUND: "agent.not_found"; readonly TURN_AGENT_BUSY: "turn.agent_busy"; readonly GOAL_ALREADY_EXISTS: "goal.already_exists"; readonly GOAL_NOT_FOUND: "goal.not_found"; readonly GOAL_OBJECTIVE_EMPTY: "goal.objective_empty"; readonly GOAL_OBJECTIVE_TOO_LONG: "goal.objective_too_long"; readonly GOAL_STATUS_INVALID: "goal.status_invalid"; readonly GOAL_METADATA_RESERVED: "goal.metadata_reserved"; readonly GOAL_NOT_RESUMABLE: "goal.not_resumable"; readonly MODEL_NOT_CONFIGURED: "model.not_configured"; readonly MODEL_CONFIG_INVALID: "model.config_invalid"; readonly AUTH_LOGIN_REQUIRED: "auth.login_required"; readonly CONTEXT_OVERFLOW: "context.overflow"; readonly LOOP_MAX_STEPS_EXCEEDED: "loop.max_steps_exceeded"; readonly PROVIDER_API_ERROR: "provider.api_error"; readonly PROVIDER_FILTERED: "provider.filtered"; readonly PROVIDER_RATE_LIMIT: "provider.rate_limit"; readonly PROVIDER_AUTH_ERROR: "provider.auth_error"; readonly PROVIDER_CONNECTION_ERROR: "provider.connection_error"; readonly SKILL_NOT_FOUND: "skill.not_found"; readonly SKILL_TYPE_UNSUPPORTED: "skill.type_unsupported"; readonly SKILL_NAME_EMPTY: "skill.name_empty"; readonly RECORDS_WRITE_FAILED: "records.write_failed"; readonly COMPACTION_FAILED: "compaction.failed"; readonly COMPACTION_UNABLE: "compaction.unable"; readonly BACKGROUND_TASK_ID_EMPTY: "task.task_id_empty"; readonly MCP_SERVER_NOT_FOUND: "mcp.server_not_found"; readonly MCP_SERVER_DISABLED: "mcp.server_disabled"; readonly MCP_STARTUP_FAILED: "mcp.startup_failed"; readonly MCP_TOOL_NAME_COLLISION: "mcp.tool_name_collision"; readonly PLUGIN_NOT_FOUND: "plugin.not_found"; readonly PLUGIN_LOAD_FAILED: "plugin.load_failed"; readonly REQUEST_INVALID: "request.invalid"; readonly REQUEST_WORK_DIR_REQUIRED: "request.work_dir_required"; readonly REQUEST_PROMPT_INPUT_EMPTY: "request.prompt_input_empty"; readonly SHELL_GIT_BASH_NOT_FOUND: "shell.git_bash_not_found"; readonly NOT_IMPLEMENTED: "not_implemented"; readonly INTERNAL: "internal"; }; export declare interface ErrorEvent extends KimiErrorPayload_2 { readonly type: 'error'; } declare type Event_2 = AgentEvent & { agentId: string; sessionId: string; }; export { Event_2 as Event } declare interface ExecutableTool extends Tool { resolveExecution(input: Input): ToolExecution | Promise; } /** * Per-call context passed to tool implementations. */ declare interface ExecutableToolContext { readonly turnId: string; readonly toolCallId: string; readonly traceId?: string; readonly metadata?: unknown; readonly signal: AbortSignal; readonly onUpdate?: ((update: ToolUpdate_2) => void) | undefined; /** * Fired once when a foreground (non-background) process task is registered, * carrying its task id. Used by the `!` shell-command path so the TUI can * later detach (ctrl+b) that exact task. Background runs skip it. */ readonly onForegroundTaskStart?: ((taskId: string) => void) | undefined; } declare interface ExecutableToolErrorResult { readonly output: ExecutableToolOutput; readonly isError: true; /** See {@link ExecutableToolSuccessResult.message}. */ readonly message?: string | undefined; /** See {@link ExecutableToolSuccessResult.note}. */ readonly note?: string | undefined; /** See {@link ExecutableToolSuccessResult.stopTurn}. */ readonly stopTurn?: boolean | undefined; /** See {@link ExecutableToolSuccessResult.truncated}. */ readonly truncated?: boolean | undefined; } declare type ExecutableToolOutput = string | ContentPart[]; declare type ExecutableToolResult = ExecutableToolSuccessResult | ExecutableToolErrorResult; declare interface ExecutableToolSuccessResult { readonly output: ExecutableToolOutput; readonly isError?: false | undefined; /** * Internal loop-control hint. Tool result events strip this field before * persistence; it only tells the current turn whether another model step or * later tool calls in the same batch are allowed. */ readonly stopTurn?: boolean | undefined; /** * Optional human-readable side channel for tool-result metadata that * should not contaminate the data stream the model sees (e.g. a * "Task snapshot retrieved." brief for TaskOutput). Distinct from * `output`: callers rendering tool results decide whether to surface * this to the user. */ readonly message?: string | undefined; /** * Optional side channel in the opposite direction of `message`: content * that is rendered to the model but never to user-facing UIs. Routed * verbatim — any formatting (tags, wording) is the producing tool's * choice. Appended to the tool result as a trailing text part when the * history is projected for the provider. */ readonly note?: string | undefined; /** * True when the tool has already returned a partial result because it * truncated, paged, or otherwise dropped original output. Later generic * budgeting must not treat the visible output as complete source text. */ readonly truncated?: boolean | undefined; } export declare interface ExperimentalFeatureState { /** Feature id. Typed as `string` because this is a runtime snapshot that * crosses the SDK/RPC boundary and must remain usable even when no flags are * registered (in which case the internal `FlagId` union collapses to `never`). */ readonly id: string; readonly title: string; readonly description: string; readonly surface: FlagSurface; readonly env: string; readonly defaultEnabled: boolean; readonly enabled: boolean; readonly source: ExperimentalFlagSource; readonly configValue?: boolean; } /** User config overrides for experimental flags (flag id → enabled). */ declare type ExperimentalFlagConfig = Partial>; /** Resolved enabled-state of every experimental flag (flag id → enabled); used for the SDK snapshot. */ export declare type ExperimentalFlagMap = Record; declare interface ExperimentalFlagResolver { enabled(id: FlagId): boolean; snapshot(): ExperimentalFlagMap; enabledIds(): readonly FlagId[]; explain(id: FlagId): ExperimentalFeatureState | undefined; explainAll(): readonly ExperimentalFeatureState[]; setConfigOverrides(overrides: ExperimentalFlagConfig | undefined): void; } export declare type ExperimentalFlagSource = 'master-env' | 'env' | 'config' | 'default'; export declare interface ExportSessionInput { readonly id: string; readonly outputPath?: string | undefined; readonly includeGlobalLog?: boolean | undefined; /** Host version to record in the export manifest. */ readonly version: string; /** How the CLI was installed (e.g. 'npm-global', 'native'). */ readonly installSource?: string | undefined; readonly shellEnv?: ShellEnvironment | undefined; } export declare interface ExportSessionManifest { readonly sessionId: string; readonly exportedAt: string; readonly kimiCodeVersion: string; readonly wireProtocolVersion: string; readonly os: string; readonly nodejsVersion: string; readonly sessionFirstActivity?: string | undefined; readonly sessionLastActivity?: string | undefined; readonly title?: string | undefined; readonly workspaceDir?: string | undefined; /** zip-relative path to the session diagnostic log when present. */ readonly sessionLogPath?: string | undefined; /** zip-relative path to the bundled global diagnostic log (only when --include-global-log). */ readonly globalLogPath?: string | undefined; /** How the CLI was installed (e.g. 'npm-global', 'native'). */ readonly installSource?: string | undefined; readonly shellEnv?: ShellEnvironment | undefined; } declare interface ExportSessionPayload { readonly sessionId: string; readonly outputPath?: string | undefined; /** * When true, the active global diagnostic log (`$KIMI_CODE_HOME/logs/kimi-code.log`) * is copied into the zip at `logs/global/kimi-code.log`. Off by default to * avoid bundling events from concurrent sessions / other projects. */ readonly includeGlobalLog?: boolean | undefined; /** Host version to record in the export manifest. */ readonly version: string; /** How the CLI was installed (e.g. 'npm-global', 'native'). */ readonly installSource?: string | undefined; readonly shellEnv?: ShellEnvironment | undefined; } export declare interface ExportSessionResult { readonly zipPath: string; readonly entries: readonly string[]; readonly sessionDir: string; readonly manifest: ExportSessionManifest; } declare interface ExportSessionResult_2 { readonly zipPath: string; readonly entries: readonly string[]; readonly sessionDir: string; readonly manifest: ExportSessionManifest; } declare interface ExtraBody { thinking?: ThinkingConfig_2; [key: string]: unknown; } /** * Fetches a models.dev-style catalog. Public endpoint, no credentials needed. * `userAgent` identifies the host product (e.g. `kimi-code-cli/1.2.3`); when * omitted the request falls back to the runtime default (`User-Agent: node`). */ export declare function fetchCatalog(url: string, options?: FetchCatalogOptions): Promise; export declare interface FetchCatalogOptions { readonly signal?: AbortSignal; readonly fetchImpl?: typeof fetch; readonly userAgent?: string; } declare interface FetchCompleteFeedbackUploadOk { readonly kind: 'ok'; } declare type FetchCompleteFeedbackUploadResult = FetchCompleteFeedbackUploadOk | FetchFeedbackUploadError; declare interface FetchFeedbackUploadError { readonly kind: 'error'; readonly status?: number; readonly message: string; } declare interface FetchManagedUsageError { readonly kind: 'error'; readonly status?: number; readonly message: string; } declare interface FetchSubmitFeedbackError { readonly kind: 'error'; readonly status?: number; readonly message: string; } declare interface FetchSubmitFeedbackOk { readonly kind: 'ok'; readonly feedbackId: number; } declare type FetchSubmitFeedbackResult = FetchSubmitFeedbackOk | FetchSubmitFeedbackError; declare type FinishReason = 'completed' | 'tool_calls' | 'truncated' | 'filtered' | 'paused' | 'other'; /** * Normalized finish-reason signal indicating why a generation stopped. * * Each provider's native stop value is mapped to one of these, and the * unmapped original string is preserved in `rawFinishReason` as an escape * hatch. `null` means the provider did not emit a finish_reason (e.g. the * stream was cut off before the final event). * * - `'completed'`: normal completion (OpenAI `'stop'`, Anthropic * `'end_turn'` / `'stop_sequence'`, Gemini `'STOP'`). * - `'tool_calls'`: generation paused so the caller can dispatch tool * calls and feed their results back. Note that the OpenAI Responses API * and Google GenAI report `'completed'` here; only the Chat * Completions–style providers and Anthropic surface a dedicated value. * - `'truncated'`: token budget exhausted (OpenAI `'length'`, Anthropic * `'max_tokens'`, Gemini `'MAX_TOKENS'`, Responses `'max_output_tokens'`). * - `'filtered'`: content filter or safety policy blocked the response. * - `'paused'`: Anthropic-specific `'pause_turn'`. * - `'other'`: recognized non-null reason that does not fit the categories * above. */ declare type FinishReason_2 = 'completed' | 'tool_calls' | 'truncated' | 'filtered' | 'paused' | 'other'; /** * Experimental feature flags. * * To add one, append an entry and gate runtime behavior through the scoped * resolver available on `KimiCore`, `Session`, or `Agent`: * { id: 'my_feature', title: 'My feature', description: '...', env: 'KIMI_CODE_EXPERIMENTAL_MY_FEATURE', default: false, surface: 'both' } * * Keep the `as const satisfies` — it derives the literal `FlagId` union that gives `enabled()` * autocomplete and typo-checking. `env` must start with 'KIMI_CODE_EXPERIMENTAL_', be unique, and * not equal the master switch 'KIMI_CODE_EXPERIMENTAL_FLAG'; `id` must not be 'flag'. */ declare const FLAG_DEFINITIONS: readonly [{ readonly id: "tool-select"; readonly title: "Tool select (progressive tool disclosure)"; readonly description: "Keep MCP tool schemas out of the immutable top-level tools[]; the model loads them on demand via the select_tools tool. Only takes effect on models whose capability catalog declares dynamically loaded tools."; readonly env: "KIMI_CODE_EXPERIMENTAL_TOOL_SELECT"; readonly default: false; readonly surface: "core"; }]; /** FlagId-typed view so consumers can fetch a definition by its literal id. */ export declare type FlagDefinition = FlagDefinitionInput & { readonly id: FlagId; }; /** Shape of a registry entry (id is a loose string so `as const satisfies` can validate it). */ export declare interface FlagDefinitionInput { readonly id: string; readonly title: string; readonly description: string; /** Full environment variable name, e.g. `KIMI_CODE_EXPERIMENTAL_MY_FEATURE`. Read directly by the resolver. */ readonly env: string; readonly default: boolean; readonly surface: FlagSurface; } /** Literal union of registered flag ids. */ export declare type FlagId = (typeof FLAG_DEFINITIONS)[number]['id']; /** Which layer consumes a flag — documentation/grouping only; not used in resolution. */ export declare type FlagSurface = 'core' | 'tui' | 'both'; export declare function flushDiagnosticLogs(): Promise; /** * Synchronous variant for crash / emergency-exit paths that call * `process.exit()` on the same tick: pending entries are appended with * `appendFileSync`, so they survive the immediate exit that would otherwise * drop everything still sitting in the async queue. */ export declare function flushDiagnosticLogsSync(): void; declare type ForegroundTaskReleaseReason = 'detached' | 'timeout_detached' | 'terminal'; export declare interface ForkSessionInput { readonly id: string; readonly forkId?: string; readonly title?: string; readonly metadata?: JsonObject; /** * Zero-based index of the user-visible turn to retain through. Omit it to * preserve the existing full-session fork behavior. */ readonly turnIndex?: number; } declare interface ForkSessionPayload { readonly sessionId: string; readonly id?: string; readonly title?: string; readonly metadata?: JsonObject_2; /** * Zero-based index of the user-visible turn to retain through. When omitted, * the complete session is copied (the existing fork behavior). */ readonly turnIndex?: number; } /** * Rehydrate a KimiErrorPayload into a KimiError. Used by SDK boundary code * receiving errors over RPC to re-surface them with a real class so * in-process consumers can still use `instanceof`. */ export declare function fromKimiErrorPayload(payload: KimiErrorPayload): KimiError; declare class FullCompaction { protected readonly agent: Agent; protected compactionCountInTurn: number; protected compacting: { abortController: AbortController; promise: Promise; blockedByTurn: boolean; } | null; private readonly observedMaxContextTokensByModel; private lastCompactedTokenCount; private consecutiveOverflowCompactions; private lastSummarizerTraceId; private activeSummarizerTrace; protected readonly strategy: CompactionStrategy; constructor(agent: Agent, strategy?: CompactionStrategy); get isCompacting(): boolean; /** Trace id (`x-trace-id`, Kimi/KFC only) of the latest summarizer request. */ get lastTraceId(): string | undefined; getEffectiveMaxContextTokens(): number; estimateCurrentRequestTokens(): number; shouldRecoverFromContextOverflow(error: unknown, estimatedRequestTokens?: number): boolean; observeContextOverflow(estimatedRequestTokens: number): void; begin(data: Readonly): void; cancel(): void; markCompleted(): void; private get tokenCountWithPending(); private estimateRequestTokens; resetForTurn(): void; handleOverflowError(signal: AbortSignal, error: unknown): Promise; beforeStep(signal: AbortSignal): Promise; afterStep(): Promise; private checkAutoCompaction; private beginAutoCompaction; private block; private compactionWorker; private buildInstruction; private postProcessSummary; private compactionRound; private triggerPreCompactHook; private triggerPostCompactHook; } /** * Enforce the provider-accepted image format set (see ./image-format-policy) * on a content-part list. Inline `data:` image parts whose MIME is outside * the accepted set are dropped and replaced with a text notice, so one * unsupported image cannot poison the session history. Accepted images are * forwarded only as the byte-exact canonical data URL: an alias * (`image/jpg`), case/whitespace variants, or MIME parameters * (`image/jpeg;charset=utf-8`) all rebuild to the bare canonical form, * because strict provider whitelists exact-match the full header. Remote * (non-data) image URLs and non-image parts pass through — a URL carries no * bytes to inspect. * * The BYTES are authoritative, not the declared MIME: the header of each * inline image is sniffed, and a mismatch (e.g. AVIF bytes an MCP image * search tool labels `image/png`) is gated on what the image IS — the * provider decodes bytes, not labels. When the sniffer doesn't recognize * the bytes (corrupt image, exotic container), the declared MIME stands * and the 400-recovery path remains the backstop. * * This is the format gate shared by every ingestion point; run it BEFORE * compression so unsupported bytes are never decoded. */ export declare function gateImageFormatParts(parts: readonly ContentPart[]): ContentPart[]; /** * Generate one assistant message by streaming from the given provider. * * Parts of the message are streamed and merged: consecutive compatible parts * (e.g. TextPart + TextPart, ToolCall + ToolCallPart) are merged in-place so * the returned message always contains fully-assembled parts. * * **Tool call completion** is inferred from merge boundaries (a non-merging * next part flushes the pending tool call into `message.toolCalls`) and from * stream end. Provider adapters translate native "done" signals into this * unified form; the generate loop never sees a separate done event. * * @param provider - The chat provider to generate from. * @param systemPrompt - System-level instruction prepended to the request. * @param tools - Tool definitions the model may invoke. * @param history - The conversation history sent as context. * @param callbacks - Optional streaming callbacks. * @param options - Optional per-call settings (e.g. an {@link AbortSignal}). * * @throws {DOMException} with name `"AbortError"` when `options.signal` is * aborted before or during streaming. * @throws {APIEmptyResponseError} when the response contains no content and * no tool calls, or only thinking content without any text or tool calls. */ declare function generate(provider: ChatProvider, systemPrompt: string, tools: Tool[], history: Message[], callbacks?: GenerateCallbacks, options?: GenerateOptions): Promise; declare interface GenerateCallbacks { onMessagePart?: (part: StreamedMessagePart) => void | Promise; /** * Fires once per fully-assembled tool call after the stream drains, in the * order tool calls appear in the final assistant message. * * Tool calls are deliberately deferred until after the stream completes: * parallel-tool-call streams may interleave argument deltas across calls * (e.g. tc0-header → tc1-header → tc0-args → tc1-args), so firing mid-stream * would dispatch a tool with half-parsed arguments and trigger toolParseError. */ onToolCall?: (toolCall: ToolCall) => void | Promise; } declare type GenerateFn = typeof generate; declare interface GenerateOptions { /** * An {@link AbortSignal} that, when aborted, requests cancellation of the * in-flight generate call. Providers that accept a signal will forward it * to their underlying HTTP client; the generate loop in * {@link generate | generate()} also checks the signal between streamed * parts. */ signal?: AbortSignal; /** * Request-scoped provider auth. Hosts should resolve this immediately before * each request/retry so providers never retain mutable credential state. */ auth?: ProviderRequestAuth; /** * Optional model-output format constraint. Providers map this to their native * structured-output field when supported. */ responseFormat?: ResponseFormat; /** * Host-side instrumentation hook fired immediately before invoking the * provider adapter's generate call. */ onRequestStart?: () => void; /** * Host-side instrumentation hook fired by the provider adapter immediately * before it dispatches the network request to the upstream API. The window * between {@link onRequestStart} and this hook is in-process request-building * time (message serialization, param assembly) spent by the client; the * window between this hook and the first streamed part is network + server * time. Splitting time-to-first-token across this boundary lets hosts * attribute latency to the client vs. the API server. */ onRequestSent?: () => void; /** * Host-side instrumentation hook fired as soon as the provider response * headers arrive (before the stream body is drained), carrying the * provider trace identifier from the `x-trace-id` header, or `null` when * the provider does not report one. Firing early lets hosts attribute a * stream that is cancelled mid-flight to its server-side request. */ onTraceId?: (traceId: string | null) => void; /** * Host-side instrumentation hook fired after the provider stream is fully * drained, before post-processing the assembled response. Receives the * {@link StreamDecodeStats} accounting accumulated across the stream when at * least one part was streamed, or `undefined` for an empty stream. */ onStreamEnd?: (stats?: StreamDecodeStats) => void; } /** * The result of a single {@link generate} call. * * Contains the fully-assembled assistant {@link message}, an optional * provider-assigned {@link id}, and token {@link usage} statistics. */ declare interface GenerateResult { /** Provider-assigned response identifier, or `null` if unavailable. */ readonly id: string | null; /** The fully-assembled assistant message with merged content parts and tool calls. */ readonly message: Message; /** Token usage for this generation, or `null` if not reported. */ readonly usage: TokenUsage_3 | null; /** * Normalized finish reason reported by the provider, or `null` if no * finish_reason was emitted (for example, the stream was interrupted * before the final event). */ readonly finishReason: FinishReason_2 | null; /** * Raw provider-specific finish_reason string preserved verbatim. * `null` if the provider did not emit one. */ readonly rawFinishReason: string | null; /** * Provider trace identifier from the `x-trace-id` response header * (Kimi/KFC only), or `null` when the provider does not report one. */ readonly traceId?: string | null; } declare interface GenerationKwargs { /** * Legacy completion-budget alias. The Moonshot Kimi API still accepts * `max_tokens`, but for reasoning models it shares the budget with * `reasoning_content` and a small value can cause a 200 response with no * `content`. Prefer `max_completion_tokens`. When both are set * `max_completion_tokens` wins; this provider normalizes by sending only * `max_completion_tokens` on the wire. */ max_tokens?: number | undefined; max_completion_tokens?: number | undefined; temperature?: number | undefined; top_p?: number | undefined; n?: number | undefined; presence_penalty?: number | undefined; frequency_penalty?: number | undefined; stop?: string | string[] | undefined; prompt_cache_key?: string | undefined; extra_body?: ExtraBody; } declare interface GetBackgroundOutputPayload { readonly taskId: string; readonly tail?: number; } declare interface GetBackgroundPayload { /** * When omitted, returns all tasks (including terminal/lost). Pass * `true` to filter down to active-only — useful for model-facing * surfaces. UI/TUI consumers should leave it undefined. */ readonly activeOnly?: boolean; /** Caps the number of tasks returned. When omitted, returns all matching tasks. */ readonly limit?: number; } export declare interface GetConfigOptions { readonly reload?: boolean | undefined; } export declare interface GetCronTasksResult { readonly tasks: readonly CronTaskSnapshot[]; } declare interface GetKimiConfigPayload { readonly reload?: boolean; } declare interface GetPluginInfoPayload { readonly id: string; } declare interface GlobalMcpServerNamePayload { readonly name: string; } /** Who performed a goal action. `cleared` is a record action, not a status. */ declare type GoalActor = 'user' | 'model' | 'runtime' | 'system'; declare type GoalActor_2 = 'user' | 'model' | 'runtime' | 'system'; export declare interface GoalBudgetLimits { readonly tokenBudget?: number; readonly turnBudget?: number; readonly wallClockBudgetMs?: number; } /** Computed budget view exposed through snapshots and tools. */ export declare interface GoalBudgetReport { readonly tokenBudget: number | null; readonly turnBudget: number | null; readonly wallClockBudgetMs: number | null; readonly remainingTokens: number | null; readonly remainingTurns: number | null; readonly remainingWallClockMs: number | null; readonly tokenBudgetReached: boolean; readonly turnBudgetReached: boolean; readonly wallClockBudgetReached: boolean; readonly overBudget: boolean; } declare interface GoalBudgetReport_2 { readonly tokenBudget: number | null; readonly turnBudget: number | null; readonly wallClockBudgetMs: number | null; readonly remainingTokens: number | null; readonly remainingTurns: number | null; readonly remainingWallClockMs: number | null; readonly tokenBudgetReached: boolean; readonly turnBudgetReached: boolean; readonly wallClockBudgetReached: boolean; readonly overBudget: boolean; } export declare interface GoalChange { readonly kind: GoalChangeKind; readonly status?: GoalStatus; readonly reason?: string; readonly stats?: GoalChangeStats; readonly actor?: GoalActor; } declare interface GoalChange_2 { readonly kind: GoalChangeKind_2; readonly status?: GoalStatus_2; readonly reason?: string; readonly stats?: GoalChangeStats_2; readonly actor?: GoalActor_2; } /** * Describes what changed on a `goal.updated` event, so the UI can render the * right thing. Absent for snapshot-only refreshes (e.g. a turn increment that * only moves the badge). * * - `lifecycle`: a status transition — `paused` / `active` (resumed) / `blocked` * — rendered as a low-profile transcript marker. * - `completion`: the goal completed successfully (the only outcome that posts * the completion message and clears the record). This replaced the older * `terminal` name, which since the state consolidation only ever meant * `complete` — `blocked` is a resumable `lifecycle` change, not a completion. */ declare type GoalChangeKind = 'lifecycle' | 'completion'; declare type GoalChangeKind_2 = 'lifecycle' | 'completion'; /** Snapshot of the goal's usage counters at the moment of a change. */ export declare interface GoalChangeStats { readonly turnsUsed: number; readonly tokensUsed: number; readonly wallClockMs: number; } declare interface GoalChangeStats_2 { readonly turnsUsed: number; readonly tokensUsed: number; readonly wallClockMs: number; } /** * Single durable owner of the current goal. * * Lifecycle rules (see the {@link GoalStatus} union for the full per-status map): * - Success: `markComplete` records success then clears the record (transient). * The model marks completion via the `UpdateGoal('complete')` tool; the turn * driver reads the status at the turn boundary. `markComplete` announces, then * clears the record. * - Task stop: `markBlocked(reason)` sets `blocked` when the model cannot * proceed, a prompt hook blocks, or a hard budget is reached. `blocked` is * resumable. * - Pause: `pauseGoal`, `pauseActiveGoal`, and the interrupt path * `pauseOnInterrupt` set `paused` (resumable); `cancelGoal` discards the * record entirely (no status — this is what `/goal cancel` does, the single * remove action). * - An aborted or failed turn is not terminal: it pauses the goal, so it stays * resumable — mirroring how `normalizeAfterReplay` demotes an `active` goal to * `paused` on agent resume. */ declare class GoalMode { private readonly agent; private state; constructor(agent: Agent); /** * Reconciles replayed goal state with runtime reality on agent resume. * * An `active` goal cannot still be running after a process restart (goal * continuation only advances inside a live turn), so it is demoted to * `paused`, requiring `/goal resume` to restart work. `paused` and `blocked` * goals are preserved (both resumable). Any stray `complete` (which should * have been followed by `goal.clear`) is removed. */ normalizeAfterReplay(): void; restoreCreate(record: AgentRecordOf<'goal.create'>): void; restoreUpdate(record: AgentRecordOf<'goal.update'>): void; restoreClear(_record: AgentRecordOf<'goal.clear'>): void; restoreForked(_record: AgentRecordOf<'forked'>): void; getGoal(): GoalToolResult; getActiveGoal(): GoalSnapshot | null; createGoal(input: CreateGoalInput_2, actor?: GoalActor): Promise; pauseGoal(input?: GoalReasonInput, actor?: GoalActor): Promise; /** * Parks the current active goal without throwing if it already stopped. Runtime * paths use this after a turn has ended, where the user may already have * paused, cleared, or otherwise changed the goal. */ pauseActiveGoal(input?: GoalReasonInput, actor?: GoalActor): Promise; resumeGoal(input?: GoalReasonInput, actor?: GoalActor): Promise; setBudgetLimits(input: { budgetLimits: GoalBudgetLimits; }, actor?: GoalActor): Promise; /** * Discards the current goal — the single user-facing "remove" action * (`/goal cancel`). There is no `cancelled` status: cancel clears the durable * record and returns the snapshot it removed, so callers can report what was * cancelled. Throws if no goal exists. (Internal callers that need to clear * without a return — e.g. `createGoal` replacing an existing goal — use the * private `clearInternal`.) */ cancelGoal(actor?: GoalActor): Promise; /** * Marks the goal `blocked`: the system stopped pursuing it for `reason` — the * model's `UpdateGoal('blocked')` (incl. objectives it deems unachievable), a * hard budget reached by the goal driver, or a prompt-hook block. * `blocked` is persisted and **resumable** via * `/goal resume` (it is a sibling of `paused`, not a dead end), so it emits a * `lifecycle` change. No-ops for a goal that is missing or not active, so a * user pause / clear is never overwritten. */ markBlocked(input?: GoalReasonInput, actor?: GoalActor): Promise; /** * Records goal success, then clears the durable record. `complete` is * transient: this records and emits a terminal `complete` change carrying the * final stats (so the UI/caller can render the outcome), then clears the goal * so the box disappears. Returns the final snapshot (status `complete`). No-ops * for a goal that is missing or not active. */ markComplete(input?: GoalReasonInput, actor?: GoalActor): Promise; /** * Parks an active goal when its live turn is aborted (Esc, shutdown, or any * other turn-level cancellation). This is **not** terminal: the goal becomes * `paused` and stays resumable via `/goal resume`, mirroring how * `normalizeAfterReplay` demotes an `active` goal on agent resume. No-ops for * a goal that is missing or already non-active, so a user pause / clear or an * already-stopped goal is never overwritten. */ pauseOnInterrupt(input?: { reason?: string; }): Promise; recordTokenUsage(tokenDelta: number): Promise; incrementTurn(): Promise; private clearInternal; private appendStatusUpdate; private appendGoalUpdate; private trackGoalCreated; private track; private applyStatus; private requireState; /** * Updates in-memory goal state and (unless `silent`) emits a `goal.updated` * event with the resulting snapshot. `silent` is used for per-step token / * wall-clock accounting so the UI is not updated on every step. */ private persistState; private emitGoalUpdated; /** Counter snapshot for a {@link GoalChange}. */ private statsOf; private toSnapshot; } declare interface GoalReasonInput { readonly reason?: string; } /** Public, computed view of the current goal. */ export declare interface GoalSnapshot { readonly goalId: string; readonly objective: string; readonly completionCriterion?: string; readonly status: GoalStatus; readonly turnsUsed: number; readonly tokensUsed: number; readonly wallClockMs: number; readonly budget: GoalBudgetReport; readonly terminalReason?: string; } declare interface GoalSnapshot_2 { readonly goalId: string; readonly objective: string; readonly completionCriterion?: string; readonly status: GoalStatus_2; readonly turnsUsed: number; readonly tokensUsed: number; readonly wallClockMs: number; readonly budget: GoalBudgetReport_2; readonly terminalReason?: string; } /** * Lifecycle status of a goal — deliberately minimal. The durable record only * ever holds `active`, `paused`, or `blocked`; `complete` is transient * (announce-then-clear) and never rests on disk. There is exactly one running * state, two resumable "stopped" states, and one success outcome: * * | Status | Persisted | Resumable | Set by | Meaning | * |------------|-----------|-----------|---------------------------------|--------------------------------------------------| * | `active` | yes | (running) | createGoal / resumeGoal | The goal driver may run continuation turns. | * | `paused` | yes | yes | pauseGoal / pauseActiveGoal / | User, interrupt, resume, or retryable runtime | * | | | | pauseOnInterrupt / | stop parked it; intact. | * | | | | normalizeAfterReplay | | * | `blocked` | yes | yes | markBlocked | The system stopped it for some `reason`. | * | `complete` | no | — | markComplete | Success — announced in a message, then cleared. | * * Only an `active` goal advances: accounting and continuation turns all gate on * `status === 'active'`. `paused` and `blocked` are the same kind of * thing — "the driver is not running continuation turns, but the goal is intact * and resumable via `/goal resume`" — differing only in *who* stopped it (the * user vs the system) and the human-readable `reason`. There is no separate * `impossible`, `budget_limited`, `error`, or `cancelled` status: an * unachievable goal or an exhausted budget becomes `blocked(+reason)`, * runtime/model/provider failures become `paused(+reason)`, and `cancelGoal` * discards the record entirely. See {@link GoalMode} * for the setters and the per-status notes below. */ export declare type GoalStatus = /** * The goal is live and the goal driver may run continuation turns toward it. * Set on creation (`createGoal`) and when a paused/blocked goal is resumed * (`resumeGoal`). The only status under which turns/tokens/wall-clock are * accounted and continuation turns run. */ 'active' /** * The user stopped the goal but it is fully intact and resumable via * `/goal resume`. Reached three ways: the user pauses (`pauseGoal`); a live * turn is aborted mid-flight, e.g. Esc/shutdown (`pauseOnInterrupt`); or a * agent is resumed from disk, where an `active` goal cannot still be running * and is demoted (`normalizeAfterReplay`); or a runtime/model/provider failure * parked it via `pauseActiveGoal`. */ | 'paused' /** * The *system* stopped pursuing the goal, for a reason carried in * `terminalReason`: the model reported it cannot proceed via * `UpdateGoal('blocked')` (an external blocker, or an objective it deems * unachievable); or a configured hard budget (token/turn/time) was reached. * Set by `markBlocked` from the model's `UpdateGoal`, the budget check in the * goal driver, and prompt-hook blocks. * Resumable like `paused` — `/goal resume` re-activates it; a plain message * just runs one normal turn without reactivating the loop. Editing the goal * while blocked takes effect on the next turn. */ | 'blocked' /** * Success: the model reported the objective met via `UpdateGoal('complete')`. * Set by `markComplete`. This status is **transient** * — `markComplete` emits the completion event and then clears the durable * record, so the goal box disappears and `complete` never rests on disk. */ | 'complete'; declare type GoalStatus_2 = 'active' | 'paused' | 'blocked' | 'complete'; /** Wrapper returned by goal read operations and tools. */ export declare interface GoalToolResult { readonly goal: GoalSnapshot | null; } export declare interface GoalUpdatedEvent { readonly type: 'goal.updated'; readonly snapshot: GoalSnapshot_2 | null; readonly change?: GoalChange_2; } declare interface GoogleGenAI {} declare interface GoogleGenAIOptions { apiKey?: string | undefined; model: string; /** * Override the endpoint the SDK talks to (forwarded as * `httpOptions.baseUrl`). When unset, the SDK falls back to its default * (`generativelanguage.googleapis.com` for Gemini, the regional * `*-aiplatform.googleapis.com` for Vertex). Set this to route through a * Gemini-compatible proxy/gateway. */ baseUrl?: string | undefined; vertexai?: boolean | undefined; project?: string | undefined; location?: string | undefined; stream?: boolean | undefined; defaultHeaders?: Record; clientFactory?: (auth: ProviderRequestAuth) => GoogleGenAI; } declare const HOOK_EVENT_TYPES: readonly ["PreToolUse", "PostToolUse", "PostToolUseFailure", "PermissionRequest", "PermissionResult", "UserPromptSubmit", "Stop", "StopFailure", "Interrupt", "SessionStart", "SessionEnd", "SubagentStart", "SubagentStop", "PreCompact", "PostCompact", "Notification"]; declare interface HookBlockDecision { readonly block: true; readonly reason: string; } declare interface HookDef { readonly event: HookEventType; readonly matcher?: string; readonly command: string; readonly timeout?: number; readonly cwd?: string; readonly env?: Readonly>; } declare type HookDefConfig = z.infer; declare const HookDefSchema: z.ZodObject<{ event: z.ZodEnum<{ PreToolUse: "PreToolUse"; PostToolUse: "PostToolUse"; PostToolUseFailure: "PostToolUseFailure"; PermissionRequest: "PermissionRequest"; PermissionResult: "PermissionResult"; UserPromptSubmit: "UserPromptSubmit"; Stop: "Stop"; StopFailure: "StopFailure"; Interrupt: "Interrupt"; SessionStart: "SessionStart"; SessionEnd: "SessionEnd"; SubagentStart: "SubagentStart"; SubagentStop: "SubagentStop"; PreCompact: "PreCompact"; PostCompact: "PostCompact"; Notification: "Notification"; }>; matcher: z.ZodOptional; command: z.ZodString; timeout: z.ZodOptional; }, z.core.$strict>; declare class HookEngine { private readonly options; private readonly byEvent; private readonly pendingTriggers; constructor(hooks?: readonly HookDef[], options?: HookEngineOptions); get summary(): Record; trigger(event: string, args?: HookEngineTriggerArgs): Promise; triggerBlock(event: string, args?: HookEngineTriggerArgs): Promise; fireAndForgetTrigger(event: string, args?: HookEngineTriggerArgs): Promise; private triggerInner; private matchingHooks; private emitTriggered; private emitResolved; } declare interface HookEngineOptions { readonly cwd?: string; readonly sessionId?: string; readonly onTriggered?: HookTriggeredCallback; readonly onResolved?: HookResolvedCallback; } declare interface HookEngineTriggerArgs { readonly matcherValue?: HookMatcherValue; readonly inputData?: Record; readonly signal?: AbortSignal; } declare type HookEventType = (typeof HOOK_EVENT_TYPES)[number]; declare type HookMatcherValue = string | readonly ContentPart[]; declare type HookResolvedCallback = (event: string, target: string, action: string, reason: string | undefined, durationMs: number) => void; declare interface HookResult { readonly action: 'allow' | 'block'; readonly message?: string; readonly reason?: string; readonly stdout?: string; readonly stderr?: string; readonly exitCode?: number; readonly timedOut?: boolean; readonly structuredOutput?: boolean; } export declare interface HookResultEvent { readonly type: 'hook.result'; readonly turnId?: number; readonly hookEvent: string; readonly content: string; readonly blocked?: boolean; } declare interface HookResultOrigin { readonly kind: 'hook_result'; readonly event: string; readonly blocked?: boolean; } declare interface HookResultOrigin_2 { readonly kind: 'hook_result'; readonly event: string; readonly blocked?: boolean; } declare type HookTriggeredCallback = (event: string, target: string, count: number) => void; /** * Raw-byte budget for a single image. base64 inflates bytes by ~4/3, so a * 3.75 MB raw payload stays under a 5 MB encoded ceiling. Tune to the active * provider's per-image limit. */ export declare const IMAGE_BYTE_BUDGET: number; export declare interface ImageCompressionCaptionInput { readonly original: ImageVariantDescription; readonly final: ImageVariantDescription; /** Absolute path where the pre-compression original can be read back. */ readonly originalPath?: string | null; } /** Wiring for the optional compression telemetry events. */ export declare interface ImageCompressionTelemetry { readonly client: TelemetryClient; /** Where the image entered the pipeline, e.g. 'read_media', 'tui_paste'. */ readonly source: string; } declare type ImageConfig = z.infer; declare const ImageConfigSchema: z.ZodObject<{ maxEdgePx: z.ZodOptional; readByteBudget: z.ZodOptional; }, z.core.$strip>; export declare class ImageLimits { private readonly env; private config; constructor(env?: Readonly>, config?: ImageConfig | undefined); /** Push (or clear, with `undefined`) the owning config. Called by the * config owner on load and reload, so limits hot-reload per owner. */ setConfig(config: ImageConfig | undefined): void; /** Longest-edge ceiling (px) for compressing images for the model. */ maxEdgePx(): number; /** Raw-byte budget for model-initiated image reads (ReadMediaFile default path). */ readByteBudget(): number; } declare interface ImageURLPart { type: 'image_url'; imageUrl: { url: string; id?: string; }; } declare interface ImageVariantDescription { /** Pixel size; pass 0 when unknown to omit the dimensions. */ readonly width: number; readonly height: number; readonly byteLength: number; readonly mimeType: string; } declare interface ImportContextPayload { /** Raw text supplied by the host. Core does not perform file I/O. */ readonly content: string; /** User-facing description of the source, for example `file 'notes.md'`. */ readonly source: string; } declare interface ImportContextRpcInput extends SessionIdRpcInput { readonly content: string; readonly source: string; } /** * Resolves a catalog provider entry to a supported wire type. Honors an * explicit `type`, otherwise infers from `npm`/`id`. Unknown providers return * `undefined` so callers can omit them instead of writing an invalid config. */ export declare function inferWireType(entry: CatalogProviderEntry): ProviderType_2 | undefined; declare class InjectionManager { protected readonly agent: Agent; private readonly injectors; private readonly goalInjector; private readonly toolsDiffInjector; constructor(agent: Agent); inject(): Promise; /** * Appends a fresh goal-context reminder at a continuation boundary. Append-only * (never mutates the prefix) so prompt caching is preserved; no-ops when goal * mode is off, the agent is not the main agent, or there is nothing to inject. */ injectGoal(): Promise; /** * Appends a loadable-tools diff announcement when the loadable set changed. * Boundary cadence (turn start + post-compaction); no-op when the disclosure * gate is closed or nothing changed. */ injectToolsDiff(): void; injectAfterCompaction(): Promise; /** * Post-compaction only: re-surface still-running background tasks. Folding the * live context to [recent user prompts, summary] drops the messages that * started them and their status updates, so without this the model can forget * a task is running and spawn a duplicate. Appended as an `injection`-origin * reminder, so the next compaction drops and rebuilds it — kept fresh, never * stacked. Runs only on the live path: restore replays the persisted reminder * and `FullCompaction.begin` short-circuits before compaction there. */ private injectActiveBackgroundTasks; onContextClear(): void; onContextCompacted(): void; onContextMessageRemoved(index: number): void; /** Per-step injectors plus the boundary goal injector, for lifecycle events. */ private lifecycleInjectors; private activeGoalInjector; } declare interface InjectionOrigin { readonly kind: 'injection'; readonly variant: string; } declare interface InjectionOrigin_2 { readonly kind: 'injection'; readonly variant: string; } /** * Install the proxy dispatcher as the process-wide undici dispatcher so every * `fetch` — LLM SDKs, in-process MCP HTTP, telemetry, OAuth, web tools, update * checks, downloads — honors the proxy. Call once at process startup, before * any network use. No-op (returns `false`) when no proxy variable is set. */ export declare function installGlobalProxyDispatcher(env?: Env, deps?: InstallProxyDeps): boolean; declare interface InstallPluginPayload { readonly source: string; } declare interface InstallProxyDeps { readonly setGlobalDispatcher: (dispatcher: Dispatcher) => void; readonly createProxyDispatcher: (env: Env) => Dispatcher | undefined; } /** Type guard for KimiError. */ export declare function isKimiError(error: unknown): error is KimiError; /** * Whether an image with this MIME may be sent to the model. Only the closed * accepted set passes; everything else must be refused at the entry point — * once an unsupported `image_url` lands in the session history, every later * request in the session is rejected by the provider. */ export declare function isModelAcceptedImageMime(mimeType: string): boolean; declare class JsonFileStore { private readonly dir; constructor(dir?: string); read(file: string): T | undefined; write(file: string, data: unknown): void; remove(file: string): void; } export declare type JsonObject = { readonly [key: string]: JsonValue; }; declare type JsonObject_2 = { readonly [key: string]: JsonValue_2; }; declare interface JsonObjectResponseFormat { readonly type: 'json_object'; } export declare type JsonPrimitive = string | number | boolean | null; declare type JsonPrimitive_2 = string | number | boolean | null; declare type JsonSchemaObject = Record; declare interface JsonSchemaResponseFormat { readonly type: 'json_schema'; readonly jsonSchema: { readonly name: string; readonly schema: JsonSchemaObject; readonly strict?: boolean | undefined; readonly description?: string | undefined; }; } export declare type JsonValue = JsonPrimitive | JsonValue[] | { readonly [key: string]: JsonValue; }; declare type JsonValue_2 = JsonPrimitive_2 | JsonValue_2[] | { readonly [key: string]: JsonValue_2; }; /** * Kimi Agent Operating System (KAOS) interface. * * This is the core abstraction that allows the agent to interact with * different execution environments (local, SSH, containers, etc.) * through a unified API. */ declare interface Kaos { /** Human-readable name for this environment (e.g. `"local"`, `"ssh:host"`). */ readonly name: string; /** * OS / shell probe describing the target environment. Populated by the * concrete Kaos implementation (e.g. `detectEnvironmentFromNode()` for * `LocalKaos`, a remote probe for `SSHKaos`). */ readonly osEnv: Environment; /** Return the path style used by this environment. */ pathClass(): 'posix' | 'win32'; /** Normalize the given path string (resolve `.` / `..` segments). */ normpath(path: string): string; /** Return the home directory of the current user. */ gethome(): string; /** Return the current working directory. */ getcwd(): string; /** Change the working directory to `path`. */ chdir(path: string): Promise; /** Return a new Kaos with the given `cwd`. */ withCwd(cwd: string): Kaos; /** * Return a new Kaos that overlays `env` onto every spawned process. * * The provided record is read when a process is spawned, so callers may * mutate a stable record to update future executions. */ withEnv(env: Record): Kaos; /** Return stat metadata for `path`. */ stat(path: string, options?: { followSymlinks?: boolean; }): Promise; /** Yield entry names in the directory at `path`. */ iterdir(path: string): AsyncGenerator; /** Yield paths matching `pattern` under `path`. */ glob(path: string, pattern: string, options?: { caseSensitive?: boolean; }): AsyncGenerator; /** Read up to `n` bytes from `path` (all bytes if `n` is omitted). */ readBytes(path: string, n?: number): Promise; /** * Read the file at `path` as a string. * * `errors` controls how decode errors are handled — mirrors Python's * `open(..., errors=)` parameter: * - `'strict'` (default): throw on any invalid byte for the encoding * - `'replace'`: substitute each invalid byte with U+FFFD (REPLACEMENT CHARACTER) * - `'ignore'`: drop invalid bytes silently */ readText(path: string, options?: { encoding?: BufferEncoding; errors?: 'strict' | 'replace' | 'ignore'; }): Promise; /** Yield lines from the file at `path` one by one. */ readLines(path: string, options?: { encoding?: BufferEncoding; errors?: 'strict' | 'replace' | 'ignore'; }): AsyncGenerator; /** Write raw bytes to `path`, returning the number of bytes written. */ writeBytes(path: string, data: Buffer): Promise; /** Write text to `path`, returning the number of characters written. */ writeText(path: string, data: string, options?: { mode?: 'w' | 'a'; encoding?: BufferEncoding; }): Promise; /** Create a directory at `path`. */ mkdir(path: string, options?: { parents?: boolean; existOk?: boolean; }): Promise; /** Spawn a process with the given arguments. */ exec(...args: string[]): Promise; /** Spawn a process with explicit environment variables. */ execWithEnv(args: string[], env?: Record): Promise; } /** * A running process spawned by a {@link Kaos} environment. * * Provides access to standard I/O streams, the process ID, and lifecycle * management (wait / kill). The interface is intentionally minimal so it * can be backed by local child processes, SSH sessions, or container runtimes. */ declare interface KaosProcess { /** Writable stream connected to the process's standard input. */ readonly stdin: Writable; /** Readable stream for the process's standard output. */ readonly stdout: Readable; /** Readable stream for the process's standard error. */ readonly stderr: Readable; /** Operating-system process ID. */ readonly pid: number; /** Exit code if the process has already terminated, otherwise `null`. */ readonly exitCode: number | null; /** Wait for the process to exit and return its exit code. */ wait(): Promise; /** Send a signal to the process (defaults to `SIGTERM`). */ kill(signal?: NodeJS.Signals): Promise; /** Release stdin/stdout/stderr resources owned by this process wrapper. */ dispose(): Promise | void; } export declare const KIMI_ERROR_INFO: { readonly 'config.invalid': { readonly title: "Invalid configuration"; readonly retryable: false; readonly public: true; readonly action: "Check config.toml and provider/model settings."; }; readonly 'session.not_found': { readonly title: "Session not found"; readonly retryable: false; readonly public: true; readonly action: "Check the session id or list available sessions."; }; readonly 'session.already_exists': { readonly title: "Session already exists"; readonly retryable: false; readonly public: true; readonly action: "Use a different session id or remove the existing session first."; }; readonly 'session.id_invalid': { readonly title: "Invalid session id"; readonly retryable: false; readonly public: true; readonly action: "Use a session id without path-traversal characters."; }; readonly 'session.id_required': { readonly title: "Session id required"; readonly retryable: false; readonly public: true; readonly action: "Provide a session id when calling this method."; }; readonly 'session.id_empty': { readonly title: "Session id is empty"; readonly retryable: false; readonly public: true; readonly action: "Provide a non-empty session id."; }; readonly 'session.title_empty': { readonly title: "Session title is empty"; readonly retryable: false; readonly public: true; readonly action: "Provide a non-empty session title."; }; readonly 'session.state_not_found': { readonly title: "Session state missing"; readonly retryable: false; readonly public: true; readonly action: "The session directory is corrupted or missing state.json."; }; readonly 'session.state_invalid': { readonly title: "Session state invalid"; readonly retryable: false; readonly public: true; readonly action: "The session state.json is corrupted; remove the session or repair the file."; }; readonly 'session.fork_active_turn': { readonly title: "Cannot fork session during active turn"; readonly retryable: true; readonly public: true; readonly action: "Wait for the active turn to complete before forking."; }; readonly 'session.export_not_found': { readonly title: "Session export directory missing"; readonly retryable: false; readonly public: true; readonly action: "The session has not been persisted to disk yet."; }; readonly 'session.export_missing_version': { readonly title: "Export version is missing"; readonly retryable: false; readonly public: true; readonly action: "Provide a version when exporting the session."; }; readonly 'session.closed': { readonly title: "Session is closed"; readonly retryable: false; readonly public: true; readonly action: "Create a new session."; }; readonly 'session.permission_mode_invalid': { readonly title: "Invalid permission mode"; readonly retryable: false; readonly public: true; readonly action: "Use one of: yolo / manual / auto."; }; readonly 'session.thinking_empty': { readonly title: "Thinking value is empty"; readonly retryable: false; readonly public: true; readonly action: "Provide a non-empty thinking option."; }; readonly 'session.model_empty': { readonly title: "Model is empty"; readonly retryable: false; readonly public: true; readonly action: "Provide a non-empty model identifier."; }; readonly 'session.plan_mode_invalid': { readonly title: "Invalid plan mode"; readonly retryable: false; readonly public: true; readonly action: "Provide a boolean plan mode."; }; readonly 'session.approval_handler_error': { readonly title: "Approval handler threw"; readonly retryable: false; readonly public: true; readonly action: "Inspect the SDK approval handler for an unhandled exception."; }; readonly 'session.question_handler_error': { readonly title: "Question handler threw"; readonly retryable: false; readonly public: true; readonly action: "Inspect the SDK question handler for an unhandled exception."; }; readonly 'session.init_failed': { readonly title: "Session init failed"; readonly retryable: false; readonly public: false; readonly action: "Review the init failure details and try again."; }; readonly 'agent.not_found': { readonly title: "Agent not found"; readonly retryable: false; readonly public: true; readonly action: "Check the agent id or list available agents."; }; readonly 'turn.agent_busy': { readonly title: "Agent is busy"; readonly retryable: true; readonly public: true; readonly action: "Wait for the current turn to finish or steer it."; }; readonly 'goal.already_exists': { readonly title: "A goal is already active"; readonly retryable: false; readonly public: true; readonly action: "Use `/goal replace ` to replace the current goal."; }; readonly 'goal.not_found': { readonly title: "No goal found"; readonly retryable: false; readonly public: true; readonly action: "Start a goal with `/goal ` first."; }; readonly 'goal.objective_empty': { readonly title: "Goal objective is empty"; readonly retryable: false; readonly public: true; readonly action: "Provide a non-empty objective."; }; readonly 'goal.objective_too_long': { readonly title: "Goal objective is too long"; readonly retryable: false; readonly public: true; readonly action: "Keep the objective under 4000 characters; reference long details by file path."; }; readonly 'goal.status_invalid': { readonly title: "Invalid goal status transition"; readonly retryable: false; readonly public: true; readonly action: "Use a status allowed for this actor (complete, blocked, or impossible)."; }; readonly 'goal.metadata_reserved': { readonly title: "Goal metadata is reserved"; readonly retryable: false; readonly public: true; readonly action: "Do not write metadata.custom.goal directly; use the goal lifecycle methods."; }; readonly 'goal.not_resumable': { readonly title: "Goal is not resumable"; readonly retryable: false; readonly public: true; readonly action: "Only paused goals can be resumed."; }; readonly 'model.not_configured': { readonly title: "No model configured"; readonly retryable: false; readonly public: true; readonly action: "Set a default model in config.toml or via setModel."; }; readonly 'model.config_invalid': { readonly title: "Invalid model configuration"; readonly retryable: false; readonly public: true; readonly action: "Check the model and provider entries in config.toml."; }; readonly 'auth.login_required': { readonly title: "Login required"; readonly retryable: false; readonly public: true; readonly action: "Run the login flow for the provider before retrying."; }; readonly 'context.overflow': { readonly title: "Context window overflow"; readonly retryable: true; readonly public: true; readonly action: "Compact the conversation or start a new session."; }; readonly 'loop.max_steps_exceeded': { readonly title: "Turn exceeded max steps"; readonly retryable: false; readonly public: true; readonly action: "Increase loop_control.max_steps_per_turn in config.toml or split the task."; }; readonly 'provider.api_error': { readonly title: "Provider API error"; readonly retryable: false; readonly public: true; readonly action: "Inspect details.statusCode / details.requestId; check provider status."; }; readonly 'provider.filtered': { readonly title: "Provider filtered response"; readonly retryable: false; readonly public: true; readonly action: "Revise the prompt or model configuration to avoid provider safety filtering."; }; readonly 'provider.rate_limit': { readonly title: "Provider rate limit"; readonly retryable: true; readonly public: true; readonly action: "Retry after a delay or reduce request frequency."; }; readonly 'provider.auth_error': { readonly title: "Provider authentication error"; readonly retryable: false; readonly public: true; readonly action: "Re-authenticate with the provider."; }; readonly 'provider.connection_error': { readonly title: "Provider connection error"; readonly retryable: true; readonly public: true; readonly action: "Check network connectivity and retry."; }; readonly 'skill.not_found': { readonly title: "Skill not found"; readonly retryable: false; readonly public: true; readonly action: "List available skills via the skill registry."; }; readonly 'skill.type_unsupported': { readonly title: "Skill type not supported"; readonly retryable: false; readonly public: true; readonly action: "Only inline skills can be activated by the user."; }; readonly 'skill.name_empty': { readonly title: "Skill name is empty"; readonly retryable: false; readonly public: true; readonly action: "Provide a non-empty skill name."; }; readonly 'records.write_failed': { readonly title: "Failed to write records"; readonly retryable: true; readonly public: true; readonly action: "Check disk space and permissions on the session directory."; }; readonly 'compaction.failed': { readonly title: "Compaction failed"; readonly retryable: false; readonly public: true; readonly action: "Inspect logs and consider increasing compaction limits."; }; readonly 'compaction.unable': { readonly title: "Unable to compact"; readonly retryable: false; readonly public: true; readonly action: "The current history has no prefix that can be compacted (e.g. only a pending user message). Start a new turn or session instead."; }; readonly 'task.task_id_empty': { readonly title: "Background task id is empty"; readonly retryable: false; readonly public: true; readonly action: "Provide a non-empty task id."; }; readonly 'mcp.server_not_found': { readonly title: "MCP server not found"; readonly retryable: false; readonly public: true; readonly action: "List configured MCP servers and check the requested name."; }; readonly 'mcp.server_disabled': { readonly title: "MCP server is disabled"; readonly retryable: false; readonly public: true; readonly action: "Enable the MCP server entry in config before reconnecting."; }; readonly 'mcp.startup_failed': { readonly title: "MCP server startup failed"; readonly retryable: true; readonly public: true; readonly action: "Inspect the MCP server log or call reconnect once the server is healthy."; }; readonly 'mcp.tool_name_collision': { readonly title: "MCP tool name collision"; readonly retryable: false; readonly public: true; readonly action: "Rename one of the colliding MCP tools or servers so their qualified names are unique."; }; readonly 'plugin.not_found': { readonly title: "Plugin not found"; readonly retryable: false; readonly public: true; readonly action: "List installed plugins via /plugins and check the requested id."; }; readonly 'plugin.load_failed': { readonly title: "Plugin state failed to load"; readonly retryable: true; readonly public: true; readonly action: "Fix the installed.json file under $KIMI_CODE_HOME/plugins/ and run /plugins reload."; }; readonly 'request.invalid': { readonly title: "Invalid request"; readonly retryable: false; readonly public: true; readonly action: "Check the input shape matches the API contract."; }; readonly 'request.work_dir_required': { readonly title: "workDir is required"; readonly retryable: false; readonly public: true; readonly action: "Provide workDir in the request payload."; }; readonly 'request.prompt_input_empty': { readonly title: "Prompt input is empty"; readonly retryable: false; readonly public: true; readonly action: "Provide non-empty prompt input."; }; readonly 'shell.git_bash_not_found': { readonly title: "Git Bash not found"; readonly retryable: false; readonly public: true; readonly action: "Install Git for Windows from https://gitforwindows.org/ or set KIMI_SHELL_PATH to a bash.exe."; }; readonly not_implemented: { readonly title: "Not implemented"; readonly retryable: false; readonly public: true; readonly action: "This feature is not implemented yet."; }; readonly internal: { readonly title: "Internal error"; readonly retryable: false; readonly public: true; readonly action: "Inspect logs or report the issue with diagnostics."; }; }; export declare interface KimiAuthCompleteFeedbackUploadInput { readonly uploadId: number; readonly parts: readonly KimiAuthCompleteFeedbackUploadPart[]; } export declare interface KimiAuthCompleteFeedbackUploadPart { readonly partNumber: number; readonly etag: string; } export declare interface KimiAuthCreateFeedbackUploadUrlInput { readonly feedbackId: number; readonly filename: string; readonly size: number; readonly sha256: string; } export declare interface KimiAuthCreateFeedbackUploadUrlOk { readonly kind: 'ok'; readonly uploadId: number; readonly parts: readonly KimiAuthFeedbackUploadPart[]; } export declare type KimiAuthCreateFeedbackUploadUrlResult = KimiAuthCreateFeedbackUploadUrlOk | FetchFeedbackUploadError; export declare class KimiAuthFacade { private readonly options; private readonly toolkit; constructor(options: KimiAuthFacadeOptions); status(providerName?: string | undefined): Promise; login(providerName?: string | undefined, options?: KimiAuthLoginOptions): Promise; logout(providerName?: string | undefined): Promise; getManagedUsage(providerName?: string | undefined): Promise; submitFeedback(input: KimiAuthSubmitFeedbackInput, providerName?: string | undefined): Promise; createFeedbackUploadUrl(input: KimiAuthCreateFeedbackUploadUrlInput, providerName?: string | undefined): Promise; completeFeedbackUpload(input: KimiAuthCompleteFeedbackUploadInput, providerName?: string | undefined): Promise; getCachedAccessToken(providerName?: string, oauthRef?: OAuthRef | undefined): Promise; readonly resolveOAuthTokenProvider: (providerName: string, oauthRef?: OAuthRef | undefined) => BearerTokenProvider; private resolveManagedAuth; private resolveRuntimeManagedAuth; private runtimeOAuthRef; } declare interface KimiAuthFacadeOptions { readonly homeDir: string; readonly configPath: string; readonly identity?: KimiHostIdentity | undefined; readonly onConfigUpdated?: ((config: KimiConfig) => void) | undefined; readonly onRefresh?: ((outcome: OAuthRefreshOutcome) => void) | undefined; } export declare interface KimiAuthFeedbackUploadPart { readonly partNumber: number; readonly url: string; readonly method: string; readonly size: number; } declare type KimiAuthLoginOptions = Omit; export declare interface KimiAuthLoginResult { readonly providerName: string; readonly ok: true; readonly defaultModel: string; readonly defaultThinking: boolean; readonly configPath?: string | undefined; } export declare interface KimiAuthLogoutResult { readonly providerName: string; readonly ok: true; } export declare interface KimiAuthSubmitFeedbackInput { readonly content: string; readonly sessionId: string; readonly version: string; readonly os: string; readonly model: string | null; readonly contact?: string; readonly info?: Record; } export declare type KimiConfig = z.infer; export declare type KimiConfigPatch = z.infer; declare const KimiConfigPatchSchema: z.ZodObject<{ providers: z.ZodOptional>; apiKey: z.ZodOptional>; baseUrl: z.ZodOptional>; defaultModel: z.ZodOptional>; oauth: z.ZodOptional; key: z.ZodString; oauthHost: z.ZodOptional; }, z.core.$strip>>>; env: z.ZodOptional>>; customHeaders: z.ZodOptional>>; source: z.ZodOptional>>; }, z.core.$strip>>>; defaultProvider: z.ZodOptional; defaultModel: z.ZodOptional; models: z.ZodOptional; model: z.ZodOptional; maxContextSize: z.ZodOptional; maxOutputSize: z.ZodOptional>; capabilities: z.ZodOptional>>; displayName: z.ZodOptional>; reasoningKey: z.ZodOptional>; protocol: z.ZodOptional>>; adaptiveThinking: z.ZodOptional>; supportEfforts: z.ZodOptional>>; defaultEffort: z.ZodOptional>; betaApi: z.ZodOptional>; overrides: z.ZodOptional>>; maxContextSize: z.ZodOptional; maxOutputSize: z.ZodOptional>; displayName: z.ZodOptional>; reasoningKey: z.ZodOptional>; adaptiveThinking: z.ZodOptional>; supportEfforts: z.ZodOptional>>; defaultEffort: z.ZodOptional>; }, z.core.$strip>>>; }, z.core.$strip>>>; thinking: z.ZodOptional>; effort: z.ZodOptional>; keep: z.ZodOptional>; }, z.core.$strip>>; planMode: z.ZodOptional; yolo: z.ZodOptional; defaultPermissionMode: z.ZodOptional>; defaultPlanMode: z.ZodOptional; permission: z.ZodOptional; scope: z.ZodDefault>; pattern: z.ZodString; reason: z.ZodOptional; }, z.core.$strip>>>>; }, z.core.$strip>>; hooks: z.ZodOptional; matcher: z.ZodOptional; command: z.ZodString; timeout: z.ZodOptional; }, z.core.$strict>>>; services: z.ZodOptional>; apiKey: z.ZodOptional>; oauth: z.ZodOptional; key: z.ZodString; oauthHost: z.ZodOptional; }, z.core.$strip>>>; customHeaders: z.ZodOptional>>; }, z.core.$strip>>; moonshotFetch: z.ZodOptional>; apiKey: z.ZodOptional>; oauth: z.ZodOptional; key: z.ZodString; oauthHost: z.ZodOptional; }, z.core.$strip>>>; customHeaders: z.ZodOptional>>; }, z.core.$strip>>; }, z.core.$strip>>; mergeAllAvailableSkills: z.ZodOptional; extraSkillDirs: z.ZodOptional>; loopControl: z.ZodOptional>; maxRetriesPerStep: z.ZodOptional>; maxRalphIterations: z.ZodOptional>; reservedContextSize: z.ZodOptional>; compactionTriggerRatio: z.ZodOptional>; }, z.core.$strip>>; background: z.ZodOptional>; keepAliveOnExit: z.ZodOptional>; bashAutoBackgroundOnTimeout: z.ZodOptional>; bashTaskTimeoutS: z.ZodOptional>; killGracePeriodMs: z.ZodOptional>; printWaitCeilingS: z.ZodOptional>; printBackgroundMode: z.ZodOptional>>; printMaxTurns: z.ZodOptional>; }, z.core.$strip>>; subagent: z.ZodOptional>; }, z.core.$strip>>; image: z.ZodOptional>; readByteBudget: z.ZodOptional>; }, z.core.$strip>>; modelCatalog: z.ZodOptional>; refreshOnStart: z.ZodOptional>; }, z.core.$strip>>; experimental: z.ZodOptional>; telemetry: z.ZodOptional; }, z.core.$strict>; export declare interface KimiConfigRpc { resolveConfigPath(input?: ResolveKimiConfigPathInput): Promise; validateConfigToml(input: ValidateKimiConfigTomlInput): Promise; } export declare class KimiConfigRpcClient implements KimiConfigRpc { private readonly ready; constructor(); resolveConfigPath(input?: ResolveKimiConfigPathInput): Promise; validateConfigToml(input: ValidateKimiConfigTomlInput): Promise; } declare const KimiConfigSchema: z.ZodObject<{ providers: z.ZodDefault; apiKey: z.ZodOptional; baseUrl: z.ZodOptional; defaultModel: z.ZodOptional; oauth: z.ZodOptional; key: z.ZodString; oauthHost: z.ZodOptional; }, z.core.$strip>>; env: z.ZodOptional>; customHeaders: z.ZodOptional>; source: z.ZodOptional>; }, z.core.$strip>>>; defaultProvider: z.ZodOptional; defaultModel: z.ZodOptional; models: z.ZodOptional; capabilities: z.ZodOptional>; displayName: z.ZodOptional; reasoningKey: z.ZodOptional; protocol: z.ZodOptional>; adaptiveThinking: z.ZodOptional; supportEfforts: z.ZodOptional>; defaultEffort: z.ZodOptional; betaApi: z.ZodOptional; overrides: z.ZodOptional>>; maxContextSize: z.ZodOptional; maxOutputSize: z.ZodOptional>; displayName: z.ZodOptional>; reasoningKey: z.ZodOptional>; adaptiveThinking: z.ZodOptional>; supportEfforts: z.ZodOptional>>; defaultEffort: z.ZodOptional>; }, z.core.$strip>>; }, z.core.$strip>>>; thinking: z.ZodOptional; effort: z.ZodOptional; keep: z.ZodOptional; }, z.core.$strip>>; planMode: z.ZodOptional; yolo: z.ZodOptional; defaultPermissionMode: z.ZodOptional>; defaultPlanMode: z.ZodOptional; permission: z.ZodOptional; scope: z.ZodDefault>; pattern: z.ZodString; reason: z.ZodOptional; }, z.core.$strip>>>; }, z.core.$strip>>; hooks: z.ZodOptional; matcher: z.ZodOptional; command: z.ZodString; timeout: z.ZodOptional; }, z.core.$strict>>>; services: z.ZodOptional; apiKey: z.ZodOptional; oauth: z.ZodOptional; key: z.ZodString; oauthHost: z.ZodOptional; }, z.core.$strip>>; customHeaders: z.ZodOptional>; }, z.core.$strip>>; moonshotFetch: z.ZodOptional; apiKey: z.ZodOptional; oauth: z.ZodOptional; key: z.ZodString; oauthHost: z.ZodOptional; }, z.core.$strip>>; customHeaders: z.ZodOptional>; }, z.core.$strip>>; }, z.core.$strip>>; mergeAllAvailableSkills: z.ZodOptional; extraSkillDirs: z.ZodOptional>; loopControl: z.ZodOptional; maxRetriesPerStep: z.ZodOptional; maxRalphIterations: z.ZodOptional; reservedContextSize: z.ZodOptional; compactionTriggerRatio: z.ZodOptional; }, z.core.$strip>>; background: z.ZodOptional; keepAliveOnExit: z.ZodOptional; bashAutoBackgroundOnTimeout: z.ZodOptional; bashTaskTimeoutS: z.ZodOptional; killGracePeriodMs: z.ZodOptional; printWaitCeilingS: z.ZodOptional; printBackgroundMode: z.ZodOptional>; printMaxTurns: z.ZodOptional; }, z.core.$strip>>; subagent: z.ZodOptional; }, z.core.$strip>>; image: z.ZodOptional; readByteBudget: z.ZodOptional; }, z.core.$strip>>; modelCatalog: z.ZodOptional; refreshOnStart: z.ZodOptional; }, z.core.$strip>>; experimental: z.ZodOptional>; telemetry: z.ZodOptional; raw: z.ZodOptional>; }, z.core.$strip>; export declare interface KimiConfigValidationIssue { readonly path: readonly KimiConfigValidationPathSegment[]; readonly message: string; } export declare type KimiConfigValidationPathSegment = string | number; declare class KimiCore implements PromisableMethods { protected readonly rpcClient: CoreRPCClient; readonly sdk: Promise; readonly homeDir: string; readonly configPath: string; readonly sessions: Map; readonly telemetry: TelemetryClient; private kaos; private runtime; private config; private configWarnings; private readonly runtimeOverride; private readonly userHomeDir; private readonly kimiRequestHeaders; private readonly resolveOAuthTokenProvider; private readonly skillDirs; private readonly sessionStore; private readonly globalMcpConfig; private readonly globalMcpOAuth; private readonly globalMcpOAuthFlows; readonly plugins: PluginManager; private pluginsReady; private pluginsLoadError; private readonly appVersion; private readonly experimentalFlags; /** `true` when the host runs `kimi -p` (v1 print mode); see `withPrintModeDefaults`. */ private readonly printMode; /** Owner-scoped [image] limits; reload pushes the new config via setConfig. */ readonly imageLimits: ImageLimits; constructor(rpcClient: CoreRPCClient, options?: KimiCoreOptions); createSession(input: CreateSessionPayload): Promise; createSessionWithOverrides(input: CreateSessionPayload, overrides: { kaos?: Kaos; persistenceKaos?: Kaos; }): Promise; getCoreInfo(): CoreInfo; getExperimentalFeatures(): readonly ExperimentalFeatureState[]; closeSession({ sessionId }: CloseSessionPayload): Promise; archiveSession({ sessionId }: ArchiveSessionPayload): Promise; deleteSession({ sessionId }: DeleteSessionPayload): Promise; resumeSession(input: ResumeSessionPayload): Promise; resumeSessionWithOverrides(input: ResumeSessionPayload, overrides: { kaos?: Kaos; persistenceKaos?: Kaos; forcePluginSessionStartReminder?: boolean; }): Promise; reloadSession(input: ReloadSessionPayload): Promise; forkSession(input: ForkSessionPayload): Promise; listSessions(input?: ListSessionsPayload): Promise; renameSession({ sessionId, ...payload }: RenameSessionRequest): Promise; exportSession(input: ExportSessionPayload): Promise; getKimiConfig(input?: GetKimiConfigPayload): Promise; getConfigDiagnostics(_input?: EmptyPayload): Promise; setKimiConfig(input: SetKimiConfigPayload): Promise; removeKimiProvider(input: RemoveKimiProviderPayload): Promise; listGlobalMcpServers(_input?: EmptyPayload): Promise; addGlobalMcpServer({ server }: PutGlobalMcpServerPayload): Promise; updateGlobalMcpServer({ server }: PutGlobalMcpServerPayload): Promise; removeGlobalMcpServer({ name }: GlobalMcpServerNamePayload): Promise; beginGlobalMcpServerAuth({ name }: GlobalMcpServerNamePayload): Promise; completeGlobalMcpServerAuth({ flowId, timeoutMs }: CompleteGlobalMcpServerAuthPayload, options?: { readonly signal?: AbortSignal; }): Promise; cancelGlobalMcpServerAuth({ flowId }: CancelGlobalMcpServerAuthPayload): Promise; resetGlobalMcpServerAuth({ name }: GlobalMcpServerNamePayload): Promise; testGlobalMcpServer({ name, cwd }: TestGlobalMcpServerPayload): Promise; prompt({ sessionId, ...payload }: SessionAgentPayload): Promise; runShellCommand({ sessionId, ...payload }: SessionAgentPayload): Promise; cancelShellCommand({ sessionId, ...payload }: SessionAgentPayload): Promise; steer({ sessionId, ...payload }: SessionAgentPayload): Promise; cancel({ sessionId, ...payload }: SessionAgentPayload): Promise; undoHistory({ sessionId, ...payload }: SessionAgentPayload): Promise; setModel({ sessionId, ...payload }: SessionAgentPayload): Promise; setThinking({ sessionId, ...payload }: SessionAgentPayload): Promise; setPermission({ sessionId, ...payload }: SessionAgentPayload): Promise; getModel({ sessionId, ...payload }: SessionAgentPayload): Promise; enterPlan({ sessionId, ...payload }: SessionAgentPayload): Promise; cancelPlan({ sessionId, ...payload }: SessionAgentPayload): Promise; clearPlan({ sessionId, ...payload }: SessionAgentPayload): Promise; enterSwarm({ sessionId, ...payload }: SessionAgentPayload): Promise; exitSwarm({ sessionId, ...payload }: SessionAgentPayload): Promise; getSwarmMode({ sessionId, ...payload }: SessionAgentPayload): Promise; beginCompaction({ sessionId, ...payload }: SessionAgentPayload): Promise; cancelCompaction({ sessionId, ...payload }: SessionAgentPayload): Promise; registerTool({ sessionId, ...payload }: SessionAgentPayload): Promise; unregisterTool({ sessionId, ...payload }: SessionAgentPayload): Promise; setActiveTools({ sessionId, ...payload }: SessionAgentPayload): Promise; stopBackground({ sessionId, ...payload }: SessionAgentPayload): Promise; detachBackground({ sessionId, ...payload }: SessionAgentPayload): Promise; clearContext({ sessionId, ...payload }: SessionAgentPayload): Promise; importContext({ sessionId, ...payload }: SessionAgentPayload): Promise; activateSkill({ sessionId, ...payload }: SessionAgentPayload): Promise; activatePluginCommand({ sessionId, ...payload }: SessionAgentPayload): Promise; getBackgroundOutput({ sessionId, ...payload }: SessionAgentPayload): Promise; getContext({ sessionId, ...payload }: SessionAgentPayload): Promise; getConfig({ sessionId, ...payload }: SessionAgentPayload): Promise; getPermission({ sessionId, ...payload }: SessionAgentPayload): Promise; getPlan({ sessionId, ...payload }: SessionAgentPayload): Promise; getUsage({ sessionId, ...payload }: SessionAgentPayload): Promise; getTools({ sessionId, ...payload }: SessionAgentPayload): Promise; getBackground({ sessionId, ...payload }: SessionAgentPayload): Promise; updateSessionMetadata({ sessionId, ...payload }: UpdateSessionMetadataRequest): Promise; getSessionMetadata({ sessionId, ...payload }: SessionScopedPayload): SessionMeta; listSkills({ sessionId, ...payload }: SessionScopedPayload): Promise; /** * List the skills available for a workspace working directory without * requiring a session. Mirrors `Session.loadSkills` exactly (same roots, * same discovery order, same built-ins) so the result matches what a new * session created in `workDir` would see. Used to populate the composer * skill menu before a session exists. */ listWorkspaceSkills({ workDir, }: ListWorkspaceSkillsPayload): Promise; listPluginCommands({ sessionId, ...payload }: SessionScopedPayload): readonly PluginCommandDef[]; listMcpServers({ sessionId, ...payload }: SessionScopedPayload): readonly McpServerInfo[]; getMcpStartupMetrics({ sessionId, ...payload }: SessionScopedPayload): Promise; reconnectMcpServer({ sessionId, ...payload }: SessionScopedPayload): Promise; generateAgentsMd({ sessionId, ...payload }: SessionScopedPayload): Promise; getSessionWarnings({ sessionId, ...payload }: SessionScopedPayload): Promise; waitForBackgroundTasksOnPrint({ sessionId, ...payload }: SessionScopedPayload): Promise; handlePrintMainTurnCompleted({ sessionId, ...payload }: SessionScopedPayload): Promise<'finish' | 'continue'>; addAdditionalDir({ sessionId, ...payload }: SessionScopedPayload): Promise; startBtw({ sessionId, ...payload }: SessionAgentPayload): Promise; createGoal({ sessionId, ...payload }: SessionAgentPayload): Promise; getGoal({ sessionId, ...payload }: SessionAgentPayload): Promise; pauseGoal({ sessionId, ...payload }: SessionAgentPayload): Promise; resumeGoal({ sessionId, ...payload }: SessionAgentPayload): Promise; cancelGoal({ sessionId, ...payload }: SessionAgentPayload): Promise; getCronTasks({ sessionId, ...payload }: SessionAgentPayload): Promise; installPlugin(payload: InstallPluginPayload): Promise; listPlugins(_: EmptyPayload): Promise; setPluginEnabled({ id, enabled }: SetPluginEnabledPayload): Promise; setPluginMcpServerEnabled({ id, server, enabled, }: SetPluginMcpServerEnabledPayload): Promise; removePlugin({ id }: RemovePluginPayload): Promise; reloadPlugins(_: EmptyPayload): Promise; getPluginInfo({ id }: GetPluginInfoPayload): Promise; private assertPluginsLoaded; private resolveRuntime; private getKaos; private resolveSessionSkillConfig; private resolveProviderManager; private mergePluginMcpConfig; private withManagedKimiPluginEnv; private managedKimiCodeEnvForPlugins; private requireSession; private sessionApi; private reloadProviderManager; private readConfigForWrite; private reloadRuntimeConfig; private setRuntimeConfig; /** * Config bound to a newly created/resumed session. In print mode (`kimi -p`, * v1) the print-mode defaults are merged in; explicit user config wins. The * raw `this.config` is left untouched so `getKimiConfig` and config writes * still round-trip the user's file values. */ private withPrintModeDefaults; private clearRuntimeCache; private refreshSessionRuntimeConfig; } declare interface KimiCoreOptions { readonly homeDir?: string | undefined; readonly configPath?: string | undefined; readonly runtime?: ToolServices | undefined; readonly kimiRequestHeaders?: Record | undefined; readonly resolveOAuthTokenProvider?: OAuthTokenProviderResolver | undefined; readonly skillDirs?: readonly string[]; readonly telemetry?: TelemetryClient | undefined; readonly appVersion?: string; /** * Host UI mode (`'print'` for `kimi -p`, `'cli'` for the TUI, ...). When * `'print'`, sessions are created with the print-mode config defaults from * `applyPrintModeConfigDefaults` (user-set values still win). */ readonly uiMode?: string | undefined; } /** * The single Kimi error class. * * Discrimination is always by `code`. Cross-process consumers receive * `KimiErrorPayload` and must branch on `code` rather than class identity. */ export declare class KimiError extends Error { readonly code: KimiErrorCode; readonly details?: Record; readonly cause?: unknown; constructor(code: KimiErrorCode, message: string, options?: KimiErrorOptions); } export declare type KimiErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes]; declare type KimiErrorCode_2 = 'config.invalid' | 'session.not_found' | 'session.already_exists' | 'session.id_invalid' | 'session.id_required' | 'session.id_empty' | 'session.title_empty' | 'session.state_not_found' | 'session.state_invalid' | 'session.fork_active_turn' | 'session.undo_unavailable' | 'session.export_not_found' | 'session.export_missing_version' | 'session.export_output_conflict' | 'session.export_too_large' | 'session.closed' | 'session.permission_mode_invalid' | 'session.thinking_empty' | 'session.model_empty' | 'session.plan_mode_invalid' | 'session.approval_handler_error' | 'session.question_handler_error' | 'session.init_failed' | 'agent.not_found' | 'turn.agent_busy' | 'goal.already_exists' | 'goal.not_found' | 'goal.objective_empty' | 'goal.objective_too_long' | 'goal.status_invalid' | 'goal.metadata_reserved' | 'goal.not_resumable' | 'goal.unsupported_agent' | 'model.not_configured' | 'model.config_invalid' | 'profile.thinking_alias_conflict' | 'model.not_found' | 'auth.login_required' | 'auth.provisioning_required' | 'auth.token_missing' | 'auth.token_unauthorized' | 'auth.model_not_resolved' | 'context.overflow' | 'loop.max_steps_exceeded' | 'provider.api_error' | 'provider.filtered' | 'provider.rate_limit' | 'provider.auth_error' | 'provider.connection_error' | 'provider.overloaded' | 'provider.not_found' | 'skill.not_found' | 'skill.type_unsupported' | 'skill.name_empty' | 'records.write_failed' | 'compaction.failed' | 'compaction.unable' | 'task.task_id_empty' | 'usage.turn_id_conflict' | 'mcp.server_not_found' | 'mcp.server_disabled' | 'mcp.startup_failed' | 'mcp.tool_name_collision' | 'message.not_found' | 'plugin.not_found' | 'plugin.load_failed' | 'request.invalid' | 'request.work_dir_required' | 'request.prompt_input_empty' | 'prompt.not_found' | 'prompt.already_completed' | 'session.busy' | 'shell.git_bash_not_found' | 'workspace.not_found' | 'terminal.not_found' | 'file.not_found' | 'file.too_large' | 'fs.path_not_found' | 'fs.permission_denied' | 'fs.path_escapes' | 'fs.is_directory' | 'fs.is_binary' | 'fs.too_large' | 'fs.already_exists' | 'fs.too_many_results' | 'fs.grep_timeout' | 'fs.git_unavailable' | 'os.fs.not_found' | 'os.fs.is_directory' | 'os.fs.not_directory' | 'os.fs.already_exists' | 'os.fs.permission_denied' | 'os.fs.not_empty' | 'os.fs.unavailable' | 'os.fs.unknown' | 'os.process.spawn_failed' | 'os.process.kill_failed' | 'storage.not_found' | 'storage.decode_failed' | 'storage.corrupted' | 'storage.io_failed' | 'storage.locked' | 'wire.duplicate_op' | 'wire.cycle' | 'wire.unknown_record' | 'validation.failed' | 'not_implemented' | 'internal'; export declare interface KimiErrorInfo { readonly title: string; readonly retryable: boolean; /** * Whether the code is a stable public contract. `false` reserves the * right to rename or remove without a major version bump. */ readonly public: boolean; readonly action?: string; } export declare interface KimiErrorOptions { /** JSON-serializable structured details. */ readonly details?: Record; /** Original error or value. Local-only; never serialized to the wire. */ readonly cause?: unknown; } /** * Wire-safe payload of a Kimi error. * * The structure passed across process / language boundaries (RPC, events, * telemetry, SDK wrappers). Class identity does not survive the boundary; * downstream code must branch on `code` rather than `instanceof`. * * `details` is JSON-serialized. `cause` is intentionally absent -- it is * local-only diagnostic state and must not cross the boundary. */ export declare interface KimiErrorPayload { readonly code: KimiErrorCode; readonly message: string; readonly name?: string; readonly details?: Record; readonly retryable: boolean; } declare interface KimiErrorPayload_2 { readonly code: KimiErrorCode_2; readonly message: string; readonly name?: string; readonly details?: Record; readonly retryable: boolean; readonly cause?: KimiErrorPayload_2; } export declare class KimiForCodingProvider implements ModelProvider { private readonly model; private readonly baseUrl; private readonly promptCacheKey; private readonly defaultHeaders; private readonly toolkit; private readonly homeDir; private readonly identity; private readonly oauthRef; constructor(options: KimiForCodingProviderOptions); get defaultModel(): string; resolveProviderConfig(model: string): ResolvedRuntimeProvider; resolveAuth(_model: string, _options?: { readonly log?: Logger; }): (request: (auth: ProviderRequestAuth) => Promise) => Promise; private buildAuth; } export declare interface KimiForCodingProviderOptions extends KimiHostIdentity { readonly homeDir?: string; readonly model?: string; readonly baseUrl?: string; readonly promptCacheKey?: string; readonly defaultHeaders?: Record; } export declare class KimiHarness { private readonly rpc; readonly homeDir: string; readonly configPath: string; readonly auth: KimiAuthFacade; private readonly identity; private readonly uiMode; private readonly telemetry; private readonly activeSessions; private readonly ensureConfigFileImpl; private readonly closeImpl; private readonly sessionStartedProperties; /** * Ingestion-side [image] limits owned by this harness's core; undefined for * daemon-client hosts, where the env var / built-in defaults apply. */ readonly imageLimits: ImageLimits | undefined; constructor(rpc: SDKRpcClientBase, options: KimiHarnessRuntimeOptions); get sessions(): ReadonlyMap; get interactiveAgentId(): string; withInteractiveAgent(agentId: string, fn: () => T): T; track(event: string, properties?: TelemetryProperties): void; setTelemetryContext(patch: TelemetryContextPatch): void; createSession(options: CreateSessionOptions): Promise; resumeSession(input: ResumeSessionInput): Promise; reloadSession(input: ReloadSessionInput): Promise; forkSession(input: ForkSessionInput): Promise; getSession(id: string): Session | undefined; closeSession(id: string): Promise; deleteSession(id: string): Promise; renameSession(input: RenameSessionInput): Promise; exportSession(input: ExportSessionInput): Promise; listSessions(options?: ListSessionsOptions): Promise; /** Skills visible to a new session in `workDir`, without creating that session. */ listWorkspaceSkills(workDir: string): Promise; getConfig(options?: GetConfigOptions): Promise; /** Warnings from the most recent config.toml load; empty when the config is fully valid. */ getConfigDiagnostics(): Promise; getExperimentalFeatures(): Promise; ensureConfigFile(): Promise; setConfig(patch: KimiConfigPatch): Promise; removeProvider(providerId: string): Promise; /** User-global MCP entries from `/mcp.json` only. */ listMcpServers(): Promise; addMcpServer(server: McpServerConfig): Promise; updateMcpServer(server: McpServerConfig): Promise; removeMcpServer(name: string): Promise; authenticateMcpServer(name: string, options: AuthenticateMcpServerOptions): Promise; resetMcpServerAuth(name: string): Promise; testMcpServer(name: string, options?: TestMcpServerOptions): Promise; close(): Promise; private trackSessionEvent; private trackSessionStarted; } export declare interface KimiHarnessOptions { readonly identity?: KimiHostIdentity | undefined; readonly homeDir?: string | undefined; readonly configPath?: string | undefined; readonly autoLoadConfig?: boolean | undefined; readonly uiMode?: string; readonly skillDirs?: readonly string[]; readonly telemetry?: TelemetryClient | undefined; readonly onOAuthRefresh?: ((outcome: OAuthRefreshOutcome) => void) | undefined; readonly sessionStartedProperties?: TelemetryProperties; } export declare interface KimiHarnessRuntimeOptions { readonly identity?: KimiHostIdentity; readonly uiMode?: string; readonly homeDir: string; readonly configPath: string; readonly auth: KimiAuthFacade; readonly telemetry: TelemetryClient; readonly ensureConfigFile: () => Promise; readonly onClose: () => void | Promise; readonly sessionStartedProperties?: TelemetryProperties; /** * Owner-scoped [image] limits for prompt-ingestion compression in the * client process (paste-time, ACP prompt conversion). In-process cores * (SDKRpcClient) hand over their core's instance; daemon-client hosts * leave it undefined and ingestion falls back to env/built-in defaults. */ readonly imageLimits?: ImageLimits | undefined; } export declare interface KimiHostIdentity { readonly userAgentProduct: string; readonly version: string; readonly userAgentSuffix?: string | undefined; } declare interface KimiOAuthLoginOptions extends LoginOptions { readonly provisionConfig?: boolean | undefined; readonly baseUrl?: string | undefined; readonly oauthRef?: KimiOAuthTokenRef | undefined; readonly oauthHost?: string | undefined; } declare interface KimiOAuthTokenRef { readonly key?: string | undefined; readonly oauthHost?: string | undefined; } declare interface KimiOptions { apiKey?: string | undefined; baseUrl?: string | undefined; model: string; stream?: boolean | undefined; defaultHeaders?: Record | undefined; generationKwargs?: GenerationKwargs | undefined; clientFactory?: (auth: ProviderRequestAuth) => OpenAI; } declare class KosongLLM implements LLM { readonly systemPrompt: string; readonly modelName: string; readonly capability?: ModelCapability | undefined; private readonly provider; private readonly generate; private readonly completionBudgetConfig; private readonly usedContextTokens; constructor(config: KosongLLMConfig); chat(params: LLMChatParams): Promise; isRetryableError(error: unknown): boolean; } declare interface KosongLLMConfig { readonly provider: ChatProvider; readonly systemPrompt: string; readonly capability?: ModelCapability | undefined; /** * Optional override for the kosong `generate()` entry point. Lets the * agent host (and its test harness) inject a scripted generator without * having to substitute the entire LLM implementation. */ readonly generate?: GenerateFn | undefined; /** * Completion budget config resolved from agent/provider settings. The * final cap is applied to each request. */ readonly completionBudgetConfig?: CompletionBudgetConfig | undefined; /** * Returns the number of context tokens already consumed by the latest * completed step (API-reported input + output). Used by chat-completions * providers to size the completion budget to the remaining context window. */ readonly usedContextTokens?: (() => number) | undefined; } export declare interface ListSessionsOptions { readonly workDir?: string; readonly sessionId?: string; } declare interface ListSessionsPayload { readonly workDir?: string; readonly sessionId?: string; readonly includeArchive?: boolean; } declare interface ListWorkspaceSkillsPayload { readonly workDir: string; } declare interface LLM { readonly systemPrompt: string; readonly modelName: string; readonly capability?: ModelCapability | undefined; isRetryableError?(error: unknown): boolean; chat(params: LLMChatParams): Promise; } declare interface LLMChatParams { messages: Message[]; tools: readonly Tool[]; signal: AbortSignal; requestLogFields?: LLMRequestLogFields; onTextDelta?: ((delta: string) => void) | undefined; onThinkDelta?: ((delta: string) => void) | undefined; onToolCallDelta?: ((delta: ToolCallDelta) => void) | undefined; /** * Fires once per completed text block. Additive relative to * `onTextDelta` — deltas still fire chunk-by-chunk for UI streaming. * Returned promises are awaited by the adapter to preserve transcript append * order. Durable transcript writes receive completed blocks only. */ onTextPart?: ((part: TextPart) => Promise | void) | undefined; /** * Fires once per completed thinking block. Additive relative to * `onThinkDelta` — deltas still fire chunk-by-chunk for UI streaming. * Returned promises are awaited by the adapter to preserve transcript append * order. Durable transcript writes receive completed blocks only. */ onThinkPart?: ((part: ThinkPart) => Promise | void) | undefined; trace?: LLMRequestTraceState; } declare interface LLMChatResponse { toolCalls: ToolCall[]; providerFinishReason?: FinishReason_2; rawFinishReason?: string; messageId?: string; usage: TokenUsage_3; streamTiming?: LLMStreamTiming; /** Provider trace identifier from the `x-trace-id` response header (Kimi/KFC only). */ traceId?: string; } /** * Request-scoped side channel from the host layers (loop, LLM adapter, * compaction) down to the `Agent.generate` choke point, consumed there by the * diagnostic logger and the wire-record request trace. */ declare interface LLMRequestLogFields { readonly turnStep?: string; readonly attempt?: string; /** Request purpose; absent means a regular loop step. */ readonly kind?: 'loop' | 'compaction'; /** Set when the messages are a fallback resend projection: the strict * wire-compliant rebuild, the media-degraded rebuild after a * request-too-large rejection, or the media-stripped rebuild after an * image-format rejection / a second request-too-large rejection. */ readonly projection?: 'strict' | 'media-degraded' | 'media-stripped'; /** Compaction only: messages dropped so far by overflow/empty shrinking. */ readonly droppedCount?: number; } declare class LlmRequestLogger { private readonly log; private lastConfigLogSignature; constructor(log: Logger); logRequest(input: { readonly provider: ChatProvider; readonly modelAlias?: string; readonly systemPrompt: string; readonly tools: readonly Tool[]; readonly messages: readonly Message[]; readonly fields: LLMRequestLogFields | undefined; }): void; } declare class LlmRequestRecorder { private readonly agent; /** Hashes of tool tables already durable in this wire log. */ private readonly seenToolsHashes; /** * Identity cache over the last wire tool table. Tool instances are treated * as immutable and are stable across steps (rebuilt only by * `initializeBuiltinTools` / MCP re-registration), so element-wise identity * implies content equality — the common per-step path costs no hashing. */ private lastWireTools; private lastToolsHash; private lastSystemPrompt; private lastSystemPromptHash; constructor(agent: Agent); /** Replay: a snapshot with this hash is already durable; never re-log it. */ restoreToolsSnapshot(hash: string): void; record(input: { readonly provider: ChatProvider; readonly systemPrompt: string; readonly tools: readonly Tool[]; readonly messages: readonly Message[]; readonly fields: LLMRequestLogFields | undefined; }): void; private toolsHashFor; private systemPromptHashFor; } /** One entry of a tools table as sent in a request's top-level `tools[]`. */ declare interface LlmRequestToolSchema { name: string; description: string; parameters: Record; } declare interface LLMRequestTrace { readonly traceId: string | undefined; } declare class LLMRequestTraceState implements LLMRequestTrace { traceId: string | undefined; reset(): void; capture(traceId: string | null | undefined): void; } declare interface LLMStreamTiming { readonly firstTokenLatencyMs: number; readonly streamDurationMs: number; /** * Portion of `firstTokenLatencyMs` spent in-process building the request * (message serialization, param assembly) before the provider dispatched the * network call. `undefined` when the provider does not report the * client/server boundary (no `onRequestSent`). */ readonly requestBuildMs?: number; /** * Portion of `firstTokenLatencyMs` spent waiting on the network + API server * from request dispatch to the first streamed token. `undefined` when the * provider does not report the client/server boundary. */ readonly serverFirstTokenMs?: number; /** * Split of `streamDurationMs` (the decode window): time spent awaiting parts * from the provider (`serverDecodeMs`, server + network) vs. time spent * processing parts in-process (`clientConsumeMs`, host callbacks / merge). * `undefined` when the provider stream did not report decode accounting. */ readonly serverDecodeMs?: number; readonly clientConsumeMs?: number; } /** * Parses an optional pruned models.dev catalog string — typically the * `__KIMI_CODE_BUILT_IN_CATALOG__` constant injected by tsdown at build * time. Returns `undefined` when the argument is missing or invalid. */ export declare function loadBuiltInCatalog(text?: string): Catalog | undefined; /** * Lenient variant of `loadRuntimeConfig` that never throws: schema errors * drop only the offending sections (whole entry for `providers`/`models`, * whole top-level section otherwise) and a bad KIMI_MODEL_* env overlay is * skipped, each reported as a warning. A file that cannot be used at all * additionally sets `fileError` so startup can fail fast while mid-run * reloads degrade. Runtime read paths use this; write paths must keep using * the strict readers so a broken file is never silently rewritten. */ export declare function loadRuntimeConfigSafe(filePath: string, env?: Readonly>): RuntimeConfigLoadResult; /** * Root logger. Import and use directly for events that don't belong to any * session (CLI startup, harness construction, etc.): * * import { log } from 'kimi-code-sdk'; * log.info('kimi-code starting', { version }); * * For events scoped to a session or agent, use the parent's `log` field: * * session.log.error('mcp initial load failed', error); * agent.log.error('turn failed', { turnId, error }); * * Late-binding: methods look up the current `RootLogger` on every call, so * importing `log` at module load (before `KimiHarness` configures the root) * is safe — calls during the pre-configure window are silent noops. */ export declare const log: Logger; export declare type LogContext = Record; export declare interface Logger { error(message: string, payload?: LogPayload): void; warn(message: string, payload?: LogPayload): void; info(message: string, payload?: LogPayload): void; debug(message: string, payload?: LogPayload): void; /** * Returns a new logger that adds `ctx` to every entry it emits. The bound * context wins over per-call payload context, so callers can't accidentally * overwrite ownership fields like `sessionId` / `agentId`: * * finalCtx = { ...payloadCtx, ...boundCtx } * * Children chain — `parent.createChild({a: 1}).createChild({b: 2})` binds * both. */ createChild(ctx: LogContext): Logger; } declare interface LoginOptions { readonly onDeviceCode?: ((auth: DeviceAuthorization) => Promise | void) | undefined; readonly signal?: AbortSignal | undefined; } export declare type LogLevel = 'off' | 'error' | 'warn' | 'info' | 'debug'; /** * Second argument to `log.error / warn / info / debug`. * * Three usage shapes, detected at runtime: * - `Error` → stack is extracted onto the entry * - `LogContext` (object) → merged into entry context; if it contains * `{ error: Error }`, that field is pulled out * and its stack extracted (bunyan-style) * - `unknown` → typically a `catch` binding; treated as an Error if * it's an Error instance, otherwise stringified into a * `reason` field */ export declare type LogPayload = unknown; declare interface LoopContentPartEvent { readonly type: 'content.part'; readonly uuid: string; readonly turnId: string; readonly step: number; readonly stepUuid: string; readonly part: TextPart | ThinkPart; } export declare type LoopControl = z.infer; declare const LoopControlSchema: z.ZodObject<{ maxStepsPerTurn: z.ZodOptional; maxRetriesPerStep: z.ZodOptional; maxRalphIterations: z.ZodOptional; reservedContextSize: z.ZodOptional; compactionTriggerRatio: z.ZodOptional; }, z.core.$strip>; declare type LoopRecordedEvent = LoopStepBeginEvent | LoopStepEndEvent | LoopContentPartEvent | LoopToolCallEvent | LoopToolResultEvent; declare interface LoopStepBeginEvent { readonly type: 'step.begin'; readonly uuid: string; readonly turnId: string; readonly step: number; } declare interface LoopStepEndEvent { readonly type: 'step.end'; readonly uuid: string; readonly turnId: string; readonly step: number; readonly usage?: TokenUsage_3 | undefined; readonly finishReason?: LoopStepStopReason | undefined; readonly llmFirstTokenLatencyMs?: number | undefined; readonly llmStreamDurationMs?: number | undefined; /** * Split of `llmFirstTokenLatencyMs`: in-process request-building time on the * client vs. network + API-server time to the first token. Both `undefined` * when the provider does not report the client/server boundary. */ readonly llmRequestBuildMs?: number | undefined; readonly llmServerFirstTokenMs?: number | undefined; /** * Split of `llmStreamDurationMs` (the decode window): time awaiting parts * from the provider vs. time processing parts in-process. Both `undefined` * when the provider stream did not report decode accounting. */ readonly llmServerDecodeMs?: number | undefined; readonly llmClientConsumeMs?: number | undefined; /** * Provider diagnostics are optional and must not drive loop control. * Use `finishReason` for normalized behavior. */ readonly providerFinishReason?: FinishReason_2 | undefined; readonly rawFinishReason?: string | undefined; readonly messageId?: string | undefined; /** * Provider trace identifier from the `x-trace-id` response header of this * step's final request attempt (Kimi/KFC only). Telemetry-only; must not * drive loop control. */ readonly traceId?: string; } /** * Step hooks are aligned to recorded phase boundaries: `beforeStep` runs before * `step.begin`, while `afterStep` runs after `step.end`. */ declare interface LoopStepHookContext { readonly turnId: string; readonly stepNumber: number; readonly signal: AbortSignal; readonly llm: LLM; } /** * Stop reason for one completed model step. * * `tool_use` is a loop-control signal: the loop executes the requested tools and * continues with another step. The other values are terminal for the current * turn unless a host hook explicitly asks the loop to continue. */ declare type LoopStepStopReason = 'end_turn' | 'max_tokens' | 'tool_use' | 'filtered' | 'paused' | 'unknown'; declare type LoopTerminalStepStopReason = Exclude; declare interface LoopToolCallEvent { readonly type: 'tool.call'; readonly uuid: string; readonly turnId: string; readonly step: number; readonly stepUuid: string; readonly toolCallId: string; readonly name: string; readonly args: unknown; readonly description?: string | undefined; readonly display?: ToolInputDisplay | undefined; readonly extras?: Record | undefined; readonly traceId?: string; } declare interface LoopToolResultEvent { readonly type: 'tool.result'; readonly parentUuid: string; readonly toolCallId: string; readonly result: ExecutableToolResult; readonly traceId?: string; } /** * Stop reasons that can be returned in a normal `TurnResult`. * * `tool_use` is intentionally absent because it cannot be the final result of a * completed turn. Errors and max-step exhaustion are represented by thrown * errors, not by this union. Compaction is a host-level retry concern rather * than a stop reason. */ declare type LoopTurnStopReason = LoopTerminalStepStopReason | 'aborted'; /** * Built-in longest-edge ceiling (px). Larger images are scaled down to fit. * This is the default only: the effective ceiling is resolved per call by * {@link resolveMaxImageEdgePx} (explicit option > env > config > this). */ export declare const MAX_IMAGE_EDGE_PX = 2000; /** * Optional context passed to {@link ChatProvider.withMaxCompletionTokens} so a * provider can tighten the caller-supplied cap to its own transport * constraints. */ declare interface MaxCompletionTokensOptions { /** * Tokens already consumed by the current context (API-reported input + * output of the latest completed step). Chat-completions providers use it * to size the cap to the remaining context window. */ readonly usedContextTokens?: number; /** Model context-window size in tokens (`max_context_size`). */ readonly maxContextTokens?: number; } export declare type MaybePromise = T | Promise; export declare const MCP_OAUTH_AUTHORIZATION_URL_TOOL_UPDATE = "mcp.oauth.authorization_url"; /** * Minimal MCP client interface consumed by {@link McpConnectionManager} and * {@link ToolManager}. * * This is a transport-agnostic seam: implementations can wrap * `@modelcontextprotocol/sdk`, a bespoke stdio client, an HTTP SSE client, * or a mock for testing. Keeping the surface small lets tests inject fakes * without pulling in the full SDK type graph. */ declare interface MCPClient { /** List the tools advertised by the MCP server. */ listTools(): Promise; /** * Invoke a tool by name with the given JSON arguments. * * `signal`, when provided, is forwarded to the underlying transport so an * abort from the loop (e.g. user cancellation) propagates all the way to * the server instead of leaving the request running in the background. */ callTool(name: string, args: Record, signal?: AbortSignal): Promise; } /** * Owns the lifecycle of every configured MCP server for a Session. * * Servers are connected in parallel; per-server failures are isolated so a * crashed or misconfigured entry never blocks Session startup. State * transitions are surfaced through {@link onStatusChange} so callers (the * Session) can react — registering tools onto the main agent, emitting * wire events, or updating the TUI. */ declare class McpConnectionManager { private readonly options; private readonly entries; private readonly listeners; private initialLoad; private initialLoadAttemptId; private initialLoadStartedAt; private initialLoadFinishedAt; /** * OAuth orchestrator injected at construction time. Consumed by the * {@link ToolManager} `needs-auth` branch to build the synthetic * `authenticate` tool. */ readonly oauthService: McpOAuthService | undefined; private readonly log; constructor(options?: McpConnectionManagerOptions); /** * Returns the URL of a remote MCP server by name, or `undefined` for * unknown / non-remote / disabled entries. Used by the synthetic auth tool * to drive OAuth discovery against the right base URL. */ getRemoteServerUrl(name: string): string | undefined; /** * @deprecated Use {@link getRemoteServerUrl}. Kept for in-repo callers that * were written before legacy SSE support shared the same OAuth path. */ getHttpServerUrl(name: string): string | undefined; onStatusChange(listener: McpStatusListener): () => void; list(): readonly McpServerEntry[]; get(name: string): McpServerEntry | undefined; /** * Returns the MCP client, the discovered tools, and the allow-list of tool * names for a given connected server, or `undefined` if the server is not * currently connected. The allow-list combines the server's `enabledTools` * and `disabledTools` filters; callers should only register names in the * set. */ resolved(name: string): { client: MCPClient; tools: readonly Tool[]; rawTools: readonly MCPToolDefinition[]; enabledNames: ReadonlySet; } | undefined; connectAll(configs: Record): Promise; connect(name: string, config: McpServerConfig_2): Promise; remove(name: string): Promise; waitForInitialLoad(signal?: AbortSignal): Promise; initialLoadDurationMs(): number; private connectAllNow; reconnect(name: string): Promise; shutdown(): Promise; private connectOne; private watchForUnexpectedClose; private beginConnectAttempt; private createClient; private resolveOAuthProvider; private shouldMarkNeedsAuth; private connectAndDiscoverTools; private closeClient; private closeRuntimeClient; private isCurrent; private emit; } declare interface McpConnectionManagerOptions { readonly envLookup?: (name: string) => string | undefined; readonly stdioCwd?: string; /** * Optional OAuth orchestrator. When provided, remote servers without a * static bearer token participate in the OAuth-via-synthetic-tool flow: * - If `oauthService.hasTokens(name, url)` is true, the provider is * attached to the transport so the SDK can refresh tokens on 401. * - Connection failures that look like 401 / `UnauthorizedError` flip * the entry into `needs-auth` instead of `failed`; `/mcp-config` * drives the browser flow through the synthetic auth tool. */ readonly oauthService?: McpOAuthService; /** * Parent logger. Defaults to the global `log`; Session passes its own * `session.log` so MCP events land in the session log too. */ readonly log?: Logger; } /** * A content block as returned by an MCP tool call (`tools/call`). * * This is a structural subset of the MCP protocol `ContentBlock` union, * covering the shapes that {@link convertMCPContentBlock} knows how to convert * into kosong `ContentPart`s. Additional fields are ignored. */ declare interface MCPContentBlock { type: string; text?: string; data?: string; mimeType?: string; uri?: string; resource?: MCPEmbeddedResourceContents; [key: string]: unknown; } /** * MCP protocol types and the minimal client contract `ToolManager` consumes. * * Lives in its own file (rather than `toolset.ts`) because the agent-side * tool-runtime layer is `ExecutableTool`, not the legacy `Toolset` interface. * What remains here is the wire-level surface: tool definitions returned by * `tools/list`, the `tools/call` result shape, and the small interface that * lets tests inject a fake transport without pulling in the MCP SDK type graph. */ /** * Inline resource contents nested under an EmbeddedResource block. * Exactly one of `text` or `blob` is populated, per the MCP schema's * `TextResourceContents | BlobResourceContents` union. */ declare interface MCPEmbeddedResourceContents { uri: string; mimeType?: string; text?: string; blob?: string; [key: string]: unknown; } export declare interface McpOAuthAuthorizationUrlUpdateData { readonly serverName: string; readonly authorizationUrl: string; } declare class McpOAuthClientProvider implements OAuthClientProvider { readonly storeKey: string; readonly serverUrl: string; private readonly store; private readonly clientLabel; private _redirectUrl; private _codeVerifier; private _state; private _lastAuthorizationUrl; constructor(options: McpOAuthProviderOptions); setRedirectUrl(url: URL): void; /** URL captured from the most recent `redirectToAuthorization` call. */ takeAuthorizationUrl(): URL | undefined; /** OAuth `state` value generated for the most recent flow, for callback verification. */ expectedState(): string | undefined; resetFlow(): void; get redirectUrl(): string | URL; get clientMetadata(): OAuthClientMetadata; state(): string; clientInformation(): OAuthClientInformationMixed | undefined; saveClientInformation(info: OAuthClientInformationMixed): void; tokens(): OAuthTokens | undefined; saveTokens(tokens: OAuthTokens): void; redirectToAuthorization(url: URL): void; saveCodeVerifier(codeVerifier: string): void; codeVerifier(): string; saveDiscoveryState(state: OAuthDiscoveryState): void; discoveryState(): OAuthDiscoveryState | undefined; invalidateCredentials(scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery'): void; private effectiveRedirectUri; } declare interface McpOAuthProviderOptions { /** Friendly name of the MCP server; used in DCR `client_name`. */ readonly serverName: string; /** Canonical resource identity used to isolate credentials for this server entry. */ readonly serverUrl: string | URL; /** JSON store used for persistence. Tests inject an in-memory dir. */ readonly store: JsonFileStore; /** Identifier embedded in DCR `client_name` ("kimi-code (server)"). */ readonly clientLabel?: string; } declare class McpOAuthService { private readonly store; private readonly clientLabel; private readonly providers; constructor(options?: McpOAuthServiceOptions); /** Returns the cached provider for `serverName` + `serverUrl`, constructing it on first use. */ getProvider(serverName: string, serverUrl: string | URL): McpOAuthClientProvider; /** True once the provider has persisted tokens for this server/resource identity. */ hasTokens(serverName: string, serverUrl: string | URL): boolean; /** * Drive the SDK `auth()` orchestrator far enough to surface an * authorization URL. The caller is responsible for displaying the URL * (typically via the synthetic authenticate tool) and then awaiting * `complete()` to finish the code exchange. */ beginAuthorization(serverName: string, serverUrl: string | URL, options?: BeginAuthorizationOptions): Promise; /** * Clear stored credentials for a server. Use `'all'` after the user * explicitly signs out; use `'tokens'` to force a re-auth while keeping * the registered DCR client. */ invalidate(serverName: string, serverUrl: string | URL, scope?: 'all' | 'client' | 'tokens' | 'discovery'): void; } declare interface McpOAuthServiceOptions { /** Storage backend; overrides `kimiHomeDir` when supplied. */ readonly store?: JsonFileStore; /** Resolved Kimi home; credentials default to `/credentials/mcp/`. */ readonly kimiHomeDir?: string; /** Override for the label embedded in DCR `client_name`. */ readonly clientLabel?: string; } export declare type McpServerConfig = McpServerConfig_2 & { readonly name: string; }; declare type McpServerConfig_2 = z.infer; declare const McpServerConfigSchema: z.ZodPipe, z.ZodDiscriminatedUnion<[z.ZodObject<{ enabled: z.ZodOptional; startupTimeoutMs: z.ZodOptional; toolTimeoutMs: z.ZodOptional; enabledTools: z.ZodOptional>; disabledTools: z.ZodOptional>; transport: z.ZodLiteral<"stdio">; command: z.ZodString; args: z.ZodOptional>; env: z.ZodOptional>; cwd: z.ZodOptional; executor: z.ZodOptional>; }, z.core.$strip>, z.ZodObject<{ enabled: z.ZodOptional; startupTimeoutMs: z.ZodOptional; toolTimeoutMs: z.ZodOptional; enabledTools: z.ZodOptional>; disabledTools: z.ZodOptional>; transport: z.ZodLiteral<"http">; url: z.ZodString; headers: z.ZodOptional>; auth: z.ZodOptional>; bearerTokenEnvVar: z.ZodOptional; }, z.core.$strip>, z.ZodObject<{ enabled: z.ZodOptional; startupTimeoutMs: z.ZodOptional; toolTimeoutMs: z.ZodOptional; enabledTools: z.ZodOptional>; disabledTools: z.ZodOptional>; transport: z.ZodLiteral<"sse">; url: z.ZodString; headers: z.ZodOptional>; auth: z.ZodOptional>; bearerTokenEnvVar: z.ZodOptional; }, z.core.$strip>], "transport">>; declare interface McpServerEntry { readonly name: string; readonly transport: McpServerConfig_2['transport']; readonly status: McpServerStatus; readonly toolCount: number; readonly error?: string; } export declare interface McpServerInfo { readonly name: string; readonly transport: 'stdio' | 'http' | 'sse'; readonly status: 'pending' | 'connected' | 'failed' | 'disabled' | 'needs-auth'; readonly toolCount: number; readonly error?: string; } declare interface McpServerRegistrationResult { readonly registered: readonly string[]; readonly collisions: readonly McpToolCollision[]; } declare type McpServerStatus = 'pending' | 'connected' | 'failed' | 'disabled' | 'needs-auth'; export declare interface McpServerStatusEvent { readonly type: 'mcp.server.status'; readonly server: McpServerStatusPayload; } export declare interface McpServerStatusPayload { readonly name: string; readonly transport: 'stdio' | 'http' | 'sse'; readonly status: 'pending' | 'connected' | 'failed' | 'disabled' | 'needs-auth'; readonly toolCount: number; readonly error?: string; } export declare interface McpStartupMetrics { readonly durationMs: number; } declare type McpStatusListener = (entry: McpServerEntry) => void; export declare interface McpTestResult { readonly success: boolean; readonly output: string; } declare interface McpToolCollision { readonly qualified: string; readonly toolName: string; readonly collidesWith: { readonly kind: 'same_server'; readonly toolName: string; } | { readonly kind: 'other_server'; readonly serverName: string; }; } /** * An MCP tool definition as returned by an MCP server's `tools/list` method. */ declare interface MCPToolDefinition { name: string; description: string; inputSchema: unknown; } declare interface McpToolEntry { readonly tool: ExecutableTool; readonly serverName: string; } /** * Result of a single MCP tool invocation. * * Matches the shape returned by the MCP protocol's `tools/call` method. */ declare interface MCPToolResult { content: MCPContentBlock[]; isError: boolean; } /** * A single message in a conversation. * * Messages carry a {@link role} (system, user, assistant, or tool), an array * of {@link ContentPart} content blocks, and optional {@link ToolCall} entries. * Tool result messages set {@link toolCallId} to correlate with the originating * call. */ declare interface Message { /** The role of the message sender. */ readonly role: Role; /** Optional display name for the sender (used by some providers). */ readonly name?: string; /** Ordered content parts (text, images, thinking, etc.). */ readonly content: ContentPart[]; /** Tool calls requested by the assistant in this message. */ readonly toolCalls: ToolCall[]; /** For `tool` role messages, the ID of the tool call this result answers. */ readonly toolCallId?: string; /** When `true`, indicates the message was not fully received (e.g. stream interrupted). */ readonly partial?: boolean; /** * Full tool definitions carried by this message. Meaningful only on * `role: 'system'` messages: it is the append-only primitive for loading a * tool mid-conversation without touching the request's top-level `tools[]` * (which must stay byte-stable to preserve the provider's prompt cache). * Providers that support message-level tool declarations (Kimi * `messages[].tools`) serialize it; callers must not send such a message to * a provider without that capability. */ readonly tools?: readonly Tool[] | undefined; } declare type MessageContent = z.infer; declare const messageContentSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ type: z.ZodLiteral<"text">; text: z.ZodString; }, z.core.$strip>, z.ZodObject<{ type: z.ZodLiteral<"tool_use">; tool_call_id: z.ZodString; tool_name: z.ZodString; input: z.ZodUnknown; }, z.core.$strip>, z.ZodObject<{ type: z.ZodLiteral<"tool_result">; tool_call_id: z.ZodString; output: z.ZodUnknown; is_error: z.ZodOptional; }, z.core.$strip>, z.ZodObject<{ type: z.ZodLiteral<"image">; source: z.ZodDiscriminatedUnion<[z.ZodObject<{ kind: z.ZodLiteral<"url">; url: z.ZodString; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"base64">; media_type: z.ZodString; data: z.ZodString; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"file">; file_id: z.ZodString; }, z.core.$strip>], "kind">; }, z.core.$strip>, z.ZodObject<{ type: z.ZodLiteral<"video">; source: z.ZodDiscriminatedUnion<[z.ZodObject<{ kind: z.ZodLiteral<"url">; url: z.ZodString; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"base64">; media_type: z.ZodString; data: z.ZodString; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"file">; file_id: z.ZodString; }, z.core.$strip>], "kind">; }, z.core.$strip>, z.ZodObject<{ type: z.ZodLiteral<"file">; file_id: z.ZodString; name: z.ZodString; media_type: z.ZodString; size: z.ZodNumber; }, z.core.$strip>, z.ZodObject<{ type: z.ZodLiteral<"thinking">; thinking: z.ZodString; signature: z.ZodOptional; }, z.core.$strip>], "type">; declare class MicroCompaction { readonly agent: Agent; private cutoff; readonly config: MicroCompactionConfig; constructor(agent: Agent, config?: Partial); reset(maxCutoff?: number): void; apply(cutoff: number): void; detect(): void; compact(messages: readonly ContextMessage[]): readonly ContextMessage[]; private measureEffect; } declare interface MicroCompactionConfig { keepRecentMessages: number; minContentTokens: number; cacheMissedThresholdMs: number; truncatedMarker: string; minContextUsageRatio: number; } export declare type ModelAlias = z.infer; declare const ModelAliasSchema: z.ZodObject<{ provider: z.ZodString; model: z.ZodString; maxContextSize: z.ZodNumber; maxOutputSize: z.ZodOptional; capabilities: z.ZodOptional>; displayName: z.ZodOptional; reasoningKey: z.ZodOptional; protocol: z.ZodOptional>; adaptiveThinking: z.ZodOptional; supportEfforts: z.ZodOptional>; defaultEffort: z.ZodOptional; betaApi: z.ZodOptional; overrides: z.ZodOptional>>; maxContextSize: z.ZodOptional; maxOutputSize: z.ZodOptional>; displayName: z.ZodOptional>; reasoningKey: z.ZodOptional>; adaptiveThinking: z.ZodOptional>; supportEfforts: z.ZodOptional>>; defaultEffort: z.ZodOptional>; }, z.core.$strip>>; }, z.core.$strip>; /** * Declared capabilities for a specific model. * * `getModelCapability(wire, model)` returns one of these so callers can gate * requests against modalities the model does not accept without dispatching * the request and watching it fail upstream. * * `max_context_tokens: 0` means "unknown"; callers that do not gate on * context length can ignore the field. */ declare interface ModelCapability { readonly image_in: boolean; readonly video_in: boolean; readonly audio_in: boolean; readonly thinking: boolean; readonly tool_use: boolean; readonly max_context_tokens: number; /** * Model accepts message-level tool declarations (`messages[].tools`) — the * "dynamically loaded tools" wire feature that clients can drive with * progressive tool disclosure. Absent means unsupported: only models * explicitly catalogued or declared with this capability may ever receive a * message carrying `tools`. */ readonly dynamically_loaded_tools?: boolean; } /** * Pushed when the daemon refreshes provider model metadata (manual or * scheduled) and the effective catalog changed. Carries the per-provider * diff so clients can both refresh their model/provider caches and surface a * summary ("3 models added") without re-diffing the whole config. */ declare interface ModelCatalogChangedEvent { readonly type: 'event.model_catalog.changed'; readonly changed: readonly ProviderRefreshChange[]; readonly unchanged: readonly string[]; readonly failed: readonly ProviderRefreshFailure[]; } declare interface ModelProvider { readonly defaultModel?: string; resolveProviderConfig(model: string): ResolvedRuntimeProvider; resolveAuth?(model: string, options?: { readonly log?: Logger; }): AuthorizedRequest | undefined; } export declare type MoonshotServiceConfig = z.infer; declare const MoonshotServiceConfigSchema: z.ZodObject<{ baseUrl: z.ZodOptional; apiKey: z.ZodOptional; oauth: z.ZodOptional; key: z.ZodString; oauthHost: z.ZodOptional; }, z.core.$strip>>; customHeaders: z.ZodOptional>; }, z.core.$strip>; /** * Lowercase, drop MIME parameters, and apply the `image/jpg` alias. Parameter * stripping keeps a declared media type like `image/jpeg; charset=utf-8` * consistent with a data-URL MIME token (which the parser already clips at * the first `;`), so an accepted image with parameters is treated exactly * like the bare form instead of being misread as unsupported. */ export declare function normalizeImageMime(mimeType: string): string; export declare type OAuthRef = z.infer; export declare type OAuthRefreshOutcome = { readonly success: true; } | { readonly success: false; readonly reason: 'unauthorized' | 'network_or_other'; }; declare const OAuthRefSchema: z.ZodObject<{ storage: z.ZodEnum<{ file: "file"; keyring: "keyring"; }>; key: z.ZodString; oauthHost: z.ZodOptional; }, z.core.$strip>; declare type OAuthTokenProviderResolver = (providerName: string, oauthRef?: OAuthRef) => BearerTokenProvider_2 | undefined; declare interface OpenAI {} declare namespace OpenAI { namespace Chat { type ChatCompletion = unknown; type ChatCompletionChunk = unknown; type ChatCompletionCreateParamsNonStreaming = unknown; } } declare interface OpenAILegacyOptions { apiKey?: string | undefined; baseUrl?: string | undefined; model: string; stream?: boolean | undefined; maxTokens?: number | undefined; reasoningKey?: string | undefined; httpClient?: unknown; defaultHeaders?: Record; toolMessageConversion?: ToolMessageConversion | undefined; clientFactory?: (auth: ProviderRequestAuth) => OpenAI; } declare interface OpenAIResponsesOptions { apiKey?: string | undefined; baseUrl?: string | undefined; model: string; maxOutputTokens?: number | undefined; httpClient?: unknown; defaultHeaders?: Record; toolMessageConversion?: ToolMessageConversion | undefined; clientFactory?: (auth: ProviderRequestAuth) => OpenAI; } /** * Environment — cross-platform probe of OS / shell. * * Detection is a pure function of injected probes (`platform` / `arch` / * `release` / `env` / `isFile` / `execFileText`) so the same suite runs * identically on any host OS. `detectEnvironmentFromNode()` bundles the Node * defaults for production callers. * * On Windows the probe expects bash from Git for Windows or MSYS2. If it * cannot be located the function throws `KaosShellNotFoundError`; the SDK * layer can wrap that into a user-facing install hint. Set * `KIMI_SHELL_PATH` to override. */ declare type OsKind = string; declare interface ParsedManagedUsage { readonly summary: UsageRow | null; readonly limits: UsageRow[]; readonly extraUsage: BoosterWalletInfo | null; } /** * Parse an image `data:` URL into its MIME and base64 payload. The MIME is * returned raw — callers decide via {@link isModelAcceptedImageMime} and * forward {@link normalizeImageMime}. MIME parameters are tolerated and * ignored (`data:image/avif;charset=utf-8;base64,…`), so a parameter-bearing * URL cannot slip past the format gate. The scheme and `base64` marker are * matched case-insensitively (RFC 2045 encoding names are case-insensitive), * so an uppercase `;BASE64,` cannot slip past either — and since callers * rebuild to the canonical URL, the marker comes back out lowercase. * Returns null for non-data URLs (e.g. a remote http(s) image — see the * scope note in the module header). */ export declare function parseImageDataUrl(url: string): { mimeType: string; base64: string; } | null; declare interface PermissionApprovalResultRecord { readonly turnId: number; readonly toolCallId: string; readonly toolName: string; readonly action: string; readonly sessionApprovalRule?: string; readonly result: ApprovalResponse_2; } declare interface PermissionData { mode: PermissionMode_2; rules: PermissionRule[]; } declare type PermissionDecisionReason = Readonly>; declare class PermissionManager { protected readonly agent: Agent; readonly policies: PermissionPolicy[]; readonly rules: PermissionRule[]; private modeOverride; private readonly parent; private readonly localSessionApprovalRulePatterns; constructor(agent: Agent, options?: PermissionManagerOptions); get mode(): PermissionMode_2; set mode(mode: PermissionMode_2); data(): PermissionData; setMode(mode: PermissionMode_2): void; recordApprovalResult(record: PermissionApprovalResultRecord): void; get sessionApprovalRulePatterns(): readonly string[]; beforeToolCall(context: PermissionPolicyContext): Promise; private requestToolApproval; private evaluatePolicies; private get effectiveRules(); private permissionPolicyResolutionToPrepare; protected formatApprovalRejectionMessage(toolName: string, result: { decision: 'approved' | 'rejected' | 'cancelled'; feedback?: string; }): string; private formatPolicyDenyMessage; } declare interface PermissionManagerOptions { readonly initialRules?: readonly PermissionRule[]; readonly parent?: PermissionManager; } export declare type PermissionMode = 'yolo' | 'manual' | 'auto'; /** * Top-level user-facing permission posture. Controls how non-deny rules * are treated when the closure is constructed. Independent of rule * merging: deny rules always fire regardless of mode. * * - `manual` — rule set drives decision; unmatched tool calls ask * - `yolo` — only deny rules can block; everything else allows * - `auto` — caller may bypass rule checks entirely */ declare type PermissionMode_2 = 'manual' | 'yolo' | 'auto'; declare type PermissionMode_3 = 'manual' | 'yolo' | 'auto'; declare interface PermissionPolicy { readonly name: string; evaluate(context: PermissionPolicyContext): PermissionPolicyResult | undefined | Promise; } declare interface PermissionPolicyContext extends ResolvedToolExecutionHookContext { } declare type PermissionPolicyResolution = PermissionPolicyResult | ({ readonly kind: 'result'; } & PrepareToolExecutionResult); declare type PermissionPolicyResult = { readonly kind: 'approve'; readonly reason?: PermissionDecisionReason; readonly executionMetadata?: unknown; } | { readonly kind: 'deny'; readonly reason?: PermissionDecisionReason; readonly message?: string; } | { readonly kind: 'ask'; readonly reason?: PermissionDecisionReason; readonly resolveApproval?: (result: ApprovalResponse_2) => PermissionPolicyResolution | undefined; readonly resolveError?: (error: unknown) => PermissionPolicyResolution | undefined; }; declare type PermissionReasonValue = string | number | boolean | null; /** * A single permission rule. `pattern` is the DSL form (`Read(/etc/**)`, * `Bash(rm *)`, or bare `Write`). Rule arguments are interpreted only by * tools that provide a matcher; other tools match by name only. */ declare interface PermissionRule { readonly decision: PermissionRuleDecision; readonly scope: PermissionRuleScope; readonly pattern: string; readonly reason?: string; } declare type PermissionRuleDecision = 'allow' | 'deny' | 'ask'; /** * Rule provenance. `session-runtime` stores rules produced by * "approve for session"; `turn-override`, `project`, and `user` are * reserved for static-loaded rules surfaced by external callers. */ declare type PermissionRuleScope = 'turn-override' | 'session-runtime' | 'project' | 'user'; declare type PersistedTask = BackgroundTaskInfo; /** * Persist `bytes` into the originals store and return the absolute file * path, or null on any failure. Idempotent for identical bytes. */ export declare function persistOriginalImage(bytes: Uint8Array, mimeType: string, options?: PersistOriginalImageOptions): Promise; /** * Content-addressed store for pre-compression image originals. * * When an ingestion point (MCP tool result, pasted image, inline base64 * upload) compresses an image that exists only in memory, the original bytes * would be gone for good — the model could never zoom into a detail the * downsampled copy lost. This module persists those originals so the * compression caption can point at a real path the model can read back with * `ReadMediaFile` (typically with `region`). * * Placement: callers that know their session pass * `{ dir: sessionMediaOriginalsDir(sessionDir) }` so originals live at * `/media-originals/` — owned by the session, cleaned up with it, * and immune to OS temp reaping. The shared temp-dir cache * ({@link originalImageCacheDir}) is only the fallback for call sites with no * session context. * * Design notes: * - Content-addressed (sha256): duplicate pastes/results reuse one file and * repeated writes are idempotent. * - Best effort: any filesystem failure returns null; callers then emit a * caption without a readback path. Persistence must never block a prompt. * - Size-capped: after each write the store is swept oldest-first (mtime) * until it fits {@link DEFAULT_MAX_TOTAL_BYTES}, so long sessions cannot * fill the disk. */ declare interface PersistOriginalImageOptions { /** * Target directory — pass `sessionMediaOriginalsDir(sessionDir)` when the * session is known. Defaults to the shared temp-dir fallback. */ readonly dir?: string; /** Override the store size cap in bytes (tests). */ readonly maxTotalBytes?: number; } declare type PlanData = null | { id: string; content: string; path: string; }; declare type PlanFilePath = string | null; export declare interface PlanInfo { readonly id: string; readonly content: string; readonly path: string; } declare class PlanMode { protected readonly agent: Agent; protected _isActive: boolean; protected _planId: null | string; protected _planFilePath: PlanFilePath; constructor(agent: Agent); createPlanId(): string; enter(id?: string, createFile?: boolean, emitStatus?: boolean): Promise; restoreEnter({ id }: { readonly id: string; }): void; cancel(id?: string): void; clear(): Promise; exit(id?: string): void; get isActive(): boolean; get planFilePath(): PlanFilePath; data(): Promise; private writeEmptyPlanFile; private ensurePlanDirectory; private planFilePathFor; } declare interface PluginAuthor { readonly name?: string; readonly email?: string; } declare interface PluginCapabilityState { readonly mcpServers?: Readonly>; } export declare interface PluginCommandActivatedEvent { readonly type: 'plugin_command.activated'; readonly activationId: string; readonly pluginId: string; readonly commandName: string; readonly commandArgs?: string; readonly trigger: 'user-slash'; } export declare interface PluginCommandDef { readonly pluginId: string; readonly name: string; readonly description: string; readonly body: string; readonly path: string; } /** * A resolved command file plus its namespace-preserving name. * * `name` is the path of the file relative to the declared `commands` entry * (without the `.md` extension, using `/` separators), so a file at * `commands/frontend/component.md` yields the name `frontend/component`. * Frontmatter `name` in the file itself takes precedence over this at load time. */ declare interface PluginCommandEntry { readonly path: string; readonly name: string; } declare interface PluginCommandOrigin { readonly kind: 'plugin_command'; readonly activationId: string; readonly pluginId: string; readonly commandName: string; readonly commandArgs?: string | undefined; readonly trigger: 'user-slash'; } declare interface PluginCommandOrigin_2 { readonly kind: 'plugin_command'; readonly activationId: string; readonly pluginId: string; readonly commandName: string; readonly commandArgs?: string; readonly trigger: 'user-slash'; } declare interface PluginDiagnostic { readonly severity: PluginDiagnosticSeverity; readonly message: string; } declare type PluginDiagnosticSeverity = 'error' | 'warn' | 'info'; export declare interface PluginGithubMetadata { readonly owner: string; readonly repo: string; readonly ref: PluginGithubRef; readonly installedSha?: string; } export declare interface PluginGithubRef { readonly kind: 'branch' | 'tag' | 'sha'; readonly value: string; } export declare interface PluginInfo extends PluginSummary { readonly root: string; readonly installedAt: string; readonly updatedAt?: string; readonly manifestKind?: PluginManifestKind; readonly manifestPath?: string; readonly manifest?: PluginManifest; readonly mcpServers: readonly PluginMcpServerInfo[]; readonly shadowedManifestPath?: string; readonly diagnostics: readonly PluginDiagnostic[]; } declare interface PluginInterface { readonly displayName?: string; readonly shortDescription?: string; readonly longDescription?: string; readonly developerName?: string; readonly websiteURL?: string; } declare class PluginManager { private readonly kimiHomeDir; private records; constructor(options: PluginManagerOptions); load(): Promise; list(): readonly PluginRecord[]; get(id: string): PluginRecord | undefined; install(source: string): Promise; setEnabled(id: string, enabled: boolean): Promise; setMcpServerEnabled(id: string, server: string, enabled: boolean): Promise; remove(id: string): Promise; reload(): Promise; pluginSkillRoots(): readonly SkillRoot[]; enabledSessionStarts(): readonly EnabledPluginSessionStart[]; enabledMcpServers(): Record; enabledHooks(): readonly HookDef[]; enabledCommands(): Promise; summaries(): readonly PluginSummary[]; info(id: string): PluginInfo | undefined; private persist; private materialize; } declare interface PluginManagerOptions { readonly kimiHomeDir: string; } declare interface PluginManifest { readonly name: string; readonly version?: string; readonly description?: string; readonly keywords?: readonly string[]; readonly author?: PluginAuthor; readonly homepage?: string; readonly license?: string; readonly skills?: readonly string[]; readonly sessionStart?: PluginSessionStart; readonly mcpServers?: Readonly>; readonly hooks?: readonly HookDefConfig[]; readonly commands?: readonly PluginCommandEntry[]; readonly interface?: PluginInterface; readonly skillInstructions?: string; } declare type PluginManifestKind = 'kimi-plugin-root' | 'kimi-plugin-dir'; export declare interface PluginMcpServerInfo { readonly name: string; readonly runtimeName: string; readonly enabled: boolean; readonly transport: 'stdio' | 'http' | 'sse'; readonly command?: string; readonly args?: readonly string[]; readonly cwd?: string; readonly url?: string; readonly envKeys?: readonly string[]; readonly headerKeys?: readonly string[]; } declare interface PluginMcpServerState { readonly enabled: boolean; } declare interface PluginRecord { readonly id: string; readonly root: string; readonly source: PluginSource; readonly enabled: boolean; readonly state: PluginState; readonly installedAt: string; readonly updatedAt?: string; readonly originalSource?: string; readonly capabilities?: PluginCapabilityState; readonly github?: PluginGithubMetadata; readonly skillInstructions?: string; readonly skillCount: number; readonly manifest?: PluginManifest; readonly manifestKind?: PluginManifestKind; readonly manifestPath?: string; readonly shadowedManifestPath?: string; readonly diagnostics: readonly PluginDiagnostic[]; } declare interface PluginSessionStart { readonly skill: string; } export declare type PluginSource = 'local-path' | 'zip-url' | 'github'; declare type PluginState = 'ok' | 'error'; export declare interface PluginSummary { readonly id: string; readonly displayName: string; readonly version?: string; readonly enabled: boolean; readonly state: PluginState; readonly skillCount: number; readonly mcpServerCount: number; readonly enabledMcpServerCount: number; readonly hookCount: number; readonly commandCount: number; readonly hasErrors: boolean; readonly source: PluginSource; readonly originalSource?: string; readonly github?: PluginGithubMetadata; } declare interface PreparedSystemPromptContext extends Pick { /** Present when the combined AGENTS.md content exceeds the recommended size. */ readonly agentsMdWarning?: string; } declare interface PrepareToolExecutionResult extends AuthorizeToolExecutionResult { readonly updatedArgs?: unknown; } declare type Prettify = { [K in keyof T]: T[K]; } & {}; export declare interface ProcessBackgroundTaskInfo extends BackgroundTaskInfoBase { readonly kind: 'process'; readonly command: string; readonly pid: number; readonly exitCode: number | null; } declare interface ProcessTaskInfo extends TaskInfoBase { readonly kind: 'process'; readonly command: string; readonly pid: number; readonly exitCode: number | null; } /** * A repair the projector applied to make the history wire-valid. Each one means * the stored history was not directly sendable to a strict provider. */ declare type ProjectionAnomaly = /** A recorded result was not adjacent to its call and had to be moved up. */ { readonly kind: 'tool_result_reordered'; readonly toolCallId: string; } /** * No result existed for a call, so a placeholder was synthesized. `trailing` * is true when it closed a still-open tail call (expected under * `synthesizeMissing`), false when it closed a mid-history orphan whose result * was lost (a genuine defect worth investigating). */ | { readonly kind: 'tool_result_synthesized'; readonly toolCallId: string; readonly trailing: boolean; } /** A result with no matching call anywhere was dropped (wire exits only). */ | { readonly kind: 'orphan_tool_result_dropped'; readonly toolCallId: string; } /** A tool call whose id already appeared earlier was dropped (strict-resend only). */ | { readonly kind: 'duplicate_tool_call_dropped'; readonly toolCallId: string; } /** A second result for an already-answered id was dropped (strict-resend only). */ | { readonly kind: 'duplicate_tool_result_dropped'; readonly toolCallId: string; } /** A leading non-user message was dropped so the first turn is user (strict). */ | { readonly kind: 'leading_non_user_dropped'; readonly role: string; } /** Two adjacent assistant turns were merged into one (strict). */ | { readonly kind: 'consecutive_assistants_merged'; } /** A non-empty but all-whitespace text block was dropped (always). */ | { readonly kind: 'whitespace_text_dropped'; readonly role: string; }; declare interface ProjectOptions { /** * When `true`, emit a synthetic `tool_result` for *every* assistant `tool_use` * whose result is not present in the provided messages — including a trailing, * still-in-flight call. Used by full compaction, where the compacted prefix is * a slice that may exclude a delayed result preserved in the retained tail; the * synthetic result keeps the exchange closed so the summary request is not * rejected. Leave `false` for normal turns: a *trailing* missing result there * means the call is still in-flight and must not be closed prematurely. (A * *non-trailing* missing result is always closed regardless of this flag — see * `repairToolExchangeAdjacency` — because a later turn proves it is not * in-flight.) */ readonly synthesizeMissing?: boolean; /** * When `true`, drop any `tool_result` whose `toolCallId` matches no assistant * `tool_use` anywhere in the provided messages. Such an orphan is wire-invalid * on every strict provider and useless to the model (it has no record of the * call the result answers). Enabled on every request-building projection — the * normal wire, the strict resend, and the compaction summarizer — so a stray * result never reaches a provider. Left OFF for non-request projections (e.g. * token-estimating a history slice), where a result's matching call may * legitimately sit outside the slice and must not be mistaken for an orphan. */ readonly dropOrphanResults?: boolean; /** * When `true`, drop leading messages until the first one is a user turn. Strict * providers require the first message to be `user`; a history that (after * dropping/compaction) starts with an assistant or tool message is rejected. * Strict-resend only — the normal path keeps the original opening. */ readonly dropLeadingNonUser?: boolean; /** * When `true`, merge back-to-back assistant messages into one. Strict providers * reject consecutive same-role turns ("roles must alternate"); consecutive user * turns are already merged at the provider boundary, but consecutive assistant * turns are not. Strict-resend only. Content is concatenated verbatim — callers * must not rely on this when extended-thinking ordering matters, but two * consecutive assistant turns do not arise in well-formed transcripts. */ readonly mergeConsecutiveAssistants?: boolean; /** * When `true`, drop assistant tool calls whose id already appeared earlier * (first occurrence wins; a message left with no content and no calls is * dropped), and drop every tool result after the first for a given id so the * kept call keeps exactly one answer. Duplicate ids are wire-invalid on * strict providers ("`tool_use` ids must be unique") and no other pass can * repair them. Strict-resend only: a provider that accepted the duplicates * when it produced them (e.g. per-response counter ids like `call_0`) must * keep seeing the history it generated — deduping the normal path would * silently erase its later tool exchanges. */ readonly dedupeDuplicateToolCalls?: boolean; /** * Optional sink invoked for every repair the projector applies to keep the * outgoing wire valid: a displaced result moved back next to its call, a * synthetic result invented for a missing one, a stray result dropped, a * leading non-user message dropped, or consecutive assistants merged. The * projection itself stays a pure transform; the caller decides whether/how to * surface these (the context logs them so a silently-mangled history is never * papered over without a trace). Not called when the history is already * well-formed. */ readonly onAnomaly?: (anomaly: ProjectionAnomaly) => void; } declare type Promisable = [T] extends [Promise] ? T | Awaited : T | Promise; declare type PromisableMethods = { [K in keyof T]: T[K] extends (...args: infer Args) => infer Return ? (...args: Args) => Promisable : never; }; declare type Promisify = [T] extends [Promise] ? T : Promise; declare interface PromptAbortedEvent { readonly type: 'prompt.aborted'; readonly promptId: string; readonly abortedAt: string; } declare interface PromptCompletedEvent { readonly type: 'prompt.completed'; readonly promptId: string; readonly finishedAt: string; readonly reason?: 'completed' | 'failed' | 'blocked'; } export declare type PromptInput = readonly PromptPart[]; export declare type PromptOrigin = UserPromptOrigin | SkillActivationOrigin | PluginCommandOrigin | InjectionOrigin | ShellCommandOrigin | CompactionSummaryOrigin | SystemTriggerOrigin | BackgroundTaskOrigin | CronJobOrigin | CronMissedOrigin | HookResultOrigin | RetryOrigin; declare type PromptOrigin_2 = UserPromptOrigin_2 | SkillActivationOrigin_2 | PluginCommandOrigin_2 | InjectionOrigin_2 | ShellCommandOrigin_2 | CompactionSummaryOrigin_2 | SystemTriggerOrigin_2 | TaskOrigin | BackgroundTaskOrigin_2 | CronJobOrigin_2 | CronMissedOrigin_2 | HookResultOrigin_2 | RetryOrigin_2; export declare type PromptPart = Extract; declare interface PromptPayload { readonly input: readonly ContentPart[]; } declare interface PromptSteeredEvent { readonly type: 'prompt.steered'; readonly activePromptId: string; readonly promptIds: readonly string[]; readonly content: readonly MessageContent[]; readonly steeredAt: string; } declare interface PromptSubmittedEvent { readonly type: 'prompt.submitted'; readonly promptId: string; readonly userMessageId: string; readonly status: 'running' | 'queued' | 'blocked'; readonly content: readonly MessageContent[]; readonly createdAt: string; } export declare type ProviderConfig = z.infer; declare type ProviderConfig_2 = ({ type: 'anthropic'; } & AnthropicOptions) | ({ type: 'openai'; } & OpenAILegacyOptions) | ({ type: 'kimi'; } & KimiOptions) | ({ type: 'google-genai'; } & GoogleGenAIOptions) | ({ type: 'openai_responses'; } & OpenAIResponsesOptions) | ({ type: 'vertexai'; } & GoogleGenAIOptions); declare const ProviderConfigSchema: z.ZodObject<{ type: z.ZodEnum<{ anthropic: "anthropic"; vertexai: "vertexai"; kimi: "kimi"; openai: "openai"; "google-genai": "google-genai"; openai_responses: "openai_responses"; }>; apiKey: z.ZodOptional; baseUrl: z.ZodOptional; defaultModel: z.ZodOptional; oauth: z.ZodOptional; key: z.ZodString; oauthHost: z.ZodOptional; }, z.core.$strip>>; env: z.ZodOptional>; customHeaders: z.ZodOptional>; source: z.ZodOptional>; }, z.core.$strip>; declare class ProviderManager implements ModelProvider { private readonly options; constructor(options: ProviderManagerOptions); private get config(); resolveProviderConfig(model: string): ResolvedRuntimeProvider; resolveAuth(model: string, options?: { readonly log?: Logger; }): AuthorizedRequest | undefined; } declare interface ProviderManagerOptions { readonly config: KimiConfig | (() => KimiConfig); readonly kimiRequestHeaders?: Record; readonly resolveOAuthTokenProvider?: OAuthTokenProviderResolver; readonly promptCacheKey?: string; } declare type ProviderRefreshChange = z.infer; declare const providerRefreshChangeSchema: z.ZodObject<{ provider_id: z.ZodString; provider_name: z.ZodString; added: z.ZodNumber; removed: z.ZodNumber; }, z.core.$strip>; declare type ProviderRefreshFailure = z.infer; declare const providerRefreshFailureSchema: z.ZodObject<{ provider: z.ZodString; reason: z.ZodString; }, z.core.$strip>; /** * Options that can be forwarded to a single {@link ChatProvider.generate} call. */ declare interface ProviderRequestAuth { /** Bearer/API token resolved for this specific provider request. */ apiKey?: string; /** Request-scoped headers. These override constructor-level default headers. */ headers?: Record; } export declare type ProviderType = z.infer; declare type ProviderType_2 = ProviderConfig_2['type']; declare const ProviderTypeSchema: z.ZodEnum<{ anthropic: "anthropic"; vertexai: "vertexai"; kimi: "kimi"; openai: "openai"; "google-genai": "google-genai"; openai_responses: "openai_responses"; }>; declare interface PutGlobalMcpServerPayload { readonly server: McpServerConfig; } export declare type QuestionAnswerMethod = 'enter' | 'space' | 'number_key'; /** * Flattened answers keyed by question text; values are the chosen option * label(s) (comma-joined for multi-select) or free-form "Other" text. * `true` marks a question as answered without echoing a concrete value. */ export declare type QuestionAnswers = Record; export declare interface QuestionBackgroundTaskInfo extends BackgroundTaskInfoBase { readonly kind: 'question'; readonly questionCount: number; readonly toolCallId?: string; } export declare type QuestionHandler = (request: QuestionRequest) => MaybePromise; export declare interface QuestionItem { readonly question: string; readonly header?: string; readonly body?: string; readonly options: readonly QuestionOption[]; readonly multiSelect?: boolean; readonly otherLabel?: string; readonly otherDescription?: string; } export declare interface QuestionOption { readonly label: string; readonly description?: string; } export declare interface QuestionRequest { readonly turnId?: number; readonly toolCallId?: string; readonly questions: readonly QuestionItem[]; } export declare interface QuestionResponse { readonly answers: QuestionAnswers; readonly method?: QuestionAnswerMethod | undefined; } export declare type QuestionResult = null | QuestionAnswers | QuestionResponse; declare interface QuestionTaskInfo extends TaskInfoBase { readonly kind: 'question'; readonly questionCount: number; readonly toolCallId?: string; } declare type QueuedSubagentTask = SpawnQueuedSubagentTask | ResumeQueuedSubagentTask; declare interface ReconnectMcpServerPayload { readonly name: string; } declare interface ReconnectMcpServerRpcInput extends SessionIdRpcInput { readonly name: string; } export declare function redact(value: T): T; declare interface RegisterBackgroundTaskOptions { /** * When false, the task is tracked by the manager but a foreground tool call * is still waiting for it. It can later be detached through RPC. */ readonly detached?: boolean; /** Deadline owned by BackgroundManager. `0` and `undefined` do not arm a timer. */ readonly timeoutMs?: number; /** * When set, detaching a foreground task resets its deadline to this value * (counted from the detach moment). Lets a command started with a short * foreground timeout run longer once it is moved to the background. */ readonly detachTimeoutMs?: number; /** * When true, a foreground task whose deadline fires is detached to the * background (re-armed to `detachTimeoutMs`) instead of being killed. * Only meaningful for non-detached registrations. */ readonly autoBackgroundOnTimeout?: boolean; /** Foreground caller signal. Ignored for tasks created already detached. */ readonly signal?: AbortSignal; } declare interface RegisterToolPayload { readonly name: string; readonly description: string; readonly parameters: Record; } declare type ReloadPluginsResult = ReloadSummary; export declare interface ReloadSessionInput extends ResumeSessionInput { readonly forcePluginSessionStartReminder?: boolean; } export declare interface ReloadSessionOptions { readonly forcePluginSessionStartReminder?: boolean; } declare interface ReloadSessionPayload { readonly sessionId: string; /** * When true, append a fresh `` system reminder to the * main agent after the session is reloaded, reflecting the currently enabled * plugins. Used by the explicit `/reload` command so the model sees plugin * changes without starting a new session. Defaults to false. */ readonly forcePluginSessionStartReminder?: boolean; } declare interface ReloadSessionRpcInput extends SessionIdRpcInput { readonly forcePluginSessionStartReminder?: boolean; } export declare interface ReloadSummary { readonly added: readonly string[]; readonly removed: readonly string[]; readonly errors: ReadonlyArray<{ readonly id: string; readonly message: string; }>; } declare interface RemoveKimiProviderPayload { readonly providerId: string; } declare interface RemovePluginPayload { readonly id: string; } export declare interface RenameSessionInput { readonly id: string; readonly title: string; } declare interface RenameSessionPayload { readonly title: string; } declare type RenameSessionRequest = SessionScopedPayload; declare class ReplayBuilder { readonly agent: Agent; private readonly options; postRestoring: boolean; captureLiveRecords: boolean; protected readonly records: AgentReplayRecord[]; private frozen; private segmentStart; constructor(agent: Agent, options?: ReplayBuilderOptions); push(record: AgentReplayRecordPayload): void; patchLast(type: T, patch: Partial>): void; removeLastMessages(removedMessages: ReadonlySet): void; finishRestoringRecord(type: string): boolean; buildResult(): readonly AgentReplayRecord[]; private removeMessagesFrom; } declare interface ReplayBuilderOptions { readonly range?: ReplayRangeOptions; } declare interface ReplayRangeOptions { readonly start?: number; readonly count?: number; } export declare function resolveConfigPath(input: { readonly homeDir?: string | undefined; readonly configPath?: string | undefined; }): string; declare interface ResolvedAgentProfile { name: string; description?: string; systemPrompt: SystemPromptRenderer; tools: string[]; whenToUse?: string; subagents?: Record; } declare type ResolvedCoreAPI = RPCMethods; declare interface ResolvedRuntimeProvider { readonly providerName: string; readonly provider: ProviderConfig_2; readonly modelCapabilities: ModelCapability; /** Declared 'always_thinking' capability — the model cannot disable thinking. */ readonly alwaysThinking?: boolean; readonly supportEfforts?: readonly string[]; readonly defaultEffort?: string; readonly maxOutputSize?: number; /** Configured provider wire type (`provider.type`), before any model-level protocol override. */ readonly type: ProviderType; /** Model-level protocol override (`alias.protocol`); when set, takes precedence over `type` for transport selection. */ readonly protocol: ModelAlias['protocol']; } declare interface ResolvedToolExecutionHookContext extends ToolExecutionHookContext { readonly execution: RunnableToolExecution; } export declare function resolveGlobalLogPath(homeDir: string): string; export declare interface ResolveKimiConfigPathInput { readonly homeDir?: string | undefined; readonly configPath?: string | undefined; } export declare function resolveKimiHome(homeDir?: string | undefined): string; declare type ResponseFormat = JsonObjectResponseFormat | JsonSchemaResponseFormat; declare interface RestoringContext { time?: number; } declare interface ResumedAgent { readonly agent: Agent; readonly warning?: string; } export declare interface ResumedAgentState { readonly type: AgentType; readonly config: AgentConfigData; readonly context: AgentContextData; readonly replay: readonly AgentReplayRecord[]; readonly permission: PermissionData; readonly plan: PlanData; readonly swarmMode?: boolean | undefined; readonly usage: UsageStatus; readonly tools: readonly ToolInfo[]; readonly toolStore?: Readonly>; readonly background: readonly BackgroundTaskInfo[]; } export declare type ResumedSessionState = Pick; export declare interface ResumedSessionSummary extends SessionSummary, ResumedSessionState { } declare type ResumeQueuedSubagentTask = BaseQueuedSubagentTask & { readonly kind: 'resume'; readonly resumeAgentId: string; }; export declare interface ResumeSessionInput { readonly id: string; readonly kaos?: Kaos | undefined; readonly persistenceKaos?: Kaos | undefined; readonly additionalDirs?: readonly string[]; /** Include persisted subagent states in the returned replay snapshot. */ readonly includeSubagents?: boolean; /** Botiverse mirror: standing-prompt text preserved across resume. */ readonly roleAdditional?: string; readonly sessionStartedProperties?: TelemetryProperties; } declare interface ResumeSessionPayload { readonly sessionId: string; readonly mcpServers?: Readonly>; readonly additionalDirs?: readonly string[]; /** Include persisted subagent states in the returned replay snapshot. */ readonly includeSubagents?: boolean; /** Botiverse mirror: standing-prompt preserved across resume. */ readonly roleAdditional?: string; } declare interface ResumeSessionResult extends SessionSummary_2 { readonly sessionMetadata: SessionMeta; readonly agents: Readonly>; readonly warning?: string | undefined; } declare interface RetryOrigin { readonly kind: 'retry'; readonly trigger?: string; } declare interface RetryOrigin_2 { readonly kind: 'retry'; readonly trigger?: string; } export declare type Role = 'system' | 'user' | 'assistant' | 'tool'; declare interface RPCCallOptions { signal?: AbortSignal; } declare type RPCClient, Other extends Record> = (self: PromisableMethods) => Promise>; declare type RPCMethods = { [K in keyof T]: T[K] extends (payload: infer Payload) => infer Return ? (payload: Payload, options?: RPCCallOptions) => Promisify : never; }; declare interface RunnableToolExecution { readonly isError?: false | undefined; readonly accesses?: ToolAccesses | undefined; readonly display?: ToolInputDisplay | undefined; readonly description?: string; /** * Stops scheduling later tool calls in the same provider batch. Use this only * for tools whose successful action changes turn lifecycle state. */ readonly stopBatchAfterThis?: boolean | undefined; readonly approvalRule: string; readonly matchesRule?: ((ruleArgs: string) => boolean) | undefined; readonly execute: (ctx: ExecutableToolContext) => Promise; } declare interface RunShellCommandPayload { readonly command: string; /** * TUI-generated correlation id echoed back on every `shell.output` live event * so the client can route chunks to the matching entry and drop stale events * from a prior run. Optional for callers that don't stream. */ readonly commandId?: string; } declare interface RunSubagentOptions { readonly parentToolCallId: string; readonly parentToolCallUuid?: string; readonly prompt: string; readonly description: string; readonly swarmIndex?: number; readonly runInBackground: boolean; readonly signal: AbortSignal; readonly onReady?: () => void; readonly suppressRateLimitFailureEvent?: boolean; } declare interface RuntimeConfigLoadResult { readonly config: KimiConfig; /** Problems in config.toml itself; non-empty means parts (or all) of the file were ignored. */ readonly fileWarnings: readonly string[]; /** Problems applying KIMI_MODEL_* env overrides; the overlay was skipped. */ readonly envWarnings: readonly string[]; /** * Set when the file is entirely unusable (unreadable, TOML syntax error, or * nothing salvageable) and `config` is pure defaults. Startup fails fast on * this — defaults-only means the user looks logged out, which is worse than * an actionable parse error. Mid-run reloads ignore it and keep the last * good config instead. */ readonly fileError?: KimiError; } declare interface SDKAgentAPI { emitEvent: (event: AgentEvent) => void; requestApproval: (request: ApprovalRequest) => Promise; requestQuestion: (request: QuestionRequest) => Promise; toolCall: (request: ToolCallRequest) => Promise; } declare type SDKAgentRPC = RPCMethods; declare type SDKAPI = WithSessionId; declare type SDKRPC = RPCMethods; export declare class SDKRpcClient extends SDKRpcClientBase { readonly homeDir: string; readonly configPath: string; readonly identity: KimiHostIdentity | undefined; readonly telemetry: TelemetryClient; readonly auth: KimiAuthFacade; readonly core: KimiCore; private readonly ready; constructor(options?: SDKRpcClientOptions); ensureConfigFile(): Promise; close(): Promise; protected getRpc(): Promise>; createSessionWithKaos(input: CreateSessionOptions, kaos: Kaos, persistenceKaos?: Kaos): Promise; resumeSessionWithKaos(input: ResumeSessionInput, kaos: Kaos, persistenceKaos?: Kaos): Promise; private createKimiRequestHeaders; } export declare abstract class SDKRpcClientBase { private readonly interactiveAgentScope; private readonly eventListeners; private readonly approvalHandlers; private readonly questionHandlers; get interactiveAgentId(): string; withInteractiveAgent(agentId: string, fn: () => T): T; protected abstract getRpc(): Promise; createSession(input: CreateSessionOptions): Promise; createSessionWithKaos(input: CreateSessionOptions, kaos: Kaos, persistenceKaos?: Kaos): Promise; resumeSession(input: ResumeSessionInput): Promise; resumeSessionWithKaos(input: ResumeSessionInput, kaos: Kaos, persistenceKaos?: Kaos): Promise; reloadSession(input: ReloadSessionRpcInput): Promise; forkSession(input: ForkSessionInput): Promise; closeSession(input: SessionIdRpcInput): Promise; deleteSession(input: SessionIdRpcInput): Promise; listSessions(input?: ListSessionsOptions): Promise; listWorkspaceSkills(workDir: string): Promise; renameSession(input: RenameSessionInput): Promise; exportSession(input: ExportSessionInput): Promise; getConfig(input?: GetConfigOptions): Promise; getConfigDiagnostics(): Promise; getExperimentalFeatures(): Promise; setConfig(input: KimiConfigPatch): Promise; removeProvider(providerId: string): Promise; listGlobalMcpServers(): Promise; addGlobalMcpServer(server: McpServerConfig): Promise; updateGlobalMcpServer(server: McpServerConfig): Promise; removeGlobalMcpServer(name: string): Promise; beginGlobalMcpServerAuth(name: string): Promise; completeGlobalMcpServerAuth(input: { readonly flowId: string; readonly timeoutMs?: number; }, signal?: AbortSignal): Promise; cancelGlobalMcpServerAuth(flowId: string): Promise; resetGlobalMcpServerAuth(name: string): Promise; testGlobalMcpServer(name: string, options?: { readonly cwd?: string; }): Promise; prompt(input: SessionPromptRpcInput): Promise; runShellCommand(input: { sessionId: string; command: string; commandId?: string; }): Promise<{ stdout: string; stderr: string; isError?: boolean; backgrounded?: boolean; }>; cancelShellCommand(input: { sessionId: string; commandId: string; }): Promise; steer(input: SessionPromptRpcInput): Promise; generateAgentsMd(input: SessionIdRpcInput): Promise; getSessionWarnings(input: SessionIdRpcInput): Promise; addAdditionalDir(input: AddAdditionalDirInput): Promise; startBtw(input: SessionIdRpcInput): Promise; cancel(input: SessionIdRpcInput): Promise; clearContext(input: SessionIdRpcInput): Promise; importContext(input: ImportContextRpcInput): Promise; setModel(input: SetSessionModelRpcInput): Promise; setThinking(input: SetSessionThinkingRpcInput): Promise; setPermission(input: SetSessionPermissionRpcInput): Promise; updateSessionMetadata(input: UpdateSessionMetadataRpcInput): Promise; setPlanMode(input: SetSessionPlanModeRpcInput): Promise; setSwarmMode(input: SetSessionSwarmModeRpcInput): Promise; swarm(input: SessionPromptRpcInput): Promise; private enterSwarmMode; private exitSwarmMode; getPlan(input: SessionIdRpcInput): Promise; clearPlan(input: SessionIdRpcInput): Promise; compact(input: SessionIdRpcInput & CompactOptions): Promise; cancelCompaction(input: SessionIdRpcInput): Promise; undoHistory(input: SessionIdRpcInput & { count: number; }): Promise; getContext(input: SessionIdRpcInput): Promise; getUsage(input: SessionIdRpcInput): Promise; getStatus(input: SessionIdRpcInput): Promise; listSkills(input: SessionIdRpcInput): Promise; listPluginCommands(input: SessionIdRpcInput): Promise; listBackgroundTasks(input: SessionIdRpcInput & { activeOnly?: boolean; limit?: number; }): Promise; getBackgroundTaskOutput(input: SessionIdRpcInput & { taskId: string; tail?: number; }): Promise; stopBackgroundTask(input: SessionIdRpcInput & { taskId: string; reason?: string; }): Promise; detachBackgroundTask(input: SessionIdRpcInput & { taskId: string; }): Promise; waitForBackgroundTasksOnPrint(input: SessionIdRpcInput): Promise; handlePrintMainTurnCompleted(input: SessionIdRpcInput): Promise<'finish' | 'continue'>; createGoal(input: SessionIdRpcInput & CreateGoalInput): Promise; getGoal(input: SessionIdRpcInput): Promise; pauseGoal(input: SessionIdRpcInput): Promise; resumeGoal(input: SessionIdRpcInput): Promise; cancelGoal(input: SessionIdRpcInput): Promise; getCronTasks(input: SessionIdRpcInput): Promise; listMcpServers(input: SessionIdRpcInput): Promise; getMcpStartupMetrics(input: SessionIdRpcInput): Promise; reconnectMcpServer(input: ReconnectMcpServerRpcInput): Promise; listPlugins(): Promise; installPlugin(source: string): Promise; setPluginEnabled(id: string, enabled: boolean): Promise; setPluginMcpServerEnabled(id: string, server: string, enabled: boolean): Promise; removePlugin(id: string): Promise; reloadPlugins(): Promise; getPluginInfo(id: string): Promise; activateSkill(input: ActivateSkillRpcInput): Promise; activatePluginCommand(input: ActivatePluginCommandRpcInput): Promise; onEvent(listener: (event: Event_2) => void): Unsubscribe; receiveEvent(event: Event_2): void; setApprovalHandler(sessionId: string, handler: ApprovalHandler | undefined): void; setQuestionHandler(sessionId: string, handler: QuestionHandler | undefined): void; clearSessionHandlers(sessionId: string): void; requestApproval(request: ApprovalRequest & { sessionId: string; agentId: string; }): Promise; requestQuestion(request: QuestionRequest & { sessionId: string; agentId: string; }): Promise; toolCall(request: ToolCallRequest): Promise; } export declare interface SDKRpcClientOptions { readonly homeDir?: string; readonly configPath?: string; readonly identity?: KimiHostIdentity; readonly resolveOAuthTokenProvider?: OAuthTokenProviderResolver; readonly skillDirs?: readonly string[]; readonly telemetry?: TelemetryClient; readonly onOAuthRefresh?: (outcome: OAuthRefreshOutcome) => void; /** * Host UI mode (`'print'` for `kimi -p`, `'cli'` for the TUI, ...). Forwarded * to the v1 core, which applies print-mode config defaults when it is * `'print'`. */ readonly uiMode?: string; } declare type SDKSessionAPI = WithAgentId; declare type SDKSessionRPC = RPCMethods; export declare type ServicesConfig = z.infer; declare const ServicesConfigSchema: z.ZodObject<{ moonshotSearch: z.ZodOptional; apiKey: z.ZodOptional; oauth: z.ZodOptional; key: z.ZodString; oauthHost: z.ZodOptional; }, z.core.$strip>>; customHeaders: z.ZodOptional>; }, z.core.$strip>>; moonshotFetch: z.ZodOptional; apiKey: z.ZodOptional; oauth: z.ZodOptional; key: z.ZodString; oauthHost: z.ZodOptional; }, z.core.$strip>>; customHeaders: z.ZodOptional>; }, z.core.$strip>>; }, z.core.$strip>; export declare class Session { readonly id: string; readonly workDir: string; summary?: SessionSummary | undefined; private resumeState; private readonly rpc; private readonly onClose?; private closed; constructor(options: SessionOptions); getResumeState(): ResumedSessionState | undefined; reloadSession(options?: ReloadSessionOptions): Promise; onEvent(listener: (event: Event_2) => void): Unsubscribe; setApprovalHandler(handler: ApprovalHandler | undefined): void; setQuestionHandler(handler: QuestionHandler | undefined): void; prompt(input: string | PromptInput): Promise; /** Execute a user-initiated `!` shell command (silent — does not prompt the * model). Resolves with the command's stdout/stderr for immediate display. * Pass `commandId` to receive live `shell.output` events for this command. */ runShellCommand(command: string, options?: { commandId?: string; }): Promise<{ stdout: string; stderr: string; isError?: boolean; backgrounded?: boolean; }>; /** Cancel a running `!` shell command by its commandId (e.g. on Esc / Ctrl+C). */ cancelShellCommand(commandId: string): Promise; steer(input: string | PromptInput): Promise; swarm(input: string | PromptInput): Promise; init(): Promise; getSessionWarnings(): Promise; addAdditionalDir(path: string, options?: AddAdditionalDirOptions): Promise; startBtw(): Promise; cancel(): Promise; setModel(model: string): Promise; setThinking(effort: ThinkingEffort): Promise; setPermission(mode: PermissionMode): Promise; /** Shallow-merge host-owned fields into this session's persisted custom metadata. */ updateMetadata(patch: JsonObject): Promise; setPlanMode(enabled: boolean): Promise; setSwarmMode(enabled: boolean, trigger: SwarmModeTrigger): Promise; getPlan(): Promise; clearPlan(): Promise; compact(options?: CompactOptions): Promise; cancelCompaction(): Promise; undoHistory(count?: number): Promise; /** Clear this session's model context without creating a new session. */ clearContext(): Promise; /** Append imported text to this session's context without prompting the model. */ importContext(content: string, source: string): Promise; getContext(): Promise; getUsage(): Promise; getStatus(): Promise; listSkills(): Promise; listPluginCommands(): Promise; /** * List background tasks for this session's interactive agent. * * Defaults to all tasks (including terminal/lost). Pass * `{ activeOnly: true }` to filter to non-terminal entries. */ listBackgroundTasks(options?: { activeOnly?: boolean; limit?: number; }): Promise; /** * Read a background task's captured output. Returns the in-memory * ring buffer if available, otherwise falls back to the persisted * `/tasks//output.log`. `tail` caps the returned * string to that many trailing characters. */ getBackgroundTaskOutput(taskId: string, options?: { tail?: number; }): Promise; /** * Request a running background task to stop. Sends SIGTERM with a * grace period (handled by the core BPM); subscribers receive a * `background.task.terminated` event when the kill settles. Calls * for unknown or already-terminal task ids are no-ops at the core * level — this method does not throw in those cases. */ stopBackgroundTask(taskId: string, options?: { reason?: string; }): Promise; /** * Detach a running foreground task so the current tool call can return while * the task continues under background-task management. */ detachBackgroundTask(taskId: string): Promise; /** * Block until every still-running background task (across all agents in this * session) reaches a terminal state. Used by `kimi -p` after the main agent's * turn finishes when the resolved print background mode is `'drain'` * (`print_background_mode = "drain"`, or the legacy `keep_alive_on_exit = true` * fallback), so background subagents get a chance to complete before the process * exits. No-op in other modes. Bounded by `background.print_wait_ceiling_s`. */ waitForBackgroundTasksOnPrint(): Promise; /** * Used by `kimi -p` after the main agent's turn ends with `reason === * 'completed'`. Returns `'finish'` when the run may exit, or `'continue'` when * the caller must keep the session alive so a background-task completion can * steer the main agent into a new turn. Policy is selected by * `background.print_background_mode` (`'exit' | 'drain' | 'steer'`); when unset * it falls back to the legacy `keep_alive_on_exit` mapping (`true ⇒ 'drain'`). */ handlePrintMainTurnCompleted(): Promise<'finish' | 'continue'>; createGoal(input: CreateGoalInput): Promise; getGoal(): Promise; pauseGoal(): Promise; resumeGoal(): Promise; cancelGoal(): Promise; /** * Enumerate the cron tasks scheduled in this session. Hosts running a * bounded session lifetime (e.g. `kimi -p`) poll this to decide whether * pending scheduled work still needs the process alive. */ getCronTasks(): Promise; listMcpServers(): Promise; getMcpStartupMetrics(): Promise; reconnectMcpServer(name: string): Promise; listPlugins(): Promise; installPlugin(source: string): Promise; setPluginEnabled(id: string, enabled: boolean): Promise; setPluginMcpServerEnabled(id: string, server: string, enabled: boolean): Promise; removePlugin(id: string): Promise; reloadPlugins(): Promise; getPluginInfo(id: string): Promise; activateSkill(name: string, args?: string | undefined): Promise; activatePluginCommand(pluginId: string, commandName: string, args?: string | undefined): Promise; close(): Promise; /** @internal */ emitMetaUpdated(patch: { readonly title?: string | undefined; }): void; private emit; private ensureOpen; private requireSummary; } declare type Session_2 = z.infer; declare class Session_3 { readonly options: SessionOptions_2; readonly rpc: SDKSessionRPC; readonly telemetry: TelemetryClient; readonly skills: SessionSkillRegistry; readonly agents: Map; readonly mcp: McpConnectionManager; readonly log: Logger; private readonly logHandle; readonly hookEngine: HookEngine; readonly experimentalFlags: ExperimentalFlagResolver; readonly imageLimits: ImageLimits; private toolKaos; private persistenceKaos; private additionalDirs; private sessionAdditionalDirs; private roleAdditional?; private readonly pluginCommands; private agentIdCounter; private readonly skillsReady; metadata: SessionMeta; private writeMetadataPromise; private agentsMdWarning; private printSteerDeadline; private printSteerTurns; constructor(options: SessionOptions_2); setToolKaos(kaos: Kaos): void; getAdditionalDirs(): readonly string[]; setAdditionalDirs(additionalDirs: readonly string[]): Promise; setBaseAdditionalDirs(additionalDirs: readonly string[]): Promise; addAdditionalDir(path: string, persist?: boolean): Promise; private notifyAdditionalDirAdded; /** * Kaos used by session-internal bootstrap (AGENTS.md context, cwd listing) * and metadata persistence. Always backed by the persistence sink (typically * the local filesystem) so a transient ACP-side failure on system files like * `AGENTS.md` never blocks `bootstrapAgentProfile` — tool calls still route * through `agent.kaos` and continue to honor the ACP bridge. */ systemContextKaos(cwd: string): Kaos; createMain(): Promise; resume(): Promise<{ warning?: string; }>; close(): Promise; closeForReload(): Promise; private cancelActiveTurnsOnClose; private activeBackgroundAgentIds; private cancelAgentTurnOnClose; private stopBackgroundTasksOnExit; /** * Wait for all still-running background tasks (across every agent) to reach a * terminal state before a `kimi -p` (print) run exits. * * Only runs when the resolved print background mode is `'drain'` (see * `resolvePrintBackgroundMode`): `print_background_mode = "drain"`, or the * legacy `keep_alive_on_exit = true` fallback. In every other mode it returns * immediately. The wait is bounded by `background.print_wait_ceiling_s` * (default `PRINT_WAIT_CEILING_S_DEFAULT`, effectively unbounded) so a wedged * task can still be given up on eventually. * * Terminal notifications are suppressed for each task while we wait, so a task * completing cannot `turn.steer` the (already finished) main agent into launching * a new turn. (This is exactly what `'steer'` mode avoids by never calling here.) */ waitForBackgroundTasksOnPrint(): Promise; /** * Resolve the effective print-mode (`kimi -p`) background-task policy. * * `background.print_background_mode` is authoritative when set. Otherwise we * fall back to the legacy `background.keep_alive_on_exit` mapping so existing * configs keep their behavior: `keep_alive_on_exit = true` ⇒ `'drain'` * (suppress + drain background tasks before exit). When neither is set the * mode defaults to `'steer'`: a headless run stays alive while background * tasks are pending so their completions can steer new main turns. */ private resolvePrintBackgroundMode; private countActiveBackgroundTasks; /** * Decide what the `kimi -p` driver should do after the main agent's turn ends * with `reason === 'completed'`. Returns `'finish'` when the run may exit, or * `'continue'` when the driver must stay alive so a background-task completion * can `turn.steer` the main agent into a new turn. * * - 'exit' : finish immediately. * - 'drain' : suppress + drain background tasks, then finish (legacy * `keep_alive_on_exit = true` behavior). * - 'steer' : while background tasks are still pending, return 'continue' so * completions steer new main turns; finish once quiescent, or when * the wall-clock ceiling (`print_wait_ceiling_s`) or the turn cap * (`print_max_turns`) is reached. This is the default mode. */ handlePrintMainTurnCompleted(): Promise<'finish' | 'continue'>; createAgent(config: Partial, options?: CreateAgentOptions): Promise<{ readonly id: string; readonly agent: Agent; }>; ensureAgentResumed(id: string): Promise; /** * Applies a profile's derived config — cwd, system prompt, active tools — to * an agent. Fresh creation and resume-of-an-incomplete-wire both route * through here so the two paths cannot drift apart. */ private bootstrapAgentProfile; getSessionWarnings(): Promise; private computeAgentsMdWarning; generateAgentsMd(): Promise; /** * Appends a fresh `` system reminder to the main agent * using the currently enabled plugins, then flushes records so the reminder is * persisted and visible on the wire. Used by the explicit `/reload` flow after * the session has been re-resumed with reloaded plugin state. * * When no plugin session start is currently resolvable but an earlier * When no plugin session start is currently resolvable but the context may still * carry stale plugin guidance — either an earlier `` * reminder, or a compaction summary that may have folded one in — appends a * neutralizing reminder instead, so the model does not keep following stale * plugin instructions and the turn-loop injector does not dedup against them. */ appendPluginSessionStartReminder(): Promise; private shouldNeutralizePluginSessionStart; get hasActiveTurn(): boolean; protected get metadataPath(): string; writeMetadata(): Promise; readMetadata(): Promise; flushMetadata(): Promise; listSkills(): Promise; listPluginCommands(): readonly PluginCommandDef[]; private loadSkills; private loadMcpServers; private emitInitialMcpLoadError; private onMcpServerStatusChange; private refreshAgentBuiltinTools; private instantiateAgent; private permissionOptions; getReadyAgent(id: string): Agent | undefined; readyAgents(): Iterable; private resolveAgentEntry; private resumeAgent; private resumePersistedAgent; private restoreAgentProfileHandle; private resolvePersistedProfile; private nextGeneratedAgentId; private requireMainAgent; private triggerSessionStart; private triggerSessionEnd; } declare type SessionAgentPayload = SessionScopedPayload>; declare interface SessionAPI extends AgentAPIWithId { renameSession: (payload: RenameSessionPayload) => void; updateSessionMetadata: (payload: UpdateSessionMetadataPayload) => void; getSessionMetadata: (payload: EmptyPayload) => SessionMeta; listSkills: (payload: EmptyPayload) => readonly SkillSummary[]; listPluginCommands: (payload: EmptyPayload) => readonly PluginCommandDef[]; listMcpServers: (payload: EmptyPayload) => readonly McpServerInfo[]; getMcpStartupMetrics: (payload: EmptyPayload) => McpStartupMetrics; reconnectMcpServer: (payload: ReconnectMcpServerPayload) => void; generateAgentsMd: (payload: EmptyPayload) => void; getSessionWarnings: (payload: EmptyPayload) => readonly SessionWarning[]; waitForBackgroundTasksOnPrint: (payload: EmptyPayload) => void; handlePrintMainTurnCompleted: (payload: EmptyPayload) => 'finish' | 'continue'; addAdditionalDir: (payload: AddAdditionalDirPayload) => AddAdditionalDirResult_2; } declare type SessionAPIWithId = WithSessionId; declare interface SessionCreatedEvent { readonly type: 'event.session.created'; readonly session: Session_2; } declare class SessionCronStore { /** * Backing map. `Map` preserves insertion order in JS, which we rely on * for {@link list}. */ private readonly tasks; /** * Generate a fresh 8-hex id and add the task. `createdAt` is set to * the supplied `nowMs` — the store never reads its own clock. * * Throws if the PRNG fails to produce an unused id within * {@link MAX_ID_ATTEMPTS} attempts. That should be unreachable in * practice; surfacing it as a throw beats silently retrying forever. */ add(init: SessionCronTaskInit, nowMs: number): CronTask; /** * Insert a previously-persisted task verbatim — id and createdAt * stay as they are on disk. Used by `CronManager.loadFromDisk()` to * rehydrate the store on resume. Unlike {@link add}, this does NOT * generate a new id; the caller is responsible for ensuring the id * matches the expected shape (the persistence layer's regex / * shape-guard handle this upstream). * * Overwrites any existing in-memory task with the same id — reload * is a "replace" operation, not a "merge". Callers that want merge * semantics should clear the store first. */ adopt(task: CronTask): void; /** * Stamp `lastFiredAt` on the in-memory task. Used by the scheduler * cursor-advance callback so the value flows back to disk via the * manager's persistence path. Returns the updated record (so the * manager can hand it straight to the per-id JSON writer), or * `undefined` when no task with that id is present — the latter * happens harmlessly if a task was concurrently removed between the * scheduler's fire and the cursor callback. */ markFired(id: string, lastFiredAt: number): CronTask | undefined; /** Returns the task or `undefined`. */ get(id: string): CronTask | undefined; /** * Snapshot in insertion order. Returns a fresh array on every call — * callers may mutate the returned array without affecting the store, * and successive calls return distinct array references. */ list(): readonly CronTask[]; /** * Remove the given ids. Returns the subset that were actually present * (so the caller can detect already-missing ids and report them). * Order of the returned ids follows the input order, not insertion * order. */ remove(ids: readonly string[]): readonly string[]; /** Empty the store. Convenience for tests / shutdown. */ clear(): void; private generateUniqueId; } /** * Input to {@link SessionCronStore.add}: everything the caller supplies, * minus `id` and `createdAt` which the store generates. */ declare type SessionCronTaskInit = Omit; declare interface SessionIdRpcInput { readonly sessionId: string; } declare interface SessionMcpConfig { readonly servers: Record; } /** * The session-owned originals store: `/media-originals`. Sits * next to the session's other artifacts (`tasks/`, `cron/`, `logs/`, * `agents/`) and is removed with the session. */ export declare function sessionMediaOriginalsDir(sessionDir: string): string; declare interface SessionMeta { createdAt: string; updatedAt: string; title: string; isCustomTitle: boolean; lastPrompt?: string; forkedFrom?: string; /** Absolute working directory the session was created in. Persisted so the * session directory is self-describing and the global session index does not * have to be trusted for the (one-way-hashed) workDir. */ workDir?: string; /** Directories added for this session only. Unlike workspace local config, * these follow the session across close/resume without affecting any other * session opened in the same workspace. */ additionalDirs?: string[]; agents: Record; custom: Record; } declare type SessionMetadataPatch = Partial>; export declare interface SessionMetaUpdatedEvent { readonly type: 'session.meta.updated'; readonly title?: string; readonly patch?: Record; } declare interface SessionOptions { readonly id: string; readonly workDir: string; readonly summary?: SessionSummary | undefined; readonly resumeState?: ResumedSessionState | undefined; readonly rpc: SDKRpcClientBase; readonly onClose?: (() => void | Promise) | undefined; } declare interface SessionOptions_2 { readonly kaos: Kaos; readonly persistenceKaos?: Kaos; readonly config?: KimiConfig; readonly id?: string | undefined; readonly homedir: string; readonly kimiHomeDir?: string; readonly rpc: SDKSessionRPC; readonly toolServices?: ToolServices; readonly initializeMainAgent?: boolean | undefined; readonly providerManager?: ProviderManager | undefined; readonly background?: BackgroundConfig | undefined; readonly hooks?: readonly HookDef[]; readonly permissionRules?: readonly PermissionRule[]; readonly skills?: SessionSkillConfig; readonly mcpConfig?: SessionMcpConfig; readonly telemetry?: TelemetryClient | undefined; readonly pluginSessionStarts?: readonly EnabledPluginSessionStart[]; readonly pluginCommands?: readonly PluginCommandDef[]; readonly appVersion?: string; readonly experimentalFlags?: ExperimentalFlagResolver; /** Owner-scoped [image] limits, threaded from the owning core into every agent. */ readonly imageLimits?: ImageLimits; readonly additionalDirs?: readonly string[]; /** Botiverse mirror: standing-prompt (Raft role/context), session-level → every agent's ROLE_ADDITIONAL. */ readonly roleAdditional?: string; /** * Print-mode (`kimi -p`) only: hold the main turn open while background * subagents (`kind === 'agent'`) are still running, idle-waiting until they * finish before the run exits. Set via the SDK `createSession` option. */ readonly drainAgentTasksOnStop?: boolean; } declare type SessionPendingInteraction = z.infer; declare const sessionPendingInteractionSchema: z.ZodEnum<{ none: "none"; approval: "approval"; question: "question"; }>; export declare type SessionPlan = PlanInfo | null; declare interface SessionPromptRpcInput { readonly sessionId: string; readonly input: PromptInput; } declare const sessionSchema: z.ZodObject<{ id: z.ZodString; workspace_id: z.ZodString; title: z.ZodString; created_at: z.ZodPipe>; updated_at: z.ZodPipe>; busy: z.ZodBoolean; main_turn_active: z.ZodOptional; pending_interaction: z.ZodOptional>; last_turn_reason: z.ZodOptional>; archived: z.ZodOptional; current_prompt_id: z.ZodOptional; last_prompt: z.ZodOptional; metadata: z.ZodObject<{ cwd: z.ZodString; }, z.core.$catchall>; agent_config: z.ZodObject<{ model: z.ZodString; system_prompt: z.ZodOptional; tools: z.ZodOptional>; mcp_servers: z.ZodOptional>; thinking: z.ZodOptional; permission_mode: z.ZodOptional>; plan_mode: z.ZodOptional; swarm_mode: z.ZodOptional; goal_objective: z.ZodOptional; goal_control: z.ZodOptional>; }, z.core.$strip>; usage: z.ZodObject<{ input_tokens: z.ZodNumber; output_tokens: z.ZodNumber; cache_read_tokens: z.ZodNumber; cache_creation_tokens: z.ZodNumber; total_cost_usd: z.ZodNumber; context_tokens: z.ZodNumber; context_limit: z.ZodNumber; turn_count: z.ZodNumber; }, z.core.$strip>; permission_rules: z.ZodArray; value: z.ZodOptional; }, z.core.$strip>>; decision: z.ZodLiteral<"approved">; created_at: z.ZodPipe>; created_by: z.ZodEnum<{ user: "user"; agent: "agent"; }>; }, z.core.$strip>>; message_count: z.ZodNumber; last_seq: z.ZodNumber; }, z.core.$strip>; declare type SessionScopedPayload = T & { readonly sessionId: string; }; declare interface SessionSkillConfig { readonly userHomeDir?: string; /** Brand data dir (KIMI_CODE_HOME); user brand skills live under `/skills`. */ readonly brandHomeDir?: string; readonly explicitDirs?: readonly string[]; readonly extraDirs?: readonly string[]; readonly pluginSkillRoots?: readonly SkillRoot[]; readonly mergeAllAvailableSkills?: boolean; readonly builtinDir?: string; } declare class SessionSkillRegistry implements SkillRegistry { private readonly byName; private readonly byPluginAndName; private readonly roots; private readonly skipped; private readonly discoverImpl; private readonly onWarning; readonly sessionId?: string; constructor(options?: SkillRegistryOptions); loadRoots(roots: readonly SkillRoot[]): Promise; registerBuiltinSkill(skill: SkillDefinition): void; register(skill: SkillDefinition, options?: { readonly replace?: boolean; }): void; getSkill(name: string): SkillDefinition | undefined; getPluginSkill(pluginId: string, name: string): SkillDefinition | undefined; private indexPluginSkill; renderSkillPrompt(skill: SkillDefinition, rawArgs: string): string; listSkills(): readonly SkillDefinition[]; listInvocableSkills(): readonly SkillDefinition[]; getSkillRoots(): readonly string[]; getSkippedByPolicy(): readonly SkippedSkill[]; getKimiSkillsDescription(): string; getModelSkillListing(): string; } export declare interface SessionStatus { readonly model?: string; readonly thinkingEffort: string; readonly permission: PermissionMode; readonly planMode: boolean; readonly swarmMode?: boolean | undefined; readonly contextTokens: number; readonly maxContextTokens: number; readonly contextUsage: number; readonly usage?: SessionUsage; } /** * @deprecated Replaced by {@link SessionWorkChangedEvent}: awaiting states * ride the approval/question channels and outcomes ride turn.ended. Kept so * pre-change journals still parse during replay. */ declare interface SessionStatusChangedEvent { readonly type: 'event.session.status_changed'; readonly status: 'idle' | 'running' | 'awaiting_approval' | 'awaiting_question' | 'aborted'; readonly previous_status: 'idle' | 'running' | 'awaiting_approval' | 'awaiting_question' | 'aborted'; readonly current_prompt_id?: string; } declare class SessionSubagentHost { private readonly session; private readonly ownerAgentId; private readonly activeChildren; constructor(session: Session_3, ownerAgentId: string); spawn(options: SpawnSubagentOptions): Promise; resume(agentId: string, options: RunSubagentOptions): Promise; retry(agentId: string, options: RunSubagentOptions): Promise; private ensureIdleSubagent; runQueued(tasks: readonly QueuedSubagentTask[]): Promise>>; suspended(event: SubagentSuspendedEvent_2): void; startBtw(): Promise; cancelAll(reason?: unknown): void; markActiveChildDetached(agentId: string): void; getProfileName(agentId: string): Promise; getSwarmItem(agentId: string): string | undefined; private resolveProfile; private runWithActiveChild; private runPromptTurn; private waitForChildCompletion; private configureChild; /** * Hold the run open until the child agent's background tasks (background * Bash, nested background agents) settle — the print-mode (`kimi -p`) * drain semantics applied to subagent completion. Drained tasks get their * terminal notifications suppressed: without that, a task outliving the * child's final turn steers a fresh turn on the finished subagent * (`steer` degrades to `launch`), which runs unobserved and whose output * never reaches the parent. Bounded by the run's signal — the Agent * tool's per-run timeout / user-cancel envelope covers the drain too. */ private drainChildBackgroundTasks; /** * Suppress terminal notifications for every child background task — * including already-settled ones whose notification may still be in * flight. `list(false)` is required: the active-only list drops a task * the moment it terminates, which is exactly when an unsuppressed * notification can still steer an orphan turn onto the finished child. */ private suppressChildTaskNotifications; private triggerSubagentStart; private triggerSubagentStop; private observeFirstRequest; private emitSubagentSpawned; private emitSubagentStarted; private emitSubagentFailed; } export declare interface SessionSummary { readonly id: string; readonly title?: string | undefined; readonly lastPrompt?: string; readonly workDir: string; readonly sessionDir: string; readonly createdAt: number; readonly updatedAt: number; readonly archived?: boolean | undefined; readonly metadata?: JsonObject | undefined; readonly additionalDirs?: readonly string[]; } declare interface SessionSummary_2 { readonly id: string; readonly title?: string | undefined; readonly lastPrompt?: string; readonly workDir: string; readonly sessionDir: string; readonly createdAt: number; readonly updatedAt: number; readonly archived?: boolean | undefined; readonly metadata?: JsonObject_2 | undefined; readonly additionalDirs?: readonly string[]; } export declare interface SessionUsage { readonly byModel?: Record | undefined; readonly currentTurn?: TokenUsage | undefined; readonly total?: TokenUsage | undefined; } declare type SessionWarning = z.infer; declare const sessionWarningSchema: z.ZodObject<{ code: z.ZodString; message: z.ZodString; severity: z.ZodEnum<{ error: "error"; info: "info"; warning: "warning"; }>; }, z.core.$strip>; declare interface SessionWorkChangedEvent { readonly type: 'event.session.work_changed'; readonly busy: boolean; /** Main-agent turn liveness, excluding background and sub-agent work. */ readonly main_turn_active?: boolean; /** Highest-priority pending interaction for clients without a session subscription. */ readonly pending_interaction?: SessionPendingInteraction; /** Outcome of the MAIN agent's most recent turn, when one has ended since * activation (see `Session.last_turn_reason`). */ readonly last_turn_reason?: 'completed' | 'cancelled' | 'failed'; } declare interface SetActiveToolsPayload { readonly names: readonly string[]; } declare type SetKimiConfigPayload = KimiConfigPatch; declare interface SetModelPayload { readonly model: string; } declare interface SetModelResult { readonly model: string; readonly providerName?: string | undefined; } declare interface SetPermissionPayload { readonly mode: PermissionMode_2; } declare interface SetPluginEnabledPayload { readonly id: string; readonly enabled: boolean; } declare interface SetPluginMcpServerEnabledPayload { readonly id: string; readonly server: string; readonly enabled: boolean; } declare interface SetSessionModelRpcInput extends SessionIdRpcInput { readonly model: string; } declare interface SetSessionModelRpcResult { readonly model: string; readonly providerName?: string | undefined; } declare interface SetSessionPermissionRpcInput extends SessionIdRpcInput { readonly mode: PermissionMode; } declare interface SetSessionPlanModeRpcInput extends SessionIdRpcInput { readonly enabled: boolean; } declare type SetSessionSwarmModeRpcInput = (SessionIdRpcInput & { readonly enabled: true; readonly trigger: SwarmModeTrigger; }) | (SessionIdRpcInput & { readonly enabled: false; }); declare interface SetSessionThinkingRpcInput extends SessionIdRpcInput { readonly effort: string; } declare interface SetThinkingPayload { readonly effort: string; } declare interface ShellCommandOrigin { readonly kind: 'shell_command'; readonly phase: 'input' | 'output'; /** Only present on `phase: 'output'` — whether the command failed, so replay * can colour stderr red only for actual failures (not warnings). */ readonly isError?: boolean; } declare interface ShellCommandOrigin_2 { readonly kind: 'shell_command'; readonly phase: 'input' | 'output'; /** Only present on `phase: 'output'` — whether the command failed, so replay * can colour stderr red only for actual failures (not warnings). */ readonly isError?: boolean; } declare interface ShellCommandResult { readonly stdout: string; readonly stderr: string; /** True when the command failed (non-zero exit / timeout / killed) — used by * the TUI to render stderr in red only for actual failures, not warnings. */ readonly isError?: boolean; /** True when the command was detached to the background (ctrl+b) instead of * completing in the foreground. The TUI uses this to skip the normal final * render (the backgrounding path owns the UI + model notification). */ readonly backgrounded?: boolean; } export declare interface ShellEnvironment { readonly term?: string | undefined; readonly termProgram?: string | undefined; readonly termProgramVersion?: string | undefined; readonly multiplexer?: string | undefined; readonly shell?: string | undefined; } declare type ShellName = 'bash' | 'sh'; /** * Live stdout/stderr chunk from a user-initiated `!` shell command. Transient * (never persisted, never replayed) — the final output is still recorded once * via `context.append_message` on completion. `commandId` lets the TUI route * chunks to the matching live entry and drop stale events from a prior run. */ declare interface ShellOutputEvent { readonly type: 'shell.output'; readonly commandId: string; readonly update: ToolUpdate; } /** * Fired once when a `!` shell command's foreground process task is registered, * carrying the task id so the client can detach (ctrl+b) it. Transient. */ declare interface ShellStartedEvent { readonly type: 'shell.started'; readonly commandId: string; readonly taskId: string; } export declare interface SkillActivatedEvent { readonly type: 'skill.activated'; readonly activationId: string; readonly skillName: string; readonly skillArgs?: string; readonly trigger: 'user-slash' | 'model-tool' | 'nested-skill'; readonly skillPath?: string; readonly skillSource?: SkillSource_2; } declare interface SkillActivationOrigin { readonly kind: 'skill_activation'; readonly activationId: string; readonly skillName: string; readonly skillArgs?: string | undefined; readonly trigger: 'user-slash' | 'model-tool' | 'nested-skill'; readonly skillType?: string | undefined; readonly skillPath?: string | undefined; readonly skillSource?: SkillSource | undefined; } declare interface SkillActivationOrigin_2 { readonly kind: 'skill_activation'; readonly activationId: string; readonly skillName: string; readonly skillArgs?: string; readonly trigger: 'user-slash' | 'model-tool' | 'nested-skill'; readonly skillType?: string; readonly skillPath?: string; readonly skillSource?: SkillSource_2; } declare interface SkillDefinition { readonly name: string; readonly description: string; readonly path: string; readonly dir: string; readonly content: string; readonly metadata: SkillMetadata; readonly source: SkillSource; readonly plugin?: SkillPluginContext; readonly mermaid?: string | undefined; readonly d2?: string; } declare class SkillManager { protected readonly agent: Agent; readonly registry: SkillRegistry; constructor(agent: Agent, registry: SkillRegistry); activate(input: ActivateSkillPayload): void; recordActivation(origin: SkillActivationOrigin, input?: readonly ContentPart[] | undefined): void; } declare interface SkillMetadata { readonly name?: string | undefined; readonly description?: string | undefined; readonly type?: string | undefined; readonly whenToUse?: string | undefined; readonly disableModelInvocation?: boolean | undefined; readonly isSubSkill?: boolean | undefined; readonly safe?: boolean | undefined; readonly arguments?: readonly unknown[] | string | undefined; readonly [key: string]: unknown; } declare interface SkillPluginContext { readonly id: string; readonly instructions?: string; } declare interface SkillRegistry { getSkill(name: string): SkillDefinition | undefined; getPluginSkill(pluginId: string, name: string): SkillDefinition | undefined; renderSkillPrompt(skill: SkillDefinition, rawArgs: string): string; listInvocableSkills(): readonly SkillDefinition[]; getSkillRoots(): readonly string[]; getModelSkillListing(): string; } declare interface SkillRegistryOptions { readonly discover?: typeof discoverSkills; readonly onWarning?: (message: string, cause?: unknown) => void; readonly sessionId?: string; } declare interface SkillRoot { readonly path: string; readonly source: SkillSource; readonly plugin?: SkillPluginContext; } declare type SkillSource = 'project' | 'user' | 'extra' | 'builtin'; declare type SkillSource_2 = 'project' | 'user' | 'extra' | 'builtin'; export declare interface SkillSummary { readonly name: string; readonly description: string; readonly path: string; readonly source: 'builtin' | 'user' | 'extra' | 'project'; readonly type?: string | undefined; readonly disableModelInvocation?: boolean | undefined; readonly isSubSkill?: boolean | undefined; } declare interface SkillSummary_2 { readonly name: string; readonly description: string; readonly path: string; readonly source: SkillSource; readonly type?: string | undefined; readonly disableModelInvocation?: boolean | undefined; readonly isSubSkill?: boolean | undefined; } declare interface SkippedSkill { readonly path: string; readonly type: string; readonly reason: string; } declare type SpawnQueuedSubagentTask = BaseQueuedSubagentTask & { readonly kind: 'spawn'; readonly resumeAgentId?: undefined; }; declare interface SpawnSubagentOptions extends RunSubagentOptions { readonly profileName: string; readonly swarmItem?: string; } /** * KAOS stat result, mirroring Python's os.stat_result fields. */ declare interface StatResult { stMode: number; stIno: number; stDev: number; stNlink: number; stUid: number; stGid: number; stSize: number; stAtime: number; stMtime: number; stCtime: number; } declare interface SteerPayload { readonly input: readonly ContentPart[]; } declare interface StopBackgroundPayload { readonly taskId: string; /** Free-form human-readable reason persisted with the task record. */ readonly reason?: string; } /** * Decode-phase accounting for a single streamed generation. Splits the window * from the first streamed part to stream end into the time spent waiting on the * provider for the next part (server + network) versus the time spent * processing each part in-process (deep copy, host callbacks, part merging). * * Because both buckets are wall-clock measured on the single JS thread, a * stop-the-world GC pause that lands while awaiting the next part is counted in * {@link serverDecodeMs}; a non-trivial {@link clientConsumeMs} share is the * unambiguous signal that the host's per-part processing is throttling decode. */ declare interface StreamDecodeStats { /** Cumulative time spent awaiting the next streamed part (server + network). */ readonly serverDecodeMs: number; /** Cumulative time spent processing streamed parts in-process (client). */ readonly clientConsumeMs: number; } /** * An async-iterable stream of message parts produced by a single LLM response. * * Consumers iterate over the stream with `for await..of` to receive * {@link StreamedMessagePart} chunks. After the iteration completes, the * {@link id}, {@link usage}, {@link finishReason}, and * {@link rawFinishReason} properties reflect the final values reported by * the provider. */ declare interface StreamedMessage { [Symbol.asyncIterator](): AsyncIterator; /** Provider-assigned response identifier, or `null` if not available. */ readonly id: string | null; /** Token usage statistics, populated after the stream completes. */ readonly usage: TokenUsage_3 | null; /** * Normalized finish reason, populated after the stream completes. * * `null` if the provider did not emit a finish_reason (for example, the * stream was interrupted before the final event arrived). */ readonly finishReason: FinishReason_2 | null; /** * Raw provider-specific finish_reason string, preserved verbatim as an * escape hatch for callers that need the original wire value. * * `null` if the provider did not emit a finish_reason. */ readonly rawFinishReason: string | null; /** * Provider trace identifier read from the `x-trace-id` response header * (Kimi/KFC only). Available as soon as the response headers arrive — * before the stream body is drained — so hosts can attribute even an * interrupted stream to its server-side request. `null` when the provider * does not report one. */ readonly traceId?: string | null; } /** * A single chunk yielded by {@link StreamedMessage}'s async iterator. * * During streaming, the generate loop receives a sequence of these parts and * merges compatible consecutive parts (e.g. TextPart + TextPart) in-place so * the final {@link Message} contains fully-assembled content. * * Tool-call completion is inferred from merge boundaries (a non-merging next * part flushes the pending tool call) and from stream end. Provider adapters * are responsible for translating their native "done" signals into this * shape; they do not emit a separate done event. */ declare type StreamedMessagePart = ContentPart | ToolCall | ToolCallPart; export declare interface SubagentCompletedEvent { readonly type: 'subagent.completed'; readonly subagentId: string; readonly resultSummary: string; readonly usage?: TokenUsage_2; readonly contextTokens?: number; } declare type SubagentCompletion = { readonly result: string; readonly usage?: TokenUsage_3; }; export declare interface SubagentFailedEvent { readonly type: 'subagent.failed'; readonly subagentId: string; readonly error: string; } declare type SubagentHandle = { readonly agentId: string; readonly profileName: string; readonly resumed: boolean; readonly completion: Promise; }; declare type SubagentResult = { readonly task: QueuedSubagentTask; readonly agentId?: string; readonly status: 'completed' | 'failed' | 'aborted'; readonly state?: 'started' | 'not_started'; readonly result?: string; readonly usage?: TokenUsage_3; readonly error?: string; }; export declare interface SubagentSpawnedEvent { readonly type: 'subagent.spawned'; readonly subagentId: string; readonly subagentName: string; readonly parentToolCallId: string; readonly parentToolCallUuid?: string; readonly parentAgentId?: string; readonly callerAgentId?: string; readonly description?: string; readonly swarmIndex?: number; readonly runInBackground: boolean; } export declare interface SubagentStartedEvent { readonly type: 'subagent.started'; readonly subagentId: string; } export declare interface SubagentSuspendedEvent { readonly type: 'subagent.suspended'; readonly subagentId: string; readonly reason: string; } declare type SubagentSuspendedEvent_2 = { readonly task: QueuedSubagentTask; readonly agentId: string; readonly reason: string; }; declare class SwarmMode { protected readonly agent: Agent; protected active: SwarmModeTrigger | null; constructor(agent: Agent); enter(trigger: SwarmModeTrigger): void; restoreEnter(trigger: SwarmModeTrigger): void; exit(): void; get isActive(): boolean; get shouldAutoExit(): boolean; } /** * manual = persistent toggle (/swarm on); * task = one-shot /swarm prompt; * tool = AgentSwarm entry. */ declare type SwarmModeTrigger = 'manual' | 'task' | 'tool'; /** * Runtime context supplied to a system prompt renderer. * * Captures everything determined at render time rather than at profile-load * time: the OS/shell, working directory, AGENTS.md instructions, available * skills, and so on. Loaders return renderers; callers invoke them with * the live context whenever a concrete prompt is needed. */ declare interface SystemPromptContext { readonly osEnv: Environment; readonly cwd: string; readonly now?: string | Date; readonly cwdListing?: string; readonly agentsMd?: string; readonly skills?: SkillRegistry | string; readonly additionalDirsInfo?: string; readonly roleAdditional?: string; } declare type SystemPromptRenderer = (context: SystemPromptContext) => string; declare interface SystemTriggerOrigin { readonly kind: 'system_trigger'; readonly name: string; } declare interface SystemTriggerOrigin_2 { readonly kind: 'system_trigger'; readonly name: string; } declare type TaskInfo = ProcessTaskInfo | AgentTaskInfo | QuestionTaskInfo; declare interface TaskInfoBase { readonly taskId: string; readonly description: string; readonly status: TaskLifecycleStatus; readonly detached?: boolean; readonly startedAt: number; readonly endedAt: number | null; readonly stopReason?: string; readonly terminalNotificationSuppressed?: boolean; readonly timeoutMs?: number; } declare type TaskLifecycleStatus = 'running' | 'completed' | 'failed' | 'timed_out' | 'killed' | 'lost'; declare interface TaskOrigin { readonly kind: 'task'; readonly taskId: string; readonly status: TaskLifecycleStatus; readonly notificationId: string; } declare interface TaskStartedEvent { readonly type: 'task.started'; readonly info: TaskInfo; } declare interface TaskTerminatedEvent { readonly type: 'task.terminated'; readonly info: TaskInfo; } export declare interface TelemetryClient { track(event: string, properties?: TelemetryProperties): void; withContext?(patch: TelemetryContextPatch): TelemetryClient; setContext?(patch: TelemetryContextPatch): void; } export declare interface TelemetryContextPatch { readonly sessionId?: string | null; } export declare type TelemetryProperties = Readonly>; declare type TelemetryPropertyValue = boolean | number | string | undefined | null; declare interface TestGlobalMcpServerPayload { readonly name: string; readonly cwd?: string; } export declare interface TestMcpServerOptions { readonly cwd?: string; } declare interface TextPart { type: 'text'; text: string; } export declare type TextPromptPart = Extract; export declare type ThinkingConfig = z.infer; declare interface ThinkingConfig_2 { type?: 'enabled' | 'disabled'; effort?: string; keep?: unknown; [key: string]: unknown; } declare const ThinkingConfigSchema: z.ZodObject<{ enabled: z.ZodOptional; effort: z.ZodOptional; keep: z.ZodOptional; }, z.core.$strip>; export declare interface ThinkingDeltaEvent { readonly type: 'thinking.delta'; readonly turnId: number; readonly delta: string; } /** * Thinking effort passed to {@link ChatProvider.withThinking}. * * `'off'` and `'on'` are the only reserved values: `'off'` disables thinking, * and `'on'` is the on-signal for boolean models (models that do not declare * `support_efforts`). Everything else is a model-declared effort (e.g. * `"low"`, `"high"`, `"max"`) carried as an open string. The type collapses to * `string` at runtime; it exists purely as a semantic marker that a value is * expected to be `'off'`, `'on'`, or a model-declared effort. * * Provider adapters receive an already-resolved effort. Adapters with a native * effort field pass concrete strings through to their upstream API; model * compatibility and fallback are resolved before this boundary. */ export declare type ThinkingEffort = 'off' | 'on' | (string & {}); declare interface ThinkPart { type: 'think'; think: string; encrypted?: string; } export declare interface TokenUsage { readonly inputOther: number; readonly output: number; readonly inputCacheRead: number; readonly inputCacheCreation: number; } declare interface TokenUsage_2 { readonly inputOther: number; readonly output: number; readonly inputCacheRead: number; readonly inputCacheCreation: number; } /** * Token usage breakdown for a single LLM generation. * * Providers map their native usage counters into this common shape so * callers can aggregate costs without caring about the backend. */ declare interface TokenUsage_3 { /** Input tokens that were neither cache-read nor cache-created. */ inputOther: number; /** Output (completion) tokens generated by the model. */ output: number; /** Input tokens served from the provider's prompt cache. */ inputCacheRead: number; /** Input tokens written into the provider's prompt cache. */ inputCacheCreation: number; } /** * Normalize any value into a KimiErrorPayload. * * Recognized errors: * - `KimiError`: passthrough. * - `APIStatusError`: 429 -> rate_limit, 401 -> auth_error, otherwise -> api_error. * - `APIConnectionError` / `APITimeoutError`: connection_error. * - `ChatProviderError`: api_error. * * Anything else collapses to `internal`. We never echo `cause` or stack on * the wire. */ export declare function toKimiErrorPayload(error: unknown): KimiErrorPayload; /** * A tool that the model may invoke during generation. * * The definition is provider-agnostic; each provider implementation converts * it to the appropriate wire format (e.g. OpenAI function-calling, Anthropic * tool-use, Google function declarations). */ declare interface Tool { /** Unique tool name used to match invocations. */ name: string; /** Human-readable description shown to the model. */ description: string; /** JSON Schema describing the tool's parameters. */ parameters: Record; /** * Client-internal marker: the tool is executable but its schema must not be * serialized into the request's top-level `tools[]` — it was (or will be) * delivered through a message-level `tools` declaration instead, and the * top-level list must stay byte-stable for prompt caching. `generate()` * strips marked tools before the provider builds the request; the marker * itself never reaches the wire. */ deferred?: true; } declare type ToolAccesses = readonly ToolResourceAccess[]; declare const ToolAccesses: { none(): ToolAccesses; all(): ToolAccesses; file(operation: ToolFileAccessOperation, path: string, options?: { readonly recursive?: boolean; }): ToolAccesses; readFile(path: string): ToolAccesses; readTree(path: string): ToolAccesses; writeFile(path: string): ToolAccesses; writeTree(path: string): ToolAccesses; readWriteFile(path: string): ToolAccesses; readWriteTree(path: string): ToolAccesses; searchTree(path: string): ToolAccesses; conflict(left: ToolAccesses, right: ToolAccesses): boolean; }; export declare interface ToolCall { type: 'function'; id: string; name: string; arguments: string | null; extras?: Record; /** * Provider-specific streaming index used to route argument deltas to the * correct parallel tool call. Set by streaming providers (OpenAI Chat * Completions `index`, Responses API `item_id`). Consumed internally by * {@link generate} and stripped before the ToolCall is stored on a Message. * * @internal */ _streamIndex?: number | string; } declare interface ToolCallDelta { readonly toolCallId: string; readonly name?: string | undefined; readonly argumentsPart?: string | undefined; } export declare interface ToolCallDeltaEvent { readonly type: 'tool.call.delta'; readonly turnId: number; readonly toolCallId: string; readonly name?: string; readonly argumentsPart?: string; } /** Streaming delta for tool call arguments. */ declare interface ToolCallPart { type: 'tool_call_part'; argumentsPart: string | null; /** * Provider-specific index for routing this streaming delta to the correct * parallel tool call. Used by OpenAI Chat Completions (`index`) and * Responses API (`item_id`/`output_index`). When absent, the delta is * appended to the most-recently-seen ToolCall (single-tool-call fallback). */ index?: number | string; } export declare interface ToolCallRequest { readonly turnId?: number | undefined; readonly toolCallId: string; readonly args: unknown; } export declare interface ToolCallResponse { readonly output: string | ContentPart[]; readonly isError?: boolean | undefined; } export declare interface ToolCallStartedEvent { readonly type: 'tool.call.started'; readonly turnId: number; readonly toolCallId: string; readonly name: string; readonly args: unknown; readonly description?: string; readonly display?: ToolInputDisplay; } declare type ToolExecution = RunnableToolExecution | ExecutableToolErrorResult; declare interface ToolExecutionHookContext extends LoopStepHookContext { readonly traceId?: string; readonly toolCall: ToolCall; readonly toolCalls: readonly ToolCall[]; readonly tool?: ExecutableTool | undefined; readonly args: unknown; } declare interface ToolFileAccess { readonly kind: 'file'; readonly operation: ToolFileAccessOperation; readonly path: string; readonly recursive?: boolean; } declare type ToolFileAccessOperation = 'read' | 'write' | 'readwrite' | 'search'; export declare interface ToolInfo { readonly name: string; readonly description: string; readonly active: boolean; readonly source: ToolSource; } export declare type ToolInputDisplay = z.infer; declare const ToolInputDisplaySchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ kind: z.ZodLiteral<"command">; command: z.ZodString; cwd: z.ZodOptional; description: z.ZodOptional; language: z.ZodOptional>; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"file_io">; operation: z.ZodEnum<{ read: "read"; write: "write"; edit: "edit"; glob: "glob"; grep: "grep"; }>; path: z.ZodString; detail: z.ZodOptional; content: z.ZodOptional; before: z.ZodOptional; after: z.ZodOptional; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"diff">; path: z.ZodString; before: z.ZodString; after: z.ZodString; hunks: z.ZodOptional; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"search">; query: z.ZodString; scope: z.ZodOptional; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"url_fetch">; url: z.ZodString; method: z.ZodOptional; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"agent_call">; agent_name: z.ZodString; prompt: z.ZodString; background: z.ZodOptional; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"skill_call">; skill_name: z.ZodString; args: z.ZodOptional; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"todo_list">; items: z.ZodArray>; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"task">; task_id: z.ZodString; status: z.ZodString; description: z.ZodString; task_kind: z.ZodOptional; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"task_stop">; task_id: z.ZodString; task_description: z.ZodString; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"plan_review">; plan: z.ZodString; path: z.ZodOptional; options: z.ZodOptional>>>; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"goal_start">; objective: z.ZodString; completionCriterion: z.ZodOptional; mode: z.ZodEnum<{ manual: "manual"; yolo: "yolo"; }>; }, z.core.$strip>, z.ZodObject<{ kind: z.ZodLiteral<"generic">; summary: z.ZodString; detail: z.ZodOptional; }, z.core.$strip>], "kind">; export declare interface ToolListUpdatedEvent { readonly type: 'tool.list.updated'; readonly reason: ToolListUpdatedReason; readonly serverName: string; } export declare type ToolListUpdatedReason = 'mcp.connected' | 'mcp.disconnected' | 'mcp.failed'; declare class ToolManager { protected readonly agent: Agent; protected builtinTools: Map; protected readonly userTools: Map; protected readonly mcpTools: Map; private loopToolsOverride; /** server name → list of qualified tool names registered for that server. */ protected readonly mcpToolsByServer: Map; protected enabledTools: Set; /** Glob patterns (e.g. `mcp__*`, `mcp__github__*`) gating which MCP tools the profile exposes. */ private mcpAccessPatterns; /** * Defer-window lead for the loaded-tools ledger: names marked loaded whose * schema message may still sit in the context's deferred queue (an open tool * exchange). The history itself is the source of truth — * `loadedDynamicToolNames()` unions this set with a history scan — so * undo/compaction/resume never need to roll this back. */ private readonly pendingLoadedDynamicTools; protected readonly store: Partial; private mcpToolStatusUnsubscribe; /** * `serverName\nhash` keys of `mcp.tools_discovered` records already durable * in this wire log. Restored on replay; reconnects with an unchanged raw * tool list, allow-list, and collision outcome do not re-log. */ private readonly seenMcpDiscoveries; /** * Discoveries observed before the record log opened (constructor-time * attach can run before `agent.resume()` replays the wire — see * `AgentRecords.observabilityReady`). The dedup decision must be re-made at * drain time, after replay has restored `seenMcpDiscoveries`. */ private readonly pendingMcpDiscoveries; private mcpDiscoveryDrainSubscribed; /** Abort controllers for in-flight `!` shell commands, keyed by commandId so * the TUI can cancel (Esc / Ctrl+C) a running command. */ private readonly shellCommandControllers; constructor(agent: Agent); protected get toolStore(): ToolStore; attachMcpTools(): void; updateStore(key: K, value: ToolStoreData[K]): void; /** * Execute a user-initiated `!` shell command. Reuses the builtin Bash tool * (same kaos / cwd / BackgroundManager as the agent), recording the command * and its output as `shell_command`-origin messages. It does NOT start a turn * — the model is not prompted (parity with claude-code's `shouldQuery: false`). */ runShellCommand(command: string, commandId?: string): Promise<{ stdout: string; stderr: string; isError?: boolean; backgrounded?: boolean; }>; cancelShellCommand(commandId: string): void; registerUserTool(input: UserToolRegistration): void; unregisterUserTool(name: string): void; inheritUserTools(parent: ToolManager): void; registerMcpServer(serverName: string, client: MCPClient, tools: readonly Tool[], enabledTools?: ReadonlySet): McpServerRegistrationResult; unregisterMcpServer(serverName: string): boolean; private handleMcpServerStatusChange; private registerNeedsAuthMcpServer; private registerConnectedMcpServer; /** Replay: a discovery with this hash is already durable; never re-log it. */ restoreMcpDiscovery(serverName: string, hash: string): void; /** * Observability record: the server's verbatim `tools/list` result plus how * this agent gated it (allow-list, collisions). See `records/types.ts`. * Parked while the record log has not opened yet (pre-replay window). */ private recordMcpToolsDiscovered; private drainPendingMcpDiscoveries; private writeMcpDiscovery; private emitMcpToolCollisions; setActiveTools(names: readonly string[]): void; copyLoopToolsFrom(source: ToolManager): void; private isMcpToolEnabled; /** * Whether MCP tools are disclosed progressively: kept out of the top-level * `tools[]` and loaded on demand via select_tools. Reads the agent's single * three-gate decision point. */ private get progressiveDisclosure(); /** * Names the model may select right now: registered MCP tools that pass the * profile's `mcp__*` access patterns, sorted for byte-stable announcements. * In disclosure mode the patterns keep their permission-filter role but stop * feeding the top-level `tools[]`. */ loadableDynamicToolNames(): string[]; /** * The loaded-tools ledger: every name whose full definition has been * delivered to the conversation via a `tools`-carrying message, plus the * defer-window pending set. History is the single source of truth, so the * ledger survives resume (records replay rebuilds the history), keeps its * state across undo (schema messages have `injection` origin and are not * undone), and empties at compaction (schema messages are discarded with * the folded history — the model re-selects what it still needs). */ loadedDynamicToolNames(): ReadonlySet; /** Mark names loaded ahead of their schema message landing in history. */ markDynamicToolsLoaded(names: Iterable): void; /** * Context was cleared (`/clear`): every schema message is gone, so the * defer-window lead must not keep reporting its names as loaded — a stale * entry would make select_tools answer "Already available" for a tool whose * definition the model can no longer see. */ onContextCleared(): void; /** * Compaction rebuilt the history and discarded every loaded schema with it * — the loaded set is empty from here on. A pending entry surviving past * this boundary would report a schema the context no longer carries as * loaded, and re-selecting it would wrongly answer "Already available" * instead of injecting. */ onContextCompacted(): void; /** * Plain schema snapshot of a registered MCP tool, read from the live * registry (never from history) at injection time. */ getMcpToolSchema(name: string): Tool | undefined; /** * Disclosure-mode wording for a tool-call preflight miss. A loaded tool * whose server dropped is a different situation from a never-announced name; * telling them apart stops the model from re-selecting a disconnected tool * in a loop or treating a transient disconnect as a permanent removal. */ missingToolMessage(name: string): string | undefined; toolInfos(): Iterable; data(): readonly ToolInfo[]; storeData(): Readonly>; initializeBuiltinTools(): void; refreshBuiltinTools(): void; private createVideoUploader; private videoUploadTelemetryProps; get loopTools(): readonly ExecutableTool[]; } /** * Strategy for converting tool-role message content. * * - `'extract_text'`: flatten all content parts into a single text string * (some providers require tool results as plain text). * - `null`: convert content parts to the standard OpenAI content-part array. */ declare type ToolMessageConversion = 'extract_text' | null; export declare interface ToolProgressEvent { readonly type: 'tool.progress'; readonly turnId: number; readonly toolCallId: string; readonly update: ToolUpdate; } declare type ToolResourceAccess = ToolFileAccess | ToolResourceAccessAll; declare interface ToolResourceAccessAll { /** * Arbitrary side effects or resources that cannot be represented as a * file access. This is intentionally operation-less and globally * exclusive for concurrency. */ readonly kind: 'all'; } export declare interface ToolResultEvent { readonly type: 'tool.result'; readonly turnId: number; readonly toolCallId: string; readonly output: unknown; readonly isError?: boolean; readonly synthetic?: boolean; } declare interface ToolServices { readonly urlFetcher?: UrlFetcher; readonly webSearcher?: WebSearchProvider; } declare type ToolSource = 'builtin' | 'user' | 'mcp'; declare interface ToolStore { get(key: K): ToolStoreData[K] | undefined; set(key: K, value: ToolStoreData[K]): void; } declare interface ToolStoreData { } declare type ToolStoreKey = Extract; declare interface ToolStoreUpdate { readonly key: K; readonly value: ToolStoreData[K]; } export declare interface ToolUpdate { readonly kind: 'stdout' | 'stderr' | 'progress' | 'status' | 'custom'; readonly text?: string; readonly percent?: number; readonly customKind?: string; readonly customData?: unknown; } declare interface ToolUpdate_2 { kind: 'stdout' | 'stderr' | 'progress' | 'status' | 'custom'; text?: string | undefined; percent?: number | undefined; /** Vendor-defined event identifier when `kind === 'custom'`. */ customKind?: string | undefined; /** Opaque payload paired with `customKind`. */ customData?: unknown; } export declare interface TurnEndedEvent { readonly type: 'turn.ended'; readonly turnId: number; readonly reason: TurnEndReason; readonly error?: KimiErrorPayload_2; readonly durationMs?: number; } export declare type TurnEndReason = 'completed' | 'cancelled' | 'failed' | 'blocked'; declare interface TurnEndResult { readonly event: TurnEndedEvent; readonly stopReason?: LoopTurnStopReason; readonly blockedByUserPromptHook?: boolean; } declare class TurnFlow { protected readonly agent: Agent; private steerBuffer; private turnId; private activeTurn; private readonly toolCallStartedAt; private readonly toolCallDupType; private readonly stepToolCallKeys; private readonly telemetryModeByTurn; private readonly currentStepByTurn; private readonly interruptedTelemetryTurnIds; private readonly interruptedTraceIdByTurn; private readonly stepFailureByTurn; private activeRequestTrace; private latestTraceId; private currentStep; constructor(agent: Agent); /** Best-effort agent id (main / generated id) derived from the agent homedir. */ private get agentId(); prompt(input: readonly ContentPart[], origin?: PromptOrigin): number | null; steer(input: readonly ContentPart[], origin?: PromptOrigin): number | null; retry(trigger?: string): number | null; private launch; /** Allocates the next monotonic turn id. */ private allocateTurnId; restorePrompt(): void; /** * Raise the turn counter to cover a turnId observed in a replayed loop event. * This is the authoritative source of the restored counter: every turn that * ran — a prompted turn, a goal continuation, or a steer-launched turn — * emits loop events carrying its real turnId, even though only prompted turns * write a `turn.prompt` record. Resuming then continues from `max + 1`. Only * ever raises the counter, never lowers it, so the live path (where `turnId` * is already allocated before any loop event) is unaffected. */ observeRestoredTurnId(turnId: number): void; restoreSteer(input: readonly ContentPart[], origin: PromptOrigin): void; cancel(turnId?: number, reason?: unknown): void; get currentId(): number; activeRequestTraceId(): string | undefined; get hasActiveTurn(): boolean; private ensureActiveTurn; waitForCurrentTurn(signal?: AbortSignal | undefined): Promise; waitForTurnFirstRequest(): Promise; private abortTurn; private flushSteerBuffer; /** * Replay inputs (prompts or steers) that were deferred while a manual compaction * held the context. Called by `FullCompaction` once the compaction lifecycle * (summary + reinjection) is done — and on cancel/failure — so deferred input is * never lost or stuck. If a turn is somehow already active (e.g. one that raced * and cancelled the compaction), let it consume the buffer like any other steer; * otherwise launch a fresh turn from the first buffered item, with the rest * draining into it via `flushSteerBuffer`. */ onCompactionFinished(): void; finishResume(): void; /** * The body of the single in-flight `activeTurn`. Routes to the goal driver * (sequential continuation turns) when a goal is active, otherwise runs exactly * one turn. Clears `activeTurn` when the whole run finishes (identified by the * launch signal, so a superseding turn is never clobbered). */ private turnWorker; /** * Drives an active goal as a sequence of ordinary turns — the autonomous * equivalent of the user repeatedly typing "continue". Each iteration runs one * full turn, then reads the goal status the model set via `UpdateGoal`: * `complete` (the record is cleared) / `blocked` stop the loop; `active` * (the model didn't decide) re-injects the goal reminder and runs the * next continuation turn. Aborted or failed turns pause the goal. Goal-state * blockers, such as explicit `UpdateGoal('blocked')`, prompt-hook blocks, and * budget limits, block it (all resumable). Returns the final turn's result. */ private driveGoal; private endGoalTurnWithoutModel; /** * Runs exactly one logical turn end to end: per-turn bookkeeping, `turn.started`, * the prompt + goal reminder, the step loop, and `turn.ended`. Goal-agnostic — * the driver layers goal semantics on top. Never throws; abnormal ends are * mapped to a `cancelled`/`failed` `turn.ended` and returned. */ private runOneTurn; private applyUserPromptHook; private runStepLoop; private closeAbandonedToolExchange; private buildDispatchEvent; private noteFirstRequestEvent; private trackLoopTelemetry; private beginTrackedStep; private trackToolLifecycle; private trackDuplicateToolCall; private hasPriorStepToolCallKey; private trackTurnInterrupted; private telemetryMode; /** * Resolve the current model's provider wire type and any model-level protocol * override for request telemetry. Never throws — telemetry must not break a * turn over an unresolvable provider config (the step loop will surface that * error on its own). */ private requestProtocolProps; private shouldTrackApiError; } export declare interface TurnStartedEvent { readonly type: 'turn.started'; readonly turnId: number; readonly origin: PromptOrigin_2; } export declare interface TurnStepCompletedEvent { readonly type: 'turn.step.completed'; readonly turnId: number; readonly step: number; readonly stepId?: string; readonly usage?: TokenUsage_2; readonly finishReason?: string; readonly llmFirstTokenLatencyMs?: number; readonly llmStreamDurationMs?: number; /** * Split of `llmFirstTokenLatencyMs`: in-process request-building time on the * client vs. network + API-server time to the first token. Both omitted when * the provider does not report the client/server boundary. */ readonly llmRequestBuildMs?: number; readonly llmServerFirstTokenMs?: number; /** * Split of `llmStreamDurationMs` (the decode window): time awaiting parts from * the provider vs. time processing parts in-process. Both omitted when the * provider stream did not report decode accounting. */ readonly llmServerDecodeMs?: number; readonly llmClientConsumeMs?: number; readonly providerFinishReason?: FinishReason; readonly rawFinishReason?: string; } export declare interface TurnStepInterruptedEvent { readonly type: 'turn.step.interrupted'; readonly turnId: number; readonly step: number; readonly stepId?: string; readonly reason: string; readonly message?: string; } export declare interface TurnStepRetryingEvent { readonly type: 'turn.step.retrying'; readonly turnId: number; readonly step: number; readonly stepId?: string; readonly failedAttempt: number; readonly nextAttempt: number; readonly maxAttempts: number; readonly delayMs: number; readonly errorName: string; readonly errorMessage: string; readonly statusCode?: number; } export declare interface TurnStepStartedEvent { readonly type: 'turn.step.started'; readonly turnId: number; readonly step: number; readonly stepId?: string; } declare interface UndoHistoryPayload { readonly count: number; } declare interface UnregisterToolPayload { readonly name: string; } export declare type Unsubscribe = () => void; declare interface UpdateSessionMetadataPayload { readonly metadata: SessionMetadataPatch; } declare type UpdateSessionMetadataRequest = SessionScopedPayload; declare interface UpdateSessionMetadataRpcInput extends SessionIdRpcInput { readonly metadata: JsonObject; } declare interface UrlFetcher { fetch(url: string, options?: { toolCallId?: string; }): Promise; } /** * How the returned content relates to the original response body. * * - `passthrough` — the body was already plain text / markdown and is * returned verbatim, in full. * - `extracted` — the body was an HTML page; only the main article text * was extracted and returned. */ declare type UrlFetchKind = 'passthrough' | 'extracted'; declare interface UrlFetchResult { /** The text handed to the LLM. */ content: string; /** Whether `content` is a verbatim passthrough or extracted main text. */ kind: UrlFetchKind; } declare class UsageRecorder { protected readonly agent?: Agent | undefined; private readonly byModel; private currentTurn; constructor(agent?: Agent | undefined); beginTurn(): void; endTurn(): void; record(model: string, usage: TokenUsage_3, scope?: UsageRecordScope): void; data(): UsageStatus; status(): UsageStatus | undefined; private byModelSnapshot; } declare type UsageRecordScope = 'session' | 'turn'; declare interface UsageRow { readonly label: string; readonly used: number; readonly limit: number; readonly resetHint?: string | undefined; } export declare interface UsageStatus { readonly byModel?: Record; readonly currentTurn?: TokenUsage_2; readonly total?: TokenUsage_2; } declare interface UserPromptOrigin { readonly kind: 'user'; } declare interface UserPromptOrigin_2 { readonly kind: 'user'; } declare interface UserToolRegistration { readonly name: string; readonly description: string; readonly parameters: Record; } export declare interface ValidateKimiConfigTomlInput { readonly text: string; readonly filePath?: string | undefined; } /** * In-memory video bytes for providers that require an uploaded file * reference instead of an inline data URL. */ declare interface VideoUploadInput { readonly data: Uint8Array; readonly mimeType: string; readonly filename?: string | undefined; } declare interface VideoURLPart { type: 'video_url'; videoUrl: { url: string; id?: string | undefined; }; } export declare interface WarningEvent { readonly type: 'warning'; readonly message: string; readonly code?: string; } declare interface WebSearchProvider { search(query: string, options?: { toolCallId?: string; }): Promise; } declare interface WebSearchResult { title: string; url: string; snippet: string; date?: string; siteName?: string; } declare type WithAgentId = WithExtraPayload; declare type WithExtraPayload = { [K in keyof T]: T[K] extends (payload: infer P) => infer R ? (payload: Prettify

) => R : never; }; declare type WithSessionId = WithExtraPayload; declare type Workspace = z.infer; declare interface WorkspaceAdditionalDirsLoadResult { readonly projectRoot: string; readonly configPath: string; readonly additionalDirs: readonly string[]; readonly warning?: string; } declare interface WorkspaceCreatedEvent { readonly type: 'event.workspace.created'; readonly workspace: Workspace; } declare interface WorkspaceDeletedEvent { readonly type: 'event.workspace.deleted'; readonly workspace_id: string; readonly root: string; } declare const workspaceSchema: z.ZodObject<{ id: z.ZodString; root: z.ZodString; name: z.ZodString; is_git_repo: z.ZodBoolean; branch: z.ZodNullable; created_at: z.ZodPipe>; last_opened_at: z.ZodPipe>; session_count: z.ZodNumber; }, z.core.$strip>; declare interface WorkspaceUpdatedEvent { readonly type: 'event.workspace.updated'; readonly workspace: Workspace; } export { } // Botiverse mirror surface extension — see scripts/repackage-sdk.mjs. // Minimal type declaration; runtime implementation is bundled in dist/index.mjs. declare class LocalKaos implements Kaos { static create(): Promise; readonly name: string; readonly osEnv: Kaos['osEnv']; pathClass(): 'posix' | 'win32'; normpath(path: string): string; gethome(): string; getcwd(): string; chdir(path: string): Promise; withCwd(cwd: string): LocalKaos; withEnv(env: Record): LocalKaos; stat: Kaos['stat']; iterdir: Kaos['iterdir']; glob: Kaos['glob']; readBytes: Kaos['readBytes']; readText: Kaos['readText']; readLines: Kaos['readLines']; writeBytes: Kaos['writeBytes']; writeText: Kaos['writeText']; mkdir: Kaos['mkdir']; exec: Kaos['exec']; execWithEnv: Kaos['execWithEnv']; } export { LocalKaos }; export type { Kaos };