Kimi-CLI Project Structure: A Complete Guide to the MoonshotAI Repository Architecture
The kimi-cli repository is a monorepo organized into four main areas: src/kimi_cli/ (core CLI and runtime), packages/ (kosong LLM abstraction and kaos OS utilities), web/ (FastAPI server and React UI), and comprehensive test suites in tests/ and tests_e2e/.
Understanding the kimi-cli project structure is essential for developers looking to extend the MoonshotAI/kimi-cli codebase or integrate its components programmatically. This Python-based CLI agent follows a clean, layered architecture that separates concerns between command-line interfaces, runtime engines, web UIs, and external package dependencies. The repository layout supports both standalone CLI usage and embedded library consumption through its modular design.
High-Level Architecture Overview
The kimi-cli project structure follows a monorepo pattern with three top-level concerns:
src/kimi_cli/– Core CLI implementation, runtime engine, agents, tools, and configurationpackages/– Independent Python packages including kosong (LLM abstraction) and kaos (OS-interaction library)web/– FastAPI-based web server and React frontend for the "wire" UI mode
Additional directories include tests/ and tests_e2e/ for unit and integration testing, klips/ for design proposals, and scripts/ for build and release tooling.
Core Implementation: src/kimi_cli/
The src/kimi_cli/ directory contains the primary implementation, organized into sub-packages with distinct responsibilities.
Entry Points and CLI Layer
The Typer-based command-line interface lives in src/kimi_cli/cli/__init__.py. This module parses flags, loads agent specifications, and hands control to the main application.
The central orchestrator is the KimiCLI class in src/kimi_cli/app.py, which coordinates the entire application lifecycle:
from kimi_cli.app import KimiCLI
from kimi_cli.session import Session
from kimi_cli.config import load_config
async def main():
config = load_config() # Loads ~/.kimi/config.toml
session = await Session.create(work_dir="my-workdir")
cli = await KimiCLI.create(session, config=config, ui_mode="none")
await cli.run()
Runtime Engine: The Soul Package
The src/kimi_cli/soul/ directory houses the asynchronous runtime engine that drives agent conversations:
kimisoul.py– Contains the main event loop (KimiSoul.run()) handling user input, slash commands, and context compactioncontext.py– Manages conversation history and checkpointingtoolset.py– Handles dynamic loading and execution of built-in toolsslash.py– Dispatches slash-command interactions
The runtime flow proceeds from app.py through soul/agent.py (which builds the Runtime), then into KimiSoul for the main asynchronous loop.
Agent Specifications and Tools
Built-in agent definitions reside in src/kimi_cli/agents/ as YAML specifications. The tools/ directory contains implementations for file manipulation, web fetching, and user prompts.
For example, invoking the file write tool directly:
from kimi_cli.tools.file.write import WriteFileTool
tool = WriteFileTool()
await tool.call(path="hello.txt", content="Hello, Kimi!\n")
Supporting Infrastructure
Key supporting modules include:
session.py– Persistent session model managing workspace directories and sub-agent storageconfig.py– Loads user-wide (~/.kimi/config.toml) and session-wide TOML configurationllm.py– Wrapper around the kosong library selecting LLM providers (OpenAI, Anthropic, etc.)plugin/– Plugin manager for custom tools and sub-agentshooks/– Lifecycle event system for startup and shutdown hookstelemetry/– Crash reporting and usage analytics
Auxiliary Packages: packages/
The packages/ directory contains independent Python libraries that the CLI depends on.
kosong: LLM Abstraction Layer
packages/kosong/ provides a lightweight abstraction normalizing chat providers, message schemas, and tool orchestration. This layer allows kimi-cli to communicate with various LLM providers through a unified interface.
kaos: OS Interaction Library
packages/kaos/ supplies OS-interaction helpers for SSH, local command execution, and file utilities. Agents use this library to run commands locally or on remote hosts transparently.
Both packages maintain their own test suites under packages/<name>/tests/.
Web Interface: web/
The FastAPI-based web server enables the "wire" UI mode:
web/app.py– HTTP and WebSocket endpoints for session managementweb/src/– Minimal React frontend for streaming wire messagesweb/runner/– Subprocess manager spawning separateKimiCLIinstances per sessionweb/api/– CRUD endpoints for sessions, configuration, and authentication
Start the web server with:
kimi server --mode wire --port 8000
Then navigate to http://localhost:8000 to access the React interface connecting via WebSocket.
Testing Infrastructure
The repository maintains comprehensive test coverage across multiple directories:
tests/– Core unit tests usingpytestandpytest-asynciofor CLI, tools, and runtimetests_e2e/– End-to-end integration tests exercising the full wire protocol, web server, and multi-session behaviortests_ai/– Documentation-style tests verifying markdown examples and encoding handlingpackages/**/tests/– Dedicated suites for kosong and kaos packages
Documentation and Build Tools
Project-level documentation and tooling include:
klips/– KIMI Improvement Proposals (design rationales and release workflows)scripts/– Build helpers (build_web.py,build_vis.py), version checks, and telemetry utilitiespyproject.toml– Poetry/UV build configuration and dependency metadataMakefile– Convenience shortcuts for testing, building, and formatting
Runtime Flow and Code Examples
The kimicl execution flow demonstrates the architecture in action:
- CLI (
cli/__init__.py) parses arguments and callsKimiCLI.create() - App Layer (
app.py) loads configuration, selects LLM provider, and builds Runtime - Runtime (
soul/agent.py) creates sub-agent store and registers tools - Soul (
soul/kimisoul.py) enters the async loop handling messages and tool calls
Extend the CLI with custom tools by subclassing BaseTool:
from kimi_cli.tools import BaseTool
class MyTool(BaseTool):
name = "my_tool"
async def call(self, *, message: str) -> str:
return f"Echo: {message}"
Then reference it in an agent YAML specification:
tools:
- import_path: path.to.my_tool.MyTool
Summary
- The kimi-cli project structure separates concerns across
src/kimi_cli/(core),packages/(libraries), andweb/(UI). - Entry points flow from
cli/__init__.pythroughapp.pyto thesoul/runtime engine. - Extensibility is supported via YAML agent specs, the plugin manager in
plugin/manager.py, and dynamic tool loading insoul/toolset.py. - Web mode uses FastAPI in
web/app.pywith a React frontend communicating over WebSockets. - Testing spans unit tests (
tests/), end-to-end integration (tests_e2e/), and package-specific suites.
Frequently Asked Questions
What is the purpose of the kosong package in kimi-cli?
The kosong package in packages/kosong/ serves as a lightweight LLM-abstraction layer that normalizes different chat providers (OpenAI, Anthropic, etc.) into a consistent interface. According to the MoonshotAI/kimi-cli source code, this allows the runtime to switch between providers without changing the core conversation logic.
How does the runtime engine handle agent conversations?
The runtime engine in src/kimi_cli/soul/kimisoul.py manages an asynchronous event loop that processes user input, executes slash commands via slash.py, invokes tools through toolset.py, and maintains conversation history using context.py. This architecture enables persistent, multi-turn conversations with checkpointing support.
Where are built-in agent specifications stored in the repository?
Built-in agent specifications are stored as YAML files in src/kimi_cli/agents/. These files define default toolsets, system prompts, and agent behaviors that the KimiCLI class loads during initialization via the runtime builder in soul/agent.py.
How can I extend kimi-cli with custom functionality?
You can extend functionality through the plugin system in src/kimi_cli/plugin/manager.py by creating custom tools that inherit from BaseTool and referencing them in agent YAML specifications. Alternatively, add hooks in src/kimi_cli/hooks/ for lifecycle events, or contribute new built-in tools to the src/kimi_cli/tools/ directory.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →