# How to Manage Chat History in Kimi-CLI: Context, Sessions, and Persistence

> Learn to manage chat history in Kimi-CLI. Explore context, sessions, and persistence for seamless conversation management and automatic summarization.

- Repository: [Moonshot AI/kimi-cli](https://github.com/MoonshotAI/kimi-cli)
- Tags: how-to-guide
- Published: 2026-07-27

---

**Kimi-CLI maintains conversation history through a `Context` object that stores messages in memory, persists them to `~/.kimi/sessions/<session-id>/`, and automatically compresses older turns into summary checkpoints when exceeding configurable token limits.**

Managing chat history effectively is critical when building terminal-based AI workflows with the MoonshotAI/kimi-cli repository. The codebase implements a sophisticated session management system that handles everything from real-time message appending to long-term persistence and automatic compaction.

## Core Architecture of History Management

The chat history system in kimi-cli relies on four primary components working in tandem:

- **`Context`** ([`src/kimi_cli/soul/context.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/context.py)): The in-memory representation of the conversation, holding a list of `Message` objects, timestamps, and checkpoint metadata.
- **`KimiSoul`** ([`src/kimi_cli/soul/kimisoul.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/kimisoul.py)): The core runtime loop that orchestrates reading from and writing to the `Context`, triggering compaction when history grows large.
- **`Session`** ([`src/kimi_cli/soul/agent.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/agent.py)): Handles persistence logic, saving the context to disk between runs and restoring it during session resumption.
- **`Compaction`** ([`src/kimi_cli/soul/compaction.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/compaction.py)): Implements automatic summarization that compresses older messages into checkpoints to maintain performance.

## How the Context Object Stores Conversation History

In [`src/kimi_cli/soul/context.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/context.py), the `Context` class serves as the central data structure for conversation state. Each interaction appends a `Message` entry containing the role, content, and metadata.

When a user submits input, `KimiSoul.run()` invokes `context.add_user_message(...)` to append the new turn. The context maintains two critical properties:

- **`context.messages`**: A complete list of all conversation turns available for tool access and LLM prompting.
- **`context.checkpoints`**: Summarized versions of older conversation segments created during compaction.

## Working with History Programmatically

Tools and custom skills can access the full conversation history through the runtime agent's context object.

```python

# Accessing the full conversation history from a running KimiCLI instance

from kimi_cli.app import KimiCLI

# Assume you already have a KimiCLI instance `cli`

ctx = cli.runtime.agent.context   # the Context object

for msg in ctx.messages:
    print(f"{msg.role}: {msg.content}")

```

You can also inject system messages or modify context state directly:

```python

# Manually adding a system message (useful for custom skills)

ctx.add_system_message("You are now in troubleshooting mode.")

# Retrieving the latest checkpoint summary (after compaction)

if ctx.checkpoints:
    latest = ctx.checkpoints[-1]
    print("Checkpoint summary:", latest.summary)

```

## Persistence and Session Management

Session continuity relies on the `Session` class in [`src/kimi_cli/soul/agent.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/agent.py). At the end of each turn, `Session.save_context()` serializes the `Context` to JSON format within the session directory located at `~/.kimi/sessions/<session-id>/`.

This persistence mechanism enables the `kimi resume` functionality, allowing users to restore exact conversation states across terminal sessions. The `SubagentStore` works alongside `Session` to manage sub-agent specific context branches when using multi-agent workflows.

## Automatic Compaction and History Summarization

To prevent token overflow during long conversations, kimi-cli implements automatic compaction via [`src/kimi_cli/soul/compaction.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/compaction.py). When `context.messages` exceeds the `MAX_MESSAGES` threshold (default approximately 200 messages), the system:

1. Selects older messages for compression
2. Generates a summary checkpoint preserving semantic meaning
3. Replaces the original messages with the compact representation

This checkpointing system maintains context window efficiency while preserving conversation continuity. Access these summaries through `context.checkpoints`, which stores the compressed history segments.

## Exporting and Importing Chat History

For backup or analysis purposes, kimi-cli supports history export through command-line flags defined in [`src/kimi_cli/cli/__init__.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/cli/__init__.py):

```bash

# Export the current session's history to JSON

kimi --export-history > conversation.json

```

Programmatically restore history into a new session using the `Context` deserialization method:

```python
from kimi_cli.soul.context import Context
import json
import pathlib

history_path = pathlib.Path.home() / ".kimi" / "sessions" / "my-session" / "context.json"
data = json.loads(history_path.read_text())
ctx = Context.from_dict(data)   # reconstructs the in-memory Context

```

## Summary

- **Context Object**: Stored in [`src/kimi_cli/soul/context.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/context.py), maintains `messages` and `checkpoints` lists for active conversations.
- **Runtime Integration**: `KimiSoul` in [`src/kimi_cli/soul/kimisoul.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/kimisoul.py) manages the conversation loop and history updates via `context.add_user_message()`.
- **Persistence**: The `Session` class saves context to `~/.kimi/sessions/<session-id>/` after each turn, enabling session resumption.
- **Compaction**: Automatic summarization occurs when exceeding ~200 messages, managed by [`src/kimi_cli/soul/compaction.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/compaction.py).
- **Programmatic Access**: Retrieve history via `cli.runtime.agent.context.messages` or export via the `--export-history` CLI flag.

## Frequently Asked Questions

### Where does kimi-cli store conversation history on disk?

Kimi-cli persists chat history in JSON format within the `~/.kimi/sessions/<session-id>/` directory. The `Session.save_context()` method in [`src/kimi_cli/soul/agent.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/agent.py) handles serialization after each conversation turn, ensuring that `kimi resume` can reconstruct the exact state including all messages and checkpoints.

### How does kimi-cli handle long conversations that exceed token limits?

The repository implements automatic compaction through [`src/kimi_cli/soul/compaction.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/compaction.py). When the message count exceeds the `MAX_MESSAGES` limit (default approximately 200), older messages are compressed into summary checkpoints. These checkpoints replace the original content in `context.checkpoints` while preserving semantic context for the LLM, preventing token overflow without losing conversation continuity.

### Can I access or modify the conversation history from within a custom skill?

Yes, custom skills can access the active `Context` object through the runtime agent. Use `cli.runtime.agent.context` to retrieve the context, then access `context.messages` for the full history or `context.add_system_message()` to inject new instructions. You can also check `context.checkpoints` to view compressed history summaries if compaction has occurred.

### How do I export my chat history for external analysis?

Use the `--export-history` flag available in the CLI entry point ([`src/kimi_cli/cli/__init__.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/cli/__init__.py)). Running `kimi --export-history` outputs the current session's context as JSON, which you can redirect to a file. Alternatively, manually read the [`context.json`](https://github.com/MoonshotAI/kimi-cli/blob/main/context.json) file directly from the session directory at `~/.kimi/sessions/<session-id>/`.