# How the Klient SDK Communicates with the Kimi-Code Server: Architecture and Implementation

> Learn how the Klient SDK communicates with the Kimi-Code server using HTTP REST and WebSockets via typed facades for efficient request-response and real-time streaming.

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

---

**The Klient SDK communicates with the Kimi-Code server through a pluggable transport layer supporting HTTP REST calls for request-response operations and WebSocket connections for real-time streaming, abstracted behind typed façade objects like `GlobalFacade`, `SessionFacade`, and `AgentFacade`.**

The Klient SDK is the official TypeScript client library for the MoonshotAI/kimi-code repository, enabling applications—from TUIs to VS Code extensions—to interact with a running Kimi-Code server. Understanding how the Klient SDK communicates with the Kimi-Code server requires examining its dual-transport architecture that separates synchronous RPC calls from asynchronous event streaming. All network details are hidden behind strongly-typed façade objects that route calls through validated contract envelopes, ensuring type safety across the client-server boundary.

## Transport Layer Architecture

The SDK abstracts network communication through a common `Transport` interface defined in [`src/transports/args.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/transports/args.ts), allowing seamless switching between HTTP, WebSocket, and in-process implementations.

### The Transport Interface

At the core of the communication stack lies the `Transport` interface, which standardizes how the SDK issues network requests:

```typescript
// src/transports/args.ts
export interface Transport {
  fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
  ws(url: string, protocols?: string[]): WebSocket;
}

```

This interface enables the SDK to treat remote HTTP servers, local IPC channels, and memory-based mock transports identically. The `Klient` class automatically selects the appropriate transport implementation based on constructor arguments, ensuring that façade methods remain transport-agnostic.

### HTTP REST Transport

For standard request-response operations, the SDK uses the default HTTP transport implemented in [`src/transports/ipc/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/transports/ipc/index.ts). This transport constructs URLs by appending paths to the base endpoint `${baseUrl}/api/v1/${path}` and serializes payloads using `JSON.stringify` with the `Content-Type: application/json` header.

```typescript
// src/transports/ipc/index.ts
async fetch(input, init) {
  const url = `${this.baseUrl}${input}`;
  const resp = await (this.fetchImpl ?? fetch)(url, init);
  return resp;
}

```

All REST endpoints follow the `/api/v1/*` pattern, with server-side route handlers located in `packages/kap-server/src/routes/*` processing the validated JSON envelopes.

### WebSocket Real-Time Transport

Live updates—including transcript operations and session events—stream over a persistent WebSocket connection to `/api/v1/ws`. The [`src/core/channel.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/core/channel.ts) module manages this connection, decoding incoming binary JSON frames via [`src/transports/ipc/codec.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/transports/ipc/codec.ts) and dispatching them through the Event Hub ([`src/core/events/hub.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/core/events/hub.ts)).

```typescript
// src/core/channel.ts
const ws = this.transport.ws(`${baseUrl}/api/v1/ws`);
ws.addEventListener('message', this.handleMessage.bind(this));

```

### In-Process Memory Transport

For unit testing, the SDK provides a lightweight memory transport under [`src/transports/memory/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/transports/memory/index.ts). This implementation bypasses network I/O entirely, resolving contract objects directly from fixture data and enabling deterministic, fast test execution.

## Request-Response Communication Flow (REST)

The REST communication pattern follows a strict envelope-based protocol. When you invoke a façade method like `client.global.getModels()`, the SDK executes a five-step process:

1. **Facade invocation** – The `GlobalFacade` method constructs a typed request envelope adhering to `ContractModelList` from [`src/contract/global/models.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/contract/global/models.ts).
2. **Transport execution** – The envelope passes to `Transport.fetch`, which issues an HTTP request to the corresponding `/api/v1/` endpoint.
3. **Server processing** – The Kimi-Code server validates the envelope using Zod schemas, executes the business logic, and returns a JSON response.
4. **Client validation** – The SDK validates the response against [`src/core/validation.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/core/validation.ts) schemas.
5. **Result return** – A strongly-typed object (e.g., `ModelInfo[]`) returns to the caller.

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

async function main() {
  const client = new Klient({ baseUrl: 'http://localhost:58627' });
  const models = await client.global.getModels();    // → GET /api/v1/models
  console.log('Available models:', models);
}
main();

```

This example from [`packages/klient/examples/basic.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/klient/examples/basic.ts) demonstrates how the Klient SDK communicates with the Kimi-Code server using standard HTTP GET requests, with the underlying transport handling URL construction and header management automatically.

## Real-Time Event Streaming (WebSocket)

While REST handles stateless queries, WebSocket connections manage stateful, server-pushed updates. The single WebSocket connection to `/api/v1/ws` multiplexes multiple event streams through the Event Hub architecture.

### Transcript Operations

Binary JSON envelopes containing `transcript.ops` flow through the WebSocket and rehydrate the L2 transcript store (`packages/transcript`). Client applications subscribe to these updates via the event system:

```typescript
client.events.on('transcript.ops', (ops) => {
  console.log('New transcript ops:', ops);
});

```

### Session Lifecycle Events

Session-wide state changes—such as `event.session.work_changed`—emit through [`src/core/events/hub.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/core/events/hub.ts), allowing real-time UI updates:

```typescript
client.events.on('session.work_changed', (ev) => {
  console.log('Work changed:', ev);
});

```

The [`examples/kimi-select-tools.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/examples/kimi-select-tools.ts) file demonstrates practical usage, showing how to subscribe to tool-result events and react to server-side agent activities in real time.

## High-Level SDK Architecture

The Klient SDK organizes communication through three primary façade objects that abstract server resources:

- **`GlobalFacade`** – Accesses server-wide resources including models, providers, and workspaces.
- **`SessionFacade`** – Manages individual sessions, handling questions, turns, and transcripts.
- **`AgentFacade`** – Controls individual agents within sessions, exposing tools, plans, and activities.

All façades communicate through the **contract layer** (`src/contract/*`), which defines Zod-validated TypeScript types ensuring that client requests and server responses remain synchronized as the API evolves. The `Klient` core class ([`src/core/klient.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/core/klient.ts)) wires together the transport, event hub, error handling, and retry logic, presenting a unified interface to consumers.

## Summary

- The Klient SDK uses a **pluggable transport interface** ([`src/transports/args.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/transports/args.ts)) supporting HTTP, WebSocket, and in-process communication.
- **REST endpoints** (`/api/v1/*`) handle synchronous RPC calls through the HTTP transport with automatic JSON serialization.
- **WebSocket connections** (`/api/v1/ws`) stream real-time transcript operations and session events via the Event Hub ([`src/core/events/hub.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/core/events/hub.ts)).
- **Zod-validated contracts** (`src/contract/*`) ensure type safety across the client-server boundary.
- Three façade objects—`GlobalFacade`, `SessionFacade`, and `AgentFacade`—provide typed access to server resources without exposing transport details.
- The **in-process memory transport** enables fast, deterministic unit testing by bypassing network I/O.

## Frequently Asked Questions

### How does the Klient SDK handle authentication when communicating with the Kimi-Code server?

The transport layer automatically manages authentication headers through the `RequestInit` configuration passed to the `fetch` implementation. When initializing the `Klient` class, you can provide custom headers that the HTTP transport in [`src/transports/ipc/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/transports/ipc/index.ts) merges into every request, ensuring secure communication with the Kimi-Code server's REST endpoints.

### Can the Klient SDK communicate with multiple Kimi-Code servers simultaneously?

Yes. Since the `Klient` class encapsulates both the transport configuration and connection state, you can instantiate multiple client instances pointing to different `baseUrl` endpoints. Each instance maintains its own transport layer, WebSocket channel ([`src/core/channel.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/core/channel.ts)), and event hub, allowing concurrent communication with distinct Kimi-Code server instances.

### What happens when the WebSocket connection to the Kimi-Code server drops?

The SDK implements reconnection logic within the channel management code ([`src/core/channel.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/core/channel.ts)). When the WebSocket closes unexpectedly, the transport layer attempts to re-establish the connection to `/api/v1/ws`, and the Event Hub buffers critical events during disconnection periods to ensure no transcript operations or session updates are lost during transient network failures.

### How does the Klient SDK validate data received from the Kimi-Code server?

All incoming and outgoing payloads pass through Zod validation schemas defined alongside the contract types in `src/contract/*` and executed via [`src/core/validation.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/core/validation.ts). This guarantees that responses from the Kimi-Code server match expected TypeScript interfaces, throwing runtime errors if server responses violate the contract schema, which protects client applications from malformed data.