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

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, 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 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, 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 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 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 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 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 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 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 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 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 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:

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 to establish a typed connection to the server infrastructure.

Spawning Subprocesses with Kaos

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

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 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:

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, which normalizes responses across different LLM providers.

Migrating Legacy Archives

Convert historical session data to the modern transcript format:

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 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:

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 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, 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, 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, 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.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →