# Core Functionalities of the kimi-code Packages: A Complete Technical Guide

> Explore the core functionalities of kimi-code packages. This guide details its modular TypeScript stack for building AI-driven coding agents, including agent engines, SDKs, and more.

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

---

**The kimi-code monorepo delivers a modular TypeScript stack comprising agent engines, HTTP/WebSocket servers, typed client SDKs, and infrastructure abstractions for building AI-driven coding agents.**

The MoonshotAI/kimi-code repository organizes its functionality into loosely-coupled TypeScript packages, each targeting a specific architectural layer of the Kimi Code platform. These kimi-code packages provide a full-stack solution for creating, deploying, and interacting with autonomous coding agents, from low-level process management to high-level client abstractions.

## Core Architecture Overview

The kimi-code packages follow a layered architecture that separates concerns between the agent runtime, network transport, client consumption, and supporting infrastructure. The stack divides into five primary layers: the **Agent Engine** (core runtime), the **Server Layer** (network API), the **Client SDK** (consumption interface), **Infrastructure Abstractions** (process and LLM management), and **Data & Observability** (persistence, telemetry, and utilities).

## Package-by-Package Breakdown

### Agent Engine Layer

The foundational runtime for autonomous agents resides in two complementary packages:

**`@moonshot-ai/agent-core`** provides the original agent engine implementation. In [`packages/agent-core/src/agent/Agent.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/agent/Agent.ts), the main `Agent` class manages service dependency injection, session lifecycles, and tool call execution according to the transcript contract. This package defines the fundamental abstractions for agent state management and service orchestration.

**`@moonshot-ai/agent-core-v2`** delivers a refactored engine with improved type safety and modularity. The entry point in [`packages/agent-core-v2/src/Agent.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core-v2/src/Agent.ts) exposes a refined API surface while maintaining backward compatibility with the core agent lifecycle hooks. Both packages enable developers to build custom agents with sophisticated service injection patterns.

### Server & API Layer

**`@moonshot-ai/kap-server`** exposes the agent engine over HTTP and WebSocket transports. The server boots from [`packages/kap-server/src/start.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kap-server/src/start.ts), initializing the REST API endpoints and WebSocket handlers that serve sessions, streams, and debugging interfaces. This package aggregates all server-side functionality, including the global search index backed by embedded storage, making it suitable for self-hosted Kimi Code deployments.

### Client SDK Layer

**`@moonshot-ai/klient`** provides a type-safe TypeScript client that mirrors the server's API surface. The factory function `createKlient()` exported from [`packages/klient/src/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/klient/src/index.ts) instantiates clients capable of calling RPC methods with full type safety across global, session, and agent scopes. The client automatically discovers server endpoints via environment configuration.

**`@moonshot-ai/node-sdk`** bundles the client functionality into a public npm SDK optimized for Node.js environments. The entry point in [`packages/node-sdk/src/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/node-sdk/src/index.ts) aggregates utilities from `klient` with additional Node-specific helpers, streamlining integration for CLI tools and automation scripts.

### Infrastructure Abstractions

**`@moonshot-ai/kaos`** implements a portable process and file abstraction layer. The `kaos.spawn()` method defined in [`packages/kaos/src/kaos.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kaos/src/kaos.ts) enables reliable subprocess management across local shells and SSH connections, handling environment variables, working directories, and cross-platform compatibility.

**`@moonshot-ai/kosong`** delivers a provider-agnostic LLM abstraction framework. The `kosong.model()` factory in [`packages/kosong/src/kosong.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kosong/src/kosong.ts) supports model selection from multiple vendors while providing unified interfaces for tokenization, usage tracking, and metadata retrieval. This abstraction allows agents to switch between models without code changes.

### Data & Observability Layer

**`@moonshot-ai/minidb`** furnishes an embedded JSON document store specifically designed for the global search index. Implementation in [`packages/minidb/src/MiniDb.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/minidb/src/MiniDb.ts) provides full-text search capabilities without external database dependencies.

**`@moonshot-ai/telemetry`** handles lightweight client-side event batching and diagnostics. The system defined in [`packages/telemetry/src/telemetry.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/telemetry/src/telemetry.ts) captures usage metrics and error reports for both the UI and SDKs.

**`@moonshot-ai/oauth`** manages authentication flows for Kimi services. The utilities in [`packages/oauth/src/oauth.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/oauth/src/oauth.ts) handle login sequences, token refresh, and secure credential storage.

**`@moonshot-ai/migration-legacy`** provides archival conversion tools. The `migrateLegacyArchive()` function in [`packages/migration-legacy/src/migrate.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/migration-legacy/src/migrate.ts) transforms historic wire-format session archives into the modern transcript format.

**`@moonshot-ai/tree-sitter-bash`** offers a pure-TypeScript Bash parser built on Tree-Sitter grammars. The parser in [`packages/tree-sitter-bash/src/parse.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/tree-sitter-bash/src/parse.ts) enables static analysis of shell scripts for permission matching and syntax highlighting.

## Practical Implementation Examples

### Listing Sessions with the Klient SDK

The following example demonstrates creating a client instance and retrieving active sessions from the global API:

```typescript
import { createKlient } from '@moonshot-ai/klient';

async function listSessions() {
  // The client automatically discovers the server URL via KIMI_SERVER_URL env var
  const client = await createKlient();

  // Global API – fetch list of sessions
  const sessions = await client.global.sessions.list();

  console.log('Active sessions:', sessions);
}

listSessions().catch(console.error);

```

This code utilizes the `createKlient()` factory from [`packages/klient/src/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/klient/src/index.ts) to establish a typed connection to the server infrastructure.

### Spawning Subprocesses with Kaos

For reliable process execution across platforms, use the Kaos abstraction layer:

```typescript
import { kaos } from '@moonshot-ai/kaos';

async function runCommand() {
  const proc = await kaos.spawn('node', ['-e', 'console.log("hello from kaos")'], {
    cwd: process.cwd(),
  });

  const stdout = await proc.output();
  console.log('Process output:', stdout);
}

runCommand().catch(console.error);

```

The `kaos.spawn()` implementation in [`packages/kaos/src/kaos.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kaos/src/kaos.ts) wraps Node.js `child_process` with enhanced error handling and portable environment management.

### Querying LLMs via Kosong

To interact with language models through the provider-agnostic interface:

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

async function askModel() {
  const model = kosong.model('openai:gpt-4o-mini'); // Example provider/model ID
  const response = await model.complete('Explain the observer pattern in 2 sentences.');

  console.log('Model answer:', response.text);
  console.log('Usage:', response.usage); // tokens, timing, finishReason, etc.
}

askModel().catch(console.error);

```

This example leverages the model catalog and request routing defined in [`packages/kosong/src/kosong.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kosong/src/kosong.ts), which normalizes responses across different LLM providers.

### Migrating Legacy Archives

Convert historical session data to the modern transcript format:

```typescript
import { migrateLegacyArchive } from '@moonshot-ai/migration-legacy';

async function migrate() {
  const legacyPath = './legacy/session-archive.jsonl';
  const newPath = './new/transcript.jsonl';

  await migrateLegacyArchive(legacyPath, newPath);
  console.log('Migration complete');
}

migrate().catch(console.error);

```

The `migrateLegacyArchive()` driver in [`packages/migration-legacy/src/migrate.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/migration-legacy/src/migrate.ts) handles parsing old wire records and re-writing them as modern transcript facts without data loss.

## Key Source Files and Implementation Details

Understanding the internal structure of the kimi-code packages requires familiarity with these representative source files:

- **[[`packages/agent-core/src/agent/Agent.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/agent/Agent.ts)](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/agent/Agent.ts)**: Implements the public `Agent` class and lifecycle hooks for service-dependent agent execution.

- **[[`packages/agent-core-v2/src/Agent.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core-v2/src/Agent.ts)](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core-v2/src/Agent.ts)**: Contains the refactored engine entry point with refined TypeScript definitions.

- **[[`packages/kap-server/src/start.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kap-server/src/start.ts)](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kap-server/src/start.ts)**: Boots the HTTP/WebSocket server and wires core services with the transcript API.

- **[[`packages/klient/src/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/klient/src/index.ts)](https://github.com/MoonshotAI/kimi-code/blob/main/packages/klient/src/index.ts)**: Exports the typed client façade including the `createKlient()` factory function.

- **[[`packages/node-sdk/src/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/node-sdk/src/index.ts)](https://github.com/MoonshotAI/kimi-code/blob/main/packages/node-sdk/src/index.ts)**: Public SDK entry point aggregating client utilities for npm distribution.

- **[[`packages/kaos/src/kaos.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kaos/src/kaos.ts)](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kaos/src/kaos.ts)**: High-level process abstraction providing `spawn()` and `exec()` with cross-platform reliability.

- **[[`packages/kosong/src/kosong.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kosong/src/kosong.ts)](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kosong/src/kosong.ts)**: Central model catalog, request routing, and usage tracking for LLM interactions.

- **[[`packages/minidb/src/MiniDb.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/minidb/src/MiniDb.ts)](https://github.com/MoonshotAI/kimi-code/blob/main/packages/minidb/src/MiniDb.ts)**: Embedded JSON document store implementation powering the global search index.

- **[[`packages/telemetry/src/telemetry.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/telemetry/src/telemetry.ts)](https://github.com/MoonshotAI/kimi-code/blob/main/packages/telemetry/src/telemetry.ts)**: Event-batching system for diagnostics and usage metrics collection.

- **[[`packages/oauth/src/oauth.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/oauth/src/oauth.ts)](https://github.com/MoonshotAI/kimi-code/blob/main/packages/oauth/src/oauth.ts)**: OAuth2 flow implementation for Kimi authentication and token management.

- **[[`packages/migration-legacy/src/migrate.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/migration-legacy/src/migrate.ts)](https://github.com/MoonshotAI/kimi-code/blob/main/packages/migration-legacy/src/migrate.ts)**: Archive conversion logic transforming legacy wire formats to modern transcripts.

- **[[`packages/tree-sitter-bash/src/parse.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/tree-sitter-bash/src/parse.ts)](https://github.com/MoonshotAI/kimi-code/blob/main/packages/tree-sitter-bash/src/parse.ts)**: Pure-TypeScript Bash parser for static analysis and syntax operations.

## Summary

- The kimi-code packages comprise a TypeScript monorepo organized into five architectural layers: Agent Engine, Server, Client SDK, Infrastructure, and Data/Observability.
- **`@moonshot-ai/agent-core`** and **`@moonshot-ai/agent-core-v2`** provide the runtime engines for agent lifecycle and service injection.
- **`@moonshot-ai/kap-server`** exposes these capabilities via HTTP/WebSocket protocols for local or remote hosting.
- **`@moonshot-ai/klient`** and **`@moonshot-ai/node-sdk`** offer type-safe client consumption of server APIs.
- **`@moonshot-ai/kaos`** and **`@moonshot-ai/kosong`** abstract process management and LLM interactions respectively.
- Supporting packages include **`@moonshot-ai/minidb`** for embedded search, **`@moonshot-ai/telemetry`** for diagnostics, and **`@moonshot-ai/migration-legacy`** for data portability.

## Frequently Asked Questions

### What is the difference between `@moonshot-ai/agent-core` and `@moonshot-ai/agent-core-v2`?

**`@moonshot-ai/agent-core-v2`** represents a architectural refactor of the original **`@moonshot-ai/agent-core`** package. While both provide agent lifecycle management and service dependency injection, the v2 implementation in [`packages/agent-core-v2/src/Agent.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core-v2/src/Agent.ts) offers improved type safety, better testability through refined module boundaries, and a more modular API surface. Developers building new applications should prefer v2, while legacy integrations may continue using the original core package.

### How does the Klient SDK connect to the Kimi Code server?

The **`@moonshot-ai/klient`** package automatically discovers server endpoints through the `KIMI_SERVER_URL` environment variable. When you invoke `createKlient()` from [`packages/klient/src/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/klient/src/index.ts), the factory configures HTTP and WebSocket transports with full TypeScript typings that mirror the server API surface. This design allows the client to call RPC methods on global, session, and agent scopes with compile-time type safety and runtime environment discovery.

### Can I use the kimi-code packages to integrate Kimi Code capabilities into my own CLI tools?

Yes. The **`@moonshot-ai/node-sdk`** package specifically targets Node.js CLI tools and automation scripts. By importing from [`packages/node-sdk/src/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/node-sdk/src/index.ts), you gain access to bundled client utilities from `klient`, `kaos`, and `kosong` with Node-specific optimizations. This SDK handles authentication, process spawning, and LLM querying through a unified interface, making it straightforward to embed Kimi Code functionality into command-line utilities or custom development workflows.

### What purpose does the `@moonshot-ai/kaos` package serve in the architecture?

**`@moonshot-ai/kaos`** provides a portable abstraction over process execution and file operations. According to the implementation in [`packages/kaos/src/kaos.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kaos/src/kaos.ts), it normalizes subprocess spawning across local shells and SSH connections, manages environment variables and working directories, and ensures cross-platform compatibility. This abstraction allows agents to execute shell commands reliably regardless of the underlying operating system, while maintaining security boundaries and proper error handling.