Session State Management and Persistence in Kimi Code: A Technical Deep Dive

Kimi Code persists session runtime data—including workspace catalogs, session indices, and per-session configuration—to atomic JSON files in ~/.kimi-code, enabling seamless session resumption across CLI, TUI, and web clients after restarts or network disconnections.

The MoonshotAI/kimi-code repository implements a robust crash-tolerant persistence layer that maintains the continuity of AI-assisted coding sessions. This system ensures that transcript cursors, active models, thinking levels, and workspace configurations survive process restarts and client reconnections through a carefully designed storage contract.

Where Session State Is Stored

The persistence contract lives in the user's home directory under ~/.kimi-code. According to the Kimi Code source code, this directory contains three primary JSON files that form the backbone of session recovery:

  • workspaces.json: The workspace catalog listing known workspaces (UI hint only, can be reconstructed)
  • session-index.json: Maps session IDs to their on-disk state file locations
  • session-state.json: Contains mutable runtime data including transcript cursors and model settings

Core Persistence Components

Workspace Registry Implementation

The workspace catalog implementation resides in packages/agent-core/src/session/store/workspace-registry-file.ts. This file maintains workspaces.json, which serves as a hint for the UI's workspace picker and recent-workspace list.

The function touchWorkspaceRegistry() (lines 12-33) registers the current working directory in the catalog:

// Conceptual implementation based on workspace-registry-file.ts
async function touchWorkspaceRegistry(workspacePath: string): Promise<void> {
  // Best-effort operation that ignores failures
  const registry = await readWorkspaceRegistryFile();
  registry.workspaces[workspacePath] = { lastAccessed: Date.now() };
  await writeWorkspaceRegistryFile(registry);
}

This operation is best-effort—failures are silently ignored because the file is not part of the logical session state and can be regenerated from the session index.

Session Index Management

The session index implementation in packages/agent-core/src/session/index.ts manages session-index.json. This file holds a map of session IDs to the on-disk location of each session's state file. The index updates atomically whenever sessions are created or destroyed, providing the canonical source of truth for session discovery.

Per-Session State Storage

The mutable session data—including the transcript cursor, active model, thinking level, and user-adjusted flags—is stored in session-state.json. The TypeScript definitions in apps/kimi-web/src/api/types.ts describe the JSON shape, while packages/kap-server/src/transport/ws/v1/sessionEventBroadcaster.ts handles the writes.

When the SessionStateService detects changes such as model switches, thinking level toggles, or new transcript turns, it refreshes the file atomically.

Atomic Write Operations for Crash Safety

To prevent corruption from crashes or concurrent writes, Kimi Code implements atomic file operations. In packages/agent-core/src/session/store/workspace-registry-file.ts (lines 100-109), the writeWorkspaceRegistryFile helper ensures durability:

// Atomic write pattern from workspace-registry-file.ts
async function writeWorkspaceRegistryFile(data: WorkspaceRegistry): Promise<void> {
  const tempPath = `${configPath}.tmp`;
  await fs.writeFile(tempPath, JSON.stringify(data, null, 2));
  await fs.rename(tempPath, configPath); // Atomic operation
}

This pattern—writing to a temporary *.tmp file before renaming it to the target filename—guarantees that a crash never leaves a partially written JSON file on disk.

Session Lifecycle and Recovery Flow

Creating a New Session

When a new session starts, the core engine executes the following persistence sequence:

  1. Generates a UUID for the session
  2. Writes an entry into session-index.json mapping the ID to the storage location
  3. Creates an empty session-state.json with default model settings, thinking level, and an empty transcript cursor

Updating Runtime State

Any change impacting observable behavior triggers an atomic update. The SessionStateService monitors:

  • Model switches between AI providers
  • Thinking level adjustments (on/off toggles)
  • New transcript turns

These events initiate immediate atomic writes to session-state.json via the persistence layer.

Client Reconnection and State Rehydration

When a client reconnects via WebSocket, the server initiates a recovery flow defined in packages/protocol/src/ws-control.ts (line 599) and implemented in packages/kap-server/src/protocol/ws-control.ts (line 691).

The server transmits a "reset" control frame containing:

// Conceptual control frame structure
interface ResetControlFrame {
  type: 'reset';
  as_of_seq: number;
  session_state: SessionState;
}

Upon receiving this frame, the client discards its in-memory state and rehydrates from the persisted snapshot. This guarantees the UI reflects the exact engine state present before the disconnection, regardless of how long the client was offline.

Summary

  • Storage Location: Kimi Code stores all session data in ~/.kimi-code using three JSON files: workspaces.json, session-index.json, and session-state.json
  • Atomic Writes: The writeWorkspaceRegistryFile function (lines 100-109) uses a temp-file-and-rename pattern to prevent corruption during crashes
  • Session Index: packages/agent-core/src/session/index.ts maintains the canonical mapping between session IDs and their physical storage locations
  • State Rehydration: On reconnect, clients receive a reset control frame (defined in packages/protocol/src/ws-control.ts line 599) that forces rehydration from disk, ensuring consistency
  • Best-Effort Caching: The workspace registry operates as a UI convenience; session recovery depends on the immutable session index and atomic state files

Frequently Asked Questions

Where does Kimi Code store session data?

Kimi Code stores session data in the ~/.kimi-code directory within the user's home folder. This location contains workspaces.json for workspace hints, session-index.json mapping session IDs to storage paths, and individual session-state.json files containing the runtime configuration for each active session.

How does Kimi Code prevent data corruption if the process crashes?

The system uses atomic file writes implemented in packages/agent-core/src/session/store/workspace-registry-file.ts (lines 100-109). The writeWorkspaceRegistryFile helper writes data to a temporary *.tmp file first, then performs an atomic rename operation to move it to the target filename. This ensures that a crash or power failure never leaves a partially written JSON file on disk.

What happens when a client reconnects after a network disconnection?

Upon WebSocket reconnection, the server sends a reset control frame defined in packages/protocol/src/ws-control.ts (line 599) and implemented in packages/kap-server/src/protocol/ws-control.ts (line 691). This frame includes the as_of_seq watermark and the current session-state.json contents. The client immediately discards its local memory state and rebuilds its UI from this persisted snapshot, guaranteeing synchronization with the server's authoritative state.

Is the workspace registry file essential for session recovery?

No. According to the Kimi Code source code, workspaces.json serves only as a UI hint for the workspace picker and recent-workspace list. It is maintained by touchWorkspaceRegistry() as a best-effort operation where failures are ignored. The session index in session-index.json (managed by packages/agent-core/src/session/index.ts) provides the canonical mapping required for session recovery, making the workspace catalog reconstructable if deleted.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →