# How to Debug Issues Within kimi-code Packages: A Complete Developer Guide

> Debug kimi-code packages effectively using kap-server. Discover and invoke DI-registered services for deep runtime introspection without source code changes. A complete developer guide.

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

---

**TLDR:** Start the **kap-server** with `--debug-endpoints` bound to a loopback address (`127.0.0.1`), then send HTTP requests to `/api/v1/debug/channels` to discover and invoke methods on any DI-registered service, enabling deep introspection of the monorepo’s runtime state without source code changes.

The `kimi-code` repository is a TypeScript monorepo that orchestrates a local **kap-server** engine alongside multiple front-ends including CLI/TUI and VS Code extensions. When tracing misconfigurations in dependency injection services, transport layers, or UI rendering cycles, developers need visibility into the internal container state. According to the MoonshotAI/kimi-code source code, the framework exposes a reflection-based debug RPC surface that grants unrestricted access to registered services, transcript stores, and render trees when safety-gated behind loopback bindings.

## Enable the Debug RPC Surface on the kap-server

The debug interface is disabled by default and gated behind both a startup flag and a network security check. The server only exposes these endpoints when the host classifies as **loopback** to prevent accidental exposure on public interfaces.

### Command-Line Startup

When launching the server via `pnpm dev:v2` or directly, append the `--debug-endpoints` flag and explicitly bind to localhost:

```bash
node ./packages/kap-server/src/start.ts --debug-endpoints --host 127.0.0.1

```

The `--debug-endpoints` flag sets `debugEndpoints: true` in `ServerStartOptions` within [`packages/kap-server/src/start.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kap-server/src/start.ts) (lines 101–102). The security classifier in [`security/bindClassify.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/security/bindClassify.ts) validates that the address is loopback before mounting the routes.

### Programmatic Configuration

If starting the server from another process (e.g., the CLI or a test harness), pass the option directly to `startServer`:

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

const server = await startServer({ 
  host: '127.0.0.1', 
  debugEndpoints: true 
});

```

## Query and Invoke Services via the Debug API

Once enabled, the debug RPC mounts under `/api/v1/debug`. The router registration occurs in **[`registerDebugRoutes.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/registerDebugRoutes.ts)** (lines 22–27), which delegates to the generic dispatcher implemented in **[`serviceDispatcherRoutes.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/serviceDispatcherRoutes.ts)** (lines 17–27).

### List Available Channels

To inspect every DI-registered service and its exposed methods, query the channels endpoint. This is the same data consumed by the **kimi-inspect** UI to build its service explorer:

```bash
curl -H "Authorization: Bearer $TOKEN" \
  http://127.0.0.1:58627/api/v1/debug/channels

```

The response returns a JSON array of channel descriptors containing service IDs, scopes, and available method lists.

### Execute Service Methods

The dispatcher resolves any scoped service ID at runtime via **`resolveAnyScopedServiceId`** in [`packages/kap-server/src/transport/channelRegistry.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kap-server/src/transport/channelRegistry.ts) (lines 19–25). This allows you to target services without hard-coding their container location.

For example, to flush the in-memory append-log store (`IAppendLogStore`):

```typescript
import fetch from 'node-fetch';

const resp = await fetch(
  'http://127.0.0.1:58627/api/v1/debug/IAppendLogStore/flush',
  {
    method: 'POST',
    headers: { Authorization: `Bearer ${token}` },
    body: JSON.stringify([]),
  }
);
const data = await resp.json();

```

The URL pattern follows `/api/v1/debug/<ServiceId>/<method>`. You can replace `ServiceId` with any identifier returned by the channels endpoint, such as `ISessionIndex` or `IAppendLogStore`, and invoke any public method they expose.

## Interpret Transport-Level Error Codes

When services throw exceptions, the RPC layer translates them into structured **`TransportError`** responses. The mapping logic resides in **[`packages/kap-server/src/transport/errors.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kap-server/src/transport/errors.ts)**.

If a debug call returns a 500-level status, inspect the `code` and `msg` fields in the JSON response. These correlate to the original exception type—distinguishing between DI container resolution failures, service implementation errors, and downstream provider timeouts.

## Debug the Terminal UI (TUI)

The `pi-tui` package provides interactive debugging utilities for render-state inspection.

### Interactive State Dumps

During runtime, press **Shift+Ctrl+D** to trigger the global debug callback defined in **[`packages/pi-tui/src/tui.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/pi-tui/src/tui.ts)** (lines 327–334). This invokes a snapshot of the current component tree.

### Environment-Based Logging

Set the `PI_DEBUG_REDRAW` environment variable to dump rendering data to disk for offline analysis:

```bash
export PI_DEBUG_REDRAW=1
pnpm dev:tui

# Press Shift+Ctrl+D to generate a dump

```

When enabled, the TUI writes component trees to `/tmp/tui/render-<timestamp>.log` (see the `debugDir` logic around line 1609 in [`tui.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/tui.ts)). Diffing these logs reveals how state mutations propagate through the render cycle.

## Use Test Fixtures for Reproducible Debugging

The test suite contains helpers that bootstrap a real server with debug endpoints enabled. Reference **[`packages/kap-server/test/debugNonloopback.e2e.test.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kap-server/test/debugNonloopback.e2e.test.ts)** for a minimal example that validates endpoint security constraints.

You can reuse this pattern to create isolated reproductions:

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

const server = await startServer({ 
  host: '127.0.0.1', 
  debugEndpoints: true 
});
// Execute debug RPC calls, then teardown

```

## Monitor Server Logs and Telemetry

Server logging is injected via **`createServerLogger`** (see [`start.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/start.ts) lines 36–39). The logger respects the `logLevel` option and outputs structured JSON to stdout, capturing lifecycle events like `session_started` or `session_load_failed`.

While **telemetry** forwarding to cloud appenders is optional and does not affect local debugging, the structured logs provide the definitive timeline for correlating client actions with server state changes.

## Key Files for Debugging Reference

| Package | File | Purpose |
|---------|------|---------|
| `kap-server` | [`src/start.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/start.ts) | Bootstrap logic, option parsing, debug-endpoint gating |
| `kap-server` | [`src/transport/registerDebugRoutes.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/transport/registerDebugRoutes.ts) | Mounts the `/api/v1/debug` router |
| `kap-server` | [`src/transport/serviceDispatcherRoutes.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/transport/serviceDispatcherRoutes.ts) | Implements reflection-based RPC dispatch |
| `kap-server` | [`src/transport/channelRegistry.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/transport/channelRegistry.ts) | Runtime resolution of scoped service IDs |
| `kap-server` | [`src/transport/errors.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/transport/errors.ts) | Exception-to-RPC error code mapping |
| `pi-tui` | [`src/tui.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/tui.ts) | Global debug key handling and render dumps |
| `kap-server` | [`test/debugNonloopback.e2e.test.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/test/debugNonloopback.e2e.test.ts) | Security validation for debug endpoint binding |

## Summary

- **Enable** the debug surface with `--debug-endpoints` on a loopback bind (`127.0.0.1`) to satisfy the security classifier.
- **Discover** injectable services via `/api/v1/debug/channels` and invoke methods using the `/api/v1/debug/<ServiceId>/<method>` pattern.
- **Diagnose** transport failures using the structured error codes in [`errors.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/errors.ts).
- **Capture** TUI render trees with `PI_DEBUG_REDRAW=1` and the Shift+Ctrl+D hotkey.
- **Reproduce** issues locally using the test-suite server fixtures for controlled debugging.

## Frequently Asked Questions

### How do I enable debug endpoints in kimi-code?

Start the server with the `--debug-endpoints` flag and ensure it binds to a loopback address such as `127.0.0.1`. This configures `ServerStartOptions` in [`packages/kap-server/src/start.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/kap-server/src/start.ts) and satisfies the loopback classification check in [`security/bindClassify.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/security/bindClassify.ts). Without the loopback bind, the endpoints remain disabled for security.

### Why are debug endpoints not accessible on my network interface?

The debug RPC surface requires a **loopback** host classification to prevent exposure to external networks. If you bind to `0.0.0.0` or a public IP, the server silently disables the debug routes. Always use `--host 127.0.0.1` when enabling debug mode.

### How can I inspect the internal state of a specific service?

Query `/api/v1/debug/channels` to retrieve the service ID (e.g., `ISessionIndex`), then POST to `/api/v1/debug/<ServiceId>/snapshot` or any exposed method. The dispatcher in [`serviceDispatcherRoutes.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/serviceDispatcherRoutes.ts) resolves the service via `resolveAnyScopedServiceId` in [`channelRegistry.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/channelRegistry.ts), returning the current state as JSON.

### What should I do if the TUI rendering appears incorrect?

Set the environment variable `PI_DEBUG_REDRAW=1` before launching the TUI, then press **Shift+Ctrl+D** to trigger a dump. Analyze the generated logs in `/tmp/tui/` to diff component trees and identify state mismatch between the application logic and the render output.