Understanding the Underlying Architecture of Kimi-Code Applications
Kimi-Code is built as a modular TypeScript monorepo that separates UI, SDK, core agent logic, and infrastructure layers, enabling the same agent engine to power both terminal and web interfaces through a dependency-injected service container.
The underlying architecture of Kimi-Code applications follows a strict separation of concerns across the MoonshotAI/kimi-code repository. This design decouples user-facing interfaces from the core AI agent logic, allowing the same Agent class to run headless or behind multiple front-ends. The system uses a local Kap server to host the agent core, while a transcript service provides the single source of truth for all conversation state.
Monorepo Structure and Package Responsibilities
The codebase organizes functionality into apps/ for user interfaces and packages/ for reusable libraries. Each package has a distinct architectural role:
| Layer | Package/Path | Primary Responsibility |
|---|---|---|
| User Interface | apps/kimi-code |
Terminal UI (TUI) invoked via the kimi CLI command. Entry point at apps/kimi-code/src/main.ts. |
| User Interface | apps/kimi-web |
Vue 3 + Vite web client communicating via REST and WebSocket (/api/v1). |
| Client SDK | packages/klient |
TypeScript SDK (createKlient) validating calls with Zod and mirroring server API endpoints. |
| Server Transport | packages/kap-server |
Boots the Kap server exposing REST/WebSocket RPC, entry point at packages/kap-server/src/start.ts. |
| Agent Core | packages/agent-core |
Implements the Agent class, Session management, and DI container with services (packages/agent-core/src/agent/agent.ts). |
| LLM Abstraction | packages/kosong |
Abstracts LLM providers and Model Context Protocol (MCP) handling via ModelCatalogService. |
| Execution Sandbox | packages/kaos |
Provides file-system and process abstractions (packages/kaos/src/exec.ts) for sandboxed commands. |
| Transcript Layer | packages/transcript |
Stores turn-by-turn conversation data with L1/L2/L3 granularity (packages/transcript/src/contract/schema.ts). |
The Five-Layer Execution Stack
User Interface Layer
The CLI application starts at apps/kimi-code/src/main.ts, which installs crash handlers and creates a Kimi harness. This harness validates CLI options and decides whether to launch the interactive TUI or a headless prompt (kimi -p). The web interface (apps/kimi-web/src/main.ts) performs the same initialization but renders through a browser environment.
Client SDK Layer (klient)
The @moonshot-ai/klient package provides the communication bridge. It exposes a createKlient factory that connects to the Kap server and validates all API calls with Zod schemas. The SDK supports global.*, session(id).*, and agent(id).* method namespaces, allowing the CLI to invoke client.session(sessionId).runPrompt() transparently.
Agent Core Engine
The Agent class in packages/agent-core/src/agent/agent.ts is the heart of the system. It owns a dependency injection container wiring services like ModelCatalogService, TranscriptService, and PermissionService. When a session starts, the agent initializes a Session object bound to a specific workspace, loading skills and tools from the DI container. The agent core contains pure business logic with no UI dependencies.
Server Transport Layer (kap-server)
The packages/kap-server/src/start.ts file exports startServer, which initializes the HTTP and WebSocket listeners on port 58627 (configurable). This layer hosts the agent-core DI container and exposes it through REST endpoints (/api/v1/*) and a WebSocket channel for real-time transcript streaming. The server also provides a debug RPC surface at /api/v1/debug/*.
Infrastructure Abstractions
Kosong (packages/kosong/src/model-catalog.ts) handles provider selection and MCP compliance, routing LLM calls to Kimi, OpenAI, or other providers. Kaos (packages/kaos/src/exec.ts) manages sandboxed process execution and temporary file handling. Transcript (packages/transcript/src/contract/schema.ts) maintains the monotonic seq counter for agents, storing prompts, assistant messages, and tool frames in a paginated journal available to both CLI and web clients.
Request Flow: How a Prompt Travels Through the System
When a user runs a command, the request flows through the architecture as follows:
- CLI Entry –
handleMainCommandinapps/kimi-code/src/cli/run-prompt.tsreceives the input and initializes the Klient SDK. - SDK Transmission – The SDK serializes the request and sends an HTTP POST to
/api/v1/sessions/{id}/runPrompton the Kap server. - Agent Execution – The server routes the request to the
Agentinstance inpackages/agent-core, which validates permissions and crafts LLM calls viakosong. - Tool Execution – If the LLM requests file access or command execution, the agent invokes
kaosabstractions (e.g., exec primitives) within the sandbox. - Transcript Writes – Every turn (user prompt, assistant response, tool frame) is appended to the transcript store with an incrementing
seqID. - Streaming Response – The server streams transcript operations back via WebSocket (
/api/v1/ws), which the CLI TUI or web client renders as a live message log.
Practical Code Examples
Starting a Headless Prompt from CLI
Run a single prompt and exit without entering interactive mode:
kimi -p "Explain the architecture of this repository"
This invokes runPrompt in apps/kimi-code/src/cli/run-prompt.ts, which uses the Klient SDK to send a global.runPrompt RPC.
Using the Client SDK Programmatically
import { createKlient } from '@moonshot-ai/klient';
import { resolveKimiHome } from '@moonshot-ai/kimi-code-sdk';
// Initialize client targeting local Kap server
const client = createKlient({
baseUrl: `http://${process.env.KIMI_SERVER_URL ?? '127.0.0.1:58627'}`,
home: resolveKimiHome(),
});
// Create session and execute prompt
const session = await client.session.create({ name: 'demo' });
const result = await client.session(session.id).runPrompt({
prompt: 'Summarize the Kimi-Code architecture',
});
console.log(result.output);
Implementation reference: packages/klient/src/client.ts.
Bootstrapping the Kap Server Manually
import { startServer } from '@moonshot-ai/kap-server';
async function main() {
await startServer({
port: 58627,
// Inject agent-core container
injector: () => import('@moonshot-ai/agent-core').then(m => m.createInjector()),
});
}
main();
See packages/kap-server/src/start.ts for the server bootstrap logic.
Key Source Files Reference
| Component | Source Location | Function/Class |
|---|---|---|
| CLI Entry | apps/kimi-code/src/main.ts |
main() harness initialization |
| Prompt Runner | apps/kimi-code/src/cli/run-prompt.ts |
runPrompt(), handleMainCommand() |
| Agent Implementation | packages/agent-core/src/agent/agent.ts |
Agent class, session binding |
| DI Container | packages/agent-core/src/services/*.ts |
ModelCatalogService, TranscriptService |
| Server Bootstrap | packages/kap-server/src/start.ts |
startServer(), createServer() |
| Transcript Schema | packages/transcript/src/contract/schema.ts |
L1/L2/L3 storage interfaces |
| Model Catalog | packages/kosong/src/model-catalog.ts |
Provider abstraction, MCP handling |
| Execution Sandbox | packages/kaos/src/exec.ts |
Sandboxed execution primitives |
| Client SDK | packages/klient/src/client.ts |
createKlient(), Zod validation |
Summary
- Kimi-Code uses a TypeScript monorepo separating UI (
apps/), SDK (packages/klient), core logic (packages/agent-core), and infrastructure (packages/kap-server,kosong,kaos). - The Agent Core operates through a dependency injection container in
packages/agent-core/src/agent/agent.ts, managing sessions, permissions, and tool execution. - The Kap Server (
packages/kap-server/src/start.ts) hosts the agent core and exposes REST/WebSocket endpoints for both CLI and web clients. - The Transcript Service provides the single source of truth for conversation state, enabling seamless handoff between headless mode, TUI, and web interfaces.
- All LLM interactions flow through the
kosongabstraction layer, supporting Model Context Protocol and multiple providers.
Frequently Asked Questions
What is the role of the Kap server in Kimi-Code?
The Kap server (packages/kap-server) acts as the transport and hosting layer for the agent core. It boots an HTTP/WebSocket server that exposes the agent's capabilities via REST API (/api/v1) and streams real-time transcript updates to connected clients. Both the CLI and web UI connect to this local server to execute prompts and receive responses.
How does the Agent Core handle dependency injection?
The Agent Core in packages/agent-core uses a DI container pattern to wire services at runtime. Key services like ModelCatalogService, TranscriptService, and PermissionService are registered in the container and injected into the Agent class during instantiation (packages/agent-core/src/agent/agent.ts). This allows the same agent logic to operate with different infrastructure implementations for testing or customization.
What is the difference between the Klient SDK and the Agent Core?
The Klient SDK (packages/klient) is a client-side TypeScript library that makes HTTP calls to the Kap server, validating requests with Zod schemas. The Agent Core (packages/agent-core) is the server-side engine that actually processes prompts, manages state, and executes tools. The SDK is what UI applications use to talk to the agent; the core is where the AI logic lives.
How does Kimi-Code support both CLI and web interfaces simultaneously?
Both interfaces connect to the same Kap server instance and consume the same transcript service. The CLI (apps/kimi-code) uses the Klient SDK to send commands and render a terminal UI, while the web app (apps/kimi-web) uses the same SDK methods over HTTP/WebSocket to render a Vue interface. Since the agent core and transcript layer are UI-agnostic, both front-ends see identical conversation state and agent capabilities.
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 →