# How to Troubleshoot Kimi‑CLI Errors: A Complete Debug Guide

> Troubleshoot kimi-cli errors with our complete debug guide. Enable debug logs, inspect session directories, and run tests to pinpoint issues in the Typer CLI, KimiSoul loop, or wire protocol.

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

---

**Enable `LOG_LEVEL=DEBUG` or `KIMI_WIRE_DEBUG=1` before executing commands, then inspect the session directory at `~/.kimi/sessions/<id>/` and run `make test` to isolate whether failures originate in the Typer CLI, the async `KimiSoul` loop, or the wire protocol.**

Kimi‑CLI is a Python‑based interactive agent from MoonshotAI that coordinates LLM interactions through **Typer** entry points, an **async runtime**, and a **wire‑based UI**. When you need to troubleshoot Kimi‑CLI errors, understanding the data flow from [`src/kimi_cli/cli/__init__.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/cli/__init__.py) through the soul’s event loop is essential for pinpointing configuration bugs, tool crashes, or protocol mismatches.

## Understanding the Kimi‑CLI Architecture

Before debugging, map the error to the correct subsystem. Kimi‑CLI couples several distinct layers:

- **CLI Entry** ([`src/kimi_cli/cli/__init__.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/cli/__init__.py)) – Parses flags, loads `~/.kimi/config.toml`, and selects the model/provider.
- **App Runtime** ([`src/kimi_cli/app.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/app.py)) – Constructs the `KimiCLI` instance, restores session context, and initializes the `KimiSoul` loop.
- **Agent Core** ([`src/kimi_cli/soul/agent.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/agent.py)) – Houses the system prompt, tool registry, and sub‑agent definitions.
- **Main Loop** ([`src/kimi_cli/soul/kimisoul.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/kimisoul.py)) – Receives user input, manages the `Context`, calls the LLM, and emits wire events.
- **Context & Persistence** ([`src/kimi_cli/soul/context.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/context.py)) – Serializes conversation history and checkpoints to [`context.json`](https://github.com/MoonshotAI/kimi-cli/blob/main/context.json).
- **Toolset** ([`src/kimi_cli/soul/toolset.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/toolset.py)) – Dynamically loads built‑in tools and MCP bridges.
- **Wire Protocol** (`src/kimi_cli/wire/`) – Defines `KimiWireMessage` events consumed by the Shell and ACP UIs.

Errors typically surface at the **wire boundary** (UI showing “unknown event”), in **tool execution** (shell or file operations), or during **context restoration** (session resume failures).

## Step‑by‑Step Debugging Workflow

### Enable Verbose Logging

Start every debug session with environment variables that activate **loguru** debug streams:

```bash

# Full debug output showing tool invocations and wire events

LOG_LEVEL=DEBUG kimi chat "your prompt"

```

For structured wire‑protocol inspection, enable the dedicated debug flag:

```bash
KIMI_WIRE_DEBUG=1 kimi chat "your prompt"

```

This pretty‑prints `KimiWireMessage` payloads with timestamps, making it easy to spot malformed events.

### Inspect Session Artifacts

Kimi‑CLI persists state in `~/.kimi/sessions/<session-id>/`. After a failure, examine:

- [`context.json`](https://github.com/MoonshotAI/kimi-cli/blob/main/context.json) – Raw conversation history and token counts. Corruption here causes “resume” errors.
- `wire.log` – Chronological dump of wire messages; useful for post‑mortem analysis of UI glitches.
- `subagents/` – Directory containing persisted sub‑agent state. Truncated files in this folder often explain resume failures.

### Execute the Test Suite

Validate the installation and isolate regressions using the Makefile targets:

```bash
make test      # Unit tests for core logic

make ai-test   # Integration tests with mocked LLM providers

make check     # Ruff linting and Pyright type checking

```

Failing tests in [`tests_e2e/test_wire_errors.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/tests_e2e/test_wire_errors.py) point directly to protocol mismatches, while failures in [`tests_e2e/test_wire_real_llm.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/tests_e2e/test_wire_real_llm.py) indicate provider‑specific issues.

### Trace Tool Execution with pdb

If a specific tool crashes (e.g., file reads or shell execution), insert a breakpoint directly in the tool implementation:

```python

# In src/kimi_cli/tools/file/read_file.py

import pdb; pdb.set_trace()

```

When the async runtime hits the tool, execution pauses, allowing inspection of local variables and the execution context.

## Diagnostic Scripts for Common Scenarios

### Dump Conversation Context

When session state is suspect, inspect [`context.json`](https://github.com/MoonshotAI/kimi-cli/blob/main/context.json) programmatically:

```python

# save as scripts/dump_context.py

from pathlib import Path
import json
import sys

def dump_context(session_id: str):
    ctx_path = Path.home() / ".kimi" / "sessions" / session_id / "context.json"
    if not ctx_path.exists():
        print(f"No session found for {session_id}")
        sys.exit(1)
    print(json.dumps(json.loads(ctx_path.read_text()), indent=2))

if __name__ == "__main__":
    dump_context(sys.argv[1])

```

Run with:

```bash
python scripts/dump_context.py <session-id>

```

### Record Wire Protocol Traffic

Capture all wire events to a dedicated log file for offline analysis:

```python

# scripts/record_wire.py

import os
from pathlib import Path
from loguru import logger

def enable_wire_logging():
    log_path = Path.home() / ".kimi" / "wire_debug.log"
    logger.add(str(log_path), level="DEBUG", filter=lambda r: "wire" in r["message"])
    os.environ["KIMI_WIRE_DEBUG"] = "1"
    print(f"Logging wire events to {log_path}")

if __name__ == "__main__":
    enable_wire_logging()

```

Source the script in your shell to enable tracing for the next command:

```bash
eval $(python scripts/record_wire.py)
kimi chat "test command"

```

### Check Sub‑Agent Persistence

List all persisted sub‑agents to identify corruption or orphaned states:

```python

# scripts/check_subagents.py

from pathlib import Path

def list_subagents():
    base = Path.home() / ".kimi" / "sessions"
    if not base.exists():
        print("No sessions directory found")
        return
    for sess in base.iterdir():
        sub_dir = sess / "subagents"
        if sub_dir.exists():
            for sub in sub_dir.glob("*"):
                print(f"{sess.name}/{sub.name}")

if __name__ == "__main__":
    list_subagents()

```

## Summary

- **Start with logs:** Use `LOG_LEVEL=DEBUG` or `KIMI_WIRE_DEBUG=1` to capture the full event stream.
- **Check persistence:** Inspect `~/.kimi/sessions/<id>/context.json` and the `subagents/` folder for corruption.
- **Test systematically:** Run `make test` and `make ai-test` to distinguish between code bugs and LLM provider issues.
- **Debug tools directly:** Insert `pdb.set_trace()` into tool files under `src/kimi_cli/tools/` to inspect runtime state.
- **Understand the flow:** Trace errors from [`src/kimi_cli/cli/__init__.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/cli/__init__.py) → [`src/kimi_cli/app.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/app.py) → [`src/kimi_cli/soul/kimisoul.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/soul/kimisoul.py) to isolate the failing layer.

## Frequently Asked Questions

### Where does Kimi‑CLI store session data?

Session data resides in `~/.kimi/sessions/<session-id>/`. The [`context.json`](https://github.com/MoonshotAI/kimi-cli/blob/main/context.json) file contains the serialized conversation history, while `subagents/` stores the state of any spawned sub‑agents. If a session fails to resume, delete the specific session folder to force a fresh context.

### How do I fix “unknown wire event” errors in the UI?

This error indicates a mismatch between the **wire protocol** definitions in `src/kimi_cli/wire/` and the UI consumer. Enable `KIMI_WIRE_DEBUG=1` and check `~/.kimi/sessions/<id>/wire.log` for malformed payloads. Compare the logged event structure against the message schemas in the wire directory.

### Why does resuming a session fail with a JSON decode error?

The [`context.json`](https://github.com/MoonshotAI/kimi-cli/blob/main/context.json) or a file in `subagents/` likely contains truncated data due to an abrupt process termination. Use the [`dump_context.py`](https://github.com/MoonshotAI/kimi-cli/blob/main/dump_context.py) script above to validate JSON integrity. If the file is corrupt, remove the specific session directory; Kimi‑CLI will regenerate the context on the next run.

### How can I test Kimi‑CLI without hitting real LLM APIs?

Use the integration test harness with mocked providers:

```bash
make ai-test TEST=tests_e2e/test_wire_real_llm.py

```

This replays recorded wire events against a mock LLM, allowing you to verify UI behavior and tool integrations without external API calls or token costs.