# How the Packages Directory Is Structured in the Kimi Code Repository

> Explore the Kimi Code repository packages directory structure. Learn how TypeScript npm packages are organized for agent engines, protocols, execution, and LLM abstractions.

- Repository: [Moonshot AI/kimi-code](https://github.com/MoonshotAI/kimi-code)
- Tags: internals
- Published: 2026-07-29

---

**The `packages` directory organizes the Kimi Code monorepo into self-contained TypeScript npm packages covering the agent engine, protocol definitions, execution environments, and LLM abstractions, with each folder following a conventional layout containing `src/`, `test/`, and isolated build configuration.**

The `packages` directory serves as the core library layer for the [MoonshotAI/kimi-code](https://github.com/MoonshotAI/kimi-code) repository, implementing a modular monorepo architecture where each sub-folder represents an independently versioned npm package. This structure isolates concerns between the agent runtime, server infrastructure, and provider integrations while maintaining strict contracts through shared protocol definitions defined in Zod schemas.

## Core Packages and Responsibilities

The repository contains specialized packages spanning from low-level parsing to high-level agent orchestration:

### Agent Engine (`agent-core` and `agent-core-v2`)

The **`agent-core`** package contains the fundamental agent runtime, including dependency injection (DI), services, plugins, and error handling. According to the source code in [`packages/agent-core/src/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/index.ts), this package exposes its public API through central re-export statements, allowing downstream code to import via the scoped name `@moonshot-ai/agent-core`.

**`agent-core-v2`** provides an updated engine implementation with stricter contracts and refined APIs. Both versions maintain the same entry point pattern, enabling the server layer to import the runtime while benefiting from version-specific improvements to type safety and service boundaries.

### Server Layer (`kap-server`)

**`kap-server`** implements the HTTP and WebSocket server that exposes the engine via the public API. In [`packages/kap-server/src/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kap-server/src/index.ts), the server imports the `Agent` class from `@moonshot-ai/agent-core` and wires it to HTTP routes, WebSocket streams, and middleware. The entry point [`packages/kap-server/src/start.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kap-server/src/start.ts) provides the `startServer` function for bootstrapping the server instance on configurable ports.

### Protocol and Communication

**`protocol`** defines **Zod-validated** wire contracts for REST, WebSocket, and internal messages. The server uses these schemas to validate incoming requests defined in [`packages/protocol/src/rest-task.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/protocol/src/rest-task.ts) and to shape outgoing events in [`packages/protocol/src/envelope.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/protocol/src/envelope.ts). The file [`packages/protocol/src/ws-control.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/protocol/src/ws-control.ts) contains the core WebSocket control message definitions that govern real-time communication.

**`transcript`** serves as the single source of truth for conversation history, supporting paged REST retrieval and real-time WebSocket streaming. The store implementation in [`packages/transcript/src/store.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/transcript/src/store.ts) handles op-batch sequencing and paging logic used by the server in [`packages/kap-server/src/routes/transcript.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kap-server/src/routes/transcript.ts) and by UI clients.

**`acp-adapter`** translates external "Agent-Control-Protocol" (ACP) calls into engine actions, allowing third-party tools to drive agents through the adapter pattern implemented in [`packages/acp-adapter/src/adapter.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/acp-adapter/src/adapter.ts).

### Execution and LLM Abstraction

**`kaos`** provides the execution environment abstraction, handling filesystem operations, process management, and SSH interactions. This package enables agents to run commands safely through the sandbox implementation found in [`packages/kaos/src/execution.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kaos/src/execution.ts).

**`kosong`** offers a **provider-agnostic** LLM abstraction layer with a model catalog that resolves model names and merges configuration layers. The [`packages/kosong/src/modelCatalog.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kosong/src/modelCatalog.ts) file implements the `ModelCatalog` class, which performs inference via provider-specific adapters while normalizing the interface across different LLM providers.

### Utilities and Language Tools

**`telemetry`** supplies shared client-side telemetry utilities consumed by both the engine and server to emit structured logs and metrics. The logger implementation in [`packages/telemetry/src/logger.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/telemetry/src/logger.ts) provides the infrastructure used across the repository for observability.

**`tree-sitter-bash`** contains a pure-TypeScript Bash parser built on the Tree-Sitter grammar. The parser in [`packages/tree-sitter-bash/src/parser.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/tree-sitter-bash/src/parser.ts) supports the shell-tool functionality and permission-matching logic without native dependencies.

**`migration-legacy`** maintains compatibility layers for older data formats, containing scripts and test fixtures in `packages/migration-legacy/test/fixtures/with-tool-calls/wire.jsonl` that migrate legacy wire formats into current schemas.

## Standard Package Layout

Every package in the `packages` directory follows a conventional TypeScript layout that enables isolated builds and clear API boundaries:

- **`src/`** – TypeScript source files (`*.ts`, `*.tsx`) exposing the public API via `export *` statements in [`src/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/index.ts)
- **`test/`** – Jest/Vitest test suites that validate package behavior and prevent regressions
- **[`tsconfig.json`](https://github.com/MoonshotAI/kimi-code/blob/main/tsconfig.json)** – TypeScript compiler configuration tuned for the specific package
- **[`vite.config.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/vite.config.ts)** or **[`vitest.config.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/vitest.config.ts)** – Build and test tool configuration for fast compilation
- **[`README.md`](https://github.com/MoonshotAI/kimi-code/blob/main/README.md)** – Package-level documentation explaining usage and design decisions

All packages are declared in both the [`pnpm-workspace.yaml`](https://github.com/MoonshotAI/kimi-code/blob/main/pnpm-workspace.yaml) workspace configuration and the Nix flake (`flake.nix`), ensuring that Node-centric and Nix-centric build pipelines see identical package sets.

## Package Interactions and Data Flow

The packages interact through well-defined dependency boundaries that enforce separation of concerns:

1. **Engine to Server** – `kap-server` imports the engine from `@moonshot-ai/agent-core` and exposes it through HTTP/WebSocket endpoints
2. **Protocol Validation** – Incoming requests pass through Zod schemas from `@moonshot-ai/protocol` before reaching the engine
3. **Telemetry** – Shared logging utilities from `@moonshot-ai/telemetry` propagate structured events across all layers
4. **Transcript** – Conversation state flows through `@moonshot-ai/transcript`, accessed by both the server and UI clients
5. **Execution** – The `kaos` package provides the sandbox where agent operations execute safely

## Working with Specific Packages

### Creating an Agent Instance

To instantiate an agent using the core engine:

```typescript
import { Agent } from '@moonshot-ai/agent-core'
import { InMemorySession } from '@moonshot-ai/agent-core'

const session = new InMemorySession({ sessionId: 'demo-1' })
const agent = new Agent({ session, agentId: 'example-agent' })

const result = await agent.runPrompt('Explain the difference between TCP and UDP.')
console.log(result.text)

```

This example references the implementation in [`packages/agent-core/src/agent.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/agent.ts).

### Starting the HTTP Server

To bootstrap the server that exposes the engine:

```typescript
import { startServer } from '@moonshot-ai/kap-server'

async function main() {
  const server = await startServer({
    port: 58627,
    debugEndpoints: true,
  })
  console.log(`Kimi server listening on http://localhost:${server.port}`)
}
main()

```

The `startServer` function is implemented in [`packages/kap-server/src/start.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kap-server/src/start.ts).

### Accessing Conversation History

To interact with the transcript service:

```typescript
import { TranscriptService } from '@moonshot-ai/transcript'

const transcript = TranscriptService.forSessionLive('session-42')
await transcript.appendTurn({
  role: 'assistant',
  content: 'Hello, I am Kimi!'
})

const recent = await transcript.getTurns({ limit: 2 })
console.log(recent)

```

The underlying store logic lives in [`packages/transcript/src/store.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/transcript/src/store.ts).

### Using the LLM Provider Layer

To query the model catalog for inference:

```typescript
import { ModelCatalog } from '@moonshot-ai/kosong'

const catalog = new ModelCatalog()
const model = await catalog.get('openai:gpt-4o')
const answer = await model.generate('Summarize the latest AI news.')
console.log(answer)

```

This utilizes the catalog implementation in [`packages/kosong/src/modelCatalog.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kosong/src/modelCatalog.ts).

## Summary

- The `packages` directory implements a **TypeScript monorepo** where each folder is an independent npm package with isolated build configuration and a single entry point at [`src/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/index.ts)
- **Core packages** include `agent-core` (runtime), `kap-server` (HTTP/WebSocket layer), `protocol` (Zod schemas), and `transcript` (conversation state management)
- **Execution packages** (`kaos`, `kosong`) provide sandboxed command execution and LLM provider abstraction
- All packages follow a **standard layout** with `src/`, `test/`, and [`tsconfig.json`](https://github.com/MoonshotAI/kimi-code/blob/main/tsconfig.json), exposing public APIs through centralized index files
- Packages are registered in both **pnpm workspace** and **Nix flake** configurations for reproducible builds across toolchains

## Frequently Asked Questions

### What distinguishes agent-core from agent-core-v2?

**`agent-core-v2`** represents an updated version of the engine with stricter contracts and refined APIs compared to the original **`agent-core`**. While both packages export compatible symbols through their respective [`src/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/index.ts) files, version 2 implements more rigorous type safety and separation of concerns, allowing the server layer to migrate gradually while maintaining the same import pattern via scoped package names.

### How does the kap-server package communicate with the agent engine?

The **`kap-server`** package imports the `Agent` class directly from `@moonshot-ai/agent-core` in its entry point at [`packages/kap-server/src/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kap-server/src/index.ts). It wires the engine to Fastify HTTP routes and WebSocket streams, using the **`protocol`** package to validate incoming requests before passing them to the agent runtime. This creates a clean separation where the server handles transport concerns while the engine manages execution logic.

### What is the purpose of the kosong package in the architecture?

**`kosong`** serves as the **provider-agnostic LLM abstraction layer**, decoupling the agent engine from specific model implementations. It manages model catalog resolution, configuration merging, and token handling through the `ModelCatalog` class in [`packages/kosong/src/modelCatalog.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kosong/src/modelCatalog.ts). This allows the agent to work with multiple LLM providers through a unified interface without hard-coding provider-specific logic into the core engine.

### How are packages built and versioned in this monorepo?

Each package maintains **isolated TypeScript configuration** via [`tsconfig.json`](https://github.com/MoonshotAI/kimi-code/blob/main/tsconfig.json) and builds independently using Vite or Vitest as configured in [`vite.config.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/vite.config.ts). The repository uses **pnpm workspaces** declared in [`pnpm-workspace.yaml`](https://github.com/MoonshotAI/kimi-code/blob/main/pnpm-workspace.yaml) to manage dependencies and linking between packages. Additionally, packages are declared in `flake.nix` to support Nix-based builds, ensuring that both Node.js and Nix build pipelines recognize the same package boundaries and versions.