How to Debug Issues Within kimi-code Applications: Complete Developer Guide

Enable the debug RPC surface with --debug-endpoints bound to 127.0.0.1 to expose internal service state via /api/v1/debug, inspect transport errors in errors.ts, and capture TUI render cycles using PI_DEBUG_REDRAW=1 for comprehensive troubleshooting.

Debugging issues within kimi-code applications requires navigating its TypeScript monorepo architecture, where a local kap-server engine powers multiple front-ends including CLI, TUI, and VS Code extensions. The repository exposes a reflection-based debug RPC layer that provides unrestricted visibility into the dependency injection (DI) container when activated on loopback interfaces, allowing you to query live service states without modifying source code.

Enable the Debug RPC Surface

The debug functionality is gated behind runtime flags to prevent accidental exposure on public networks. When starting the server via pnpm dev:v2 or programmatically, you must explicitly activate the endpoints and ensure the host resolves as loopback.

Start the server with the required flags:

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

The --debug-endpoints flag triggers the debugEndpoints option in ServerStartOptions as defined in packages/kap-server/src/start.ts (lines 101‑102). The server performs a security check via classify in security/bindClassify.ts to verify the bind address qualifies as loopback; debug endpoints remain disabled on non-loopback interfaces.

To enable debugging programmatically from another process (such as the CLI), pass the option to startServer:

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

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

Query Services via the Debug HTTP API

Once enabled, the server mounts a reflection-based RPC dispatcher under /api/v1/debug. This surface is registered by registerDebugRoutes.ts (lines 22‑27), which delegates to the generic dispatcher in serviceDispatcherRoutes.ts (lines 17‑27).

List Available Channels

Discover all exposed services and their methods by querying the channels endpoint:

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 methods. The kimi-inspect UI consumes this same data to build its service explorer.

Invoke Service Methods

Target any DI-registered service by constructing the path /api/v1/debug/<ServiceId>/<method>. The dispatcher resolves the service at runtime via resolveAnyScopedServiceId in packages/kap-server/src/transport/channelRegistry.ts (lines 19‑25).

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

import fetch from 'node-fetch';

const token = process.env.KIMI_TOKEN;
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();
console.log(data);

Extract Service State Snapshots

Fetch structured internal state from any service to verify runtime values:

async function getServiceState(token: string, serviceId: string) {
  const url = `http://127.0.0.1:58627/api/v1/debug/${serviceId}/snapshot`;
  const resp = await fetch(url, {
    method: 'POST',
    headers: { Authorization: `Bearer ${token}` },
    body: JSON.stringify([]),
  });
  if (!resp.ok) throw new Error(`Debug call failed: ${resp.status}`);
  const { data } = await resp.json();
  return data;
}

// Usage example:
const state = await getServiceState(token, 'ISessionIndex');
console.log(JSON.stringify(state, null, 2));

Diagnose Transport-Level Errors

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.

If you receive 500-level responses, examine the code and msg fields in the error payload. This correlation helps determine whether failures originate from service implementation logic, DI container resolution, or downstream providers.

Debug the Terminal UI Interactively

The pi-tui package provides runtime introspection tools for UI-related issues.

Press Shift+Ctrl+D to trigger the debug callback defined in packages/pi-tui/src/tui.ts (lines 327‑334). Additionally, set the environment variable PI_DEBUG_REDRAW=1 before launching the TUI to enable render-cycle dumps:

export PI_DEBUG_REDRAW=1
pnpm dev:tui

# Press Shift+Ctrl+D in the UI to dump state

When enabled, the TUI writes rendering data to /tmp/tui/render-<timestamp>.log (see the debugDir logic around line 1609). Diff these logs to trace how component trees change across state updates.

Leverage Test Helpers for Reproduction

The test suite contains helpers that instantiate real servers with debug RPC enabled. Reference packages/kap-server/test/debugNonloopback.e2e.test.ts for a minimal example that validates endpoint security.

Use this pattern to spin up temporary debug servers in custom scripts:

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

const server = await startServer({ 
  host: '127.0.0.1', 
  debugEndpoints: true 
});
// Server is now accessible for curl-based debugging

Common Debug Scenarios

Service Not Found Errors

Query /api/v1/debug/channels to verify the service ID is registered. If absent, ensure the package containing the service is imported in the server bootstrap sequence (check bootstrap seeds in start.ts).

Authentication Failures (401)

Confirm the bearer token matches the persistent token printed on server startup, or supply the optional rpcToken if you configured custom authentication.

Unexpected Transcript State

Use the /api/v1/debug/transcript/... endpoints to fetch raw operation logs and compare them against UI representations.

Debug RPC Unavailable

Verify the server started with both --debug-endpoints and a loopback address (127.0.0.1). The framework silently disables debug surfaces on non-loopback binds for security.

Summary

  • Activate the debug surface with --debug-endpoints and loopback binding to safely expose internal services.
  • Query /api/v1/debug/channels to discover all injectable services, then invoke methods via /api/v1/debug/<Service>/<method>.
  • Interpret transport errors using the mapper in packages/kap-server/src/transport/errors.ts.
  • Capture TUI render states by setting PI_DEBUG_REDRAW=1 and triggering dumps with Shift+Ctrl+D.
  • Use test helpers from debugNonloopback.e2e.test.ts to create reproducible debug environments.

Frequently Asked Questions

How do I enable debug endpoints in kimi-code?

Start the server with the --debug-endpoints flag and bind to 127.0.0.1 to satisfy the loopback security check defined in security/bindClassify.ts. Programmatically, pass debugEndpoints: true to the startServer options in packages/kap-server/src/start.ts.

Why is the debug RPC returning 401 Unauthorized?

The bearer token in your request headers must match the persistent token printed during server startup, or the custom rpcToken configured in server options. Verify the Authorization: Bearer <token> header format and ensure the token has not expired.

How can I inspect the TUI render state for visual bugs?

Set the environment variable PI_DEBUG_REDRAW=1 before launching the TUI, then press Shift+Ctrl+D to trigger a dump. The framework writes component tree data to /tmp/tui/render-<timestamp>.log according to the logic in packages/pi-tui/src/tui.ts, allowing offline inspection of rendering cycles.

What should I check if a service method returns 404?

First, query /api/v1/debug/channels to confirm the service ID is registered in the DI container. If the service is missing, check that its package is properly imported in the server bootstrap. Also verify the method name spelling matches the exposed interface, as the dispatcher in serviceDispatcherRoutes.ts performs exact string matching.

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 →