πŸ”¬ SOVEREIGN FORENSIC ANALYSIS

Kimi Code CLI
Deep Architecture Analysis

A comprehensive educational dissection of MoonshotAI's open-source coding agent β€” from prompt construction lineage through agentic loops, subagent orchestration, tool parallelism, to compaction intelligence.

GitHub β†’ 3.4k β˜…v0.27.0 β€’ TypeScript β€’ MIT
911Source Files
16Packages
3Subagent Types
128Max Swarm
50K+Lines Analyzed
πŸ›οΈ

Architecture Overview

The monorepo structure and 16 packages composing the complete coding agent system.

Diagram
agent-core

Main engine: loop, tools, prompts, compaction, subagents

~35%
agent-core-v2

Next-gen engine with DI container, wire protocol

~25%
klient

Multi-transport client (WS, HTTP, IPC, memory)

~10%
kaos

Process management β€” local + SSH execution

~8%
pi-tui

Custom terminal UI framework

~7%
kap-server

Agent Protocol Server for editor integration

~5%
kosong

LLM provider abstraction (OpenAI/Anthropic)

~4%
others

protocol, minidb, oauth, acp-adapter, telemetry, migration-legacy

~6%
🧬

Prompt Construction Lineage

Complete path from template files through profile resolution to the final system prompt sent to the LLM.

Lineage Flow Diagram

Diagram

Template Variable Resolution

VariableSourceExample
{{ KIMI_OS }}kaos.osEnv.osKindLinux / macOS / Windows
{{ KIMI_SHELL }}kaos.osEnv.shellNameBash (/bin/bash)
{{ KIMI_NOW }}context.nowISO 8601 timestamp
{{ KIMI_WORK_DIR }}config.cwd/home/user/project
{{ KIMI_WORK_DIR_LS }}context.cwdListingDirectory tree view
{{ KIMI_AGENTS_MD }}context.agentsMdAGENTS.md project instructions
{{ KIMI_SKILLS }}skills registryAvailable skill listing
{{ ROLE_ADDITIONAL }}promptVars + context.roleAdditionalSubagent-specific role

Profile Inheritance Tree

Diagram
profile/default/system.md β€” Main system prompt template (158 lines, Jinja2-style variables)
profile/default/agent.yaml β€” Base profile: defines extends chain root, tool list, subagent declarations
profile/default/coder.yaml β€” Coder subagent: extends agent, adds ROLE_ADDITIONAL for subagent context
profile/default/explore.yaml β€” Explore subagent: read-only, fast codebase exploration with regex
profile/default/plan.yaml β€” Plan subagent: read-only planning, recommends explore agents
profile/default.ts β€” Bundles raw YAML+MD into PROFILE_SOURCES map
profile/resolve.ts β€” resolveAgentProfiles(): extends inheritance, template renderer construction
agent/index.ts β€” Agent.useProfile() and refreshSystemPrompt() wire profile to config
utils/render-prompt.ts β€” Template engine for Jinja2-style variable substitution
πŸ”„

The Agentic Loop Engine

The dual-layer turn-step execution loop that powers every Kimi Code agent interaction.

Diagram

Turn Level (run-turn.ts)

β€’ Outer while(true) loop with abort + max-step guards

β€’ Media degradation cascade: normal β†’ media-degraded β†’ media-stripped

β€’ Once degraded, stays degraded for rest of turn

β€’ Usage aggregation via addUsage() across all steps

β€’ Optional shouldContinueAfterStop hook for non-tool-stop continuation

Step Level (turn-step.ts)

β€’ Pre-step hooks: compaction check, permission sync

β€’ Dynamic tool table rebuild via buildTools() each step

β€’ LLM call with streaming callback wiring

β€’ Tool-call batch lifecycle: classification β†’ scheduling β†’ execution β†’ results

β€’ Stop reasons: tool_use | end_turn | max_tokens | refusal

loop/run-turn.ts β€” Turn-level convergence, max-step enforcement, media degradation (~255 lines)
loop/turn-step.ts β€” One provider step: hooks, message build, LLM call, tool-call handoff
loop/tool-call.ts β€” Tool-call batch lifecycle: classification, preparation, scheduling, results
loop/README.md β€” Architecture contracts: ownership, event dispatch, test boundaries
⚑

Tool Concurrency & Resource Conflict Detection

How Kimi Code maximizes parallel tool execution through file-level resource access tracking.

Diagram

βœ… Safe β€” Run in Parallel

β€’ Read + Read on different files

β€’ Read + Search on different directory trees

β€’ Read + Glob (tool-level safe)

β€’ Grep + Read (different paths)

⚠️ Must Serialize

β€’ Write + anything on same path

β€’ ReadWrite(dir) + Read(dir/sub)

β€’ Bash (declares All access)

β€’ AgentSwarm (declares All access)

loop/tool-scheduler.ts β€” Stateful execution scheduler: active/queued task queues, conflict detection (~100 lines)
loop/tool-access.ts β€” Resource conflict model: file-level read/write/readwrite/search with recursive directory overlap detection (~118 lines)
🐝

Subagent & Swarm Orchestration

How Kimi Code delegates work to isolated subagents and coordinates parallel swarms with sophisticated rate-limit handling.

Diagram

πŸ€– Single Agent Tool

β€’ Spawns one subagent per tool call with isolated context

β€’ Inherits model config from parent agent

β€’ Summary under 200 chars triggers follow-up expansion turn

β€’ Background mode: detaches from parent turn lifecycle

β€’ 2-hour default timeout (KIMI_SUBAGENT_TIMEOUT_MS)

🐝 AgentSwarm Tool

β€’ Parallel batch: up to 128 subagents in one call

β€’ prompt_template + items β†’ individual prompts per subagent

β€’ Resume support: resume_agent_ids for retrying failed subagents

β€’ Rate-limit phase: 3β†’6β†’12s exponential backoff

β€’ Completed/failed/aborted per-subagent status tracking

Swarm Batch Scheduling Algorithm

Normal Phase

β€’ Launch 5 tasks immediately, then 1 more every 700ms ramp

β€’ Priority ordering: rate-limited retries β†’ explicit resumes β†’ new spawns

β€’ Respects KIMI_CODE_AGENT_SWARM_MAX_CONCURRENCY cap

Rate-Limit Phase

β€’ Entered on first provider rate limit error

β€’ Capacity = ready normal launches (min 1), shrinks by 1 per hit

β€’ Retry delays: 3s β†’ 6s β†’ 12s β†’ doubling each attempt

β€’ Capacity recovery: +1 after 3 minutes quiet window

β€’ Solitary task rule: if only 1 unfinished, fail instead of suspend forever

session/subagent-batch.ts β€” SubagentBatch scheduler: dual-phase operation, capacity management (~680 lines)
session/subagent-host.ts β€” SessionSubagentHost: spawn, resume, retry, background draining (~599 lines)
🧠

Context Compaction Intelligence

How Kimi Code autonomously manages conversation context through LLM-based summarization with overflow detection and adaptive recovery.

Diagram

Key Compaction Insights

1. LLM-as-Summarizer: Uses the same model to summarize conversation history, including system prompt as context. Avoids introducing a separate model dependency.

2. Dynamic Tool Context Stripping: Schema messages and loadable-tool announcements are excluded from summarizer input entirely β€” they are protocol state, not conversation, and summarizing them wastes tokens.

3. Overflow Learning: When provider rejects with 413, the actual token limit is observed and cached per model, capped at 85% for safety margin. This prevents repeated overflow→compact loops.

4. Post-Compaction Re-injection: System prompt refreshed, tool manifests re-announced, goals/todos re-appended. This ensures agent state continuity after the conversation is summarized.

5. Truncation Safety: If summarizer response is truncated (finish_reason=truncated), retries with CompactionTruncatedError instead of accepting partial summary.

agent/compaction/full.ts β€” FullCompaction engine: triggers, retry loops, overflow recovery (~793 lines)
πŸͺ

Lifecycle Hooks & Safety Gates

Plugin hook architecture for gating risky tool calls, auditing decisions, and triggering external notifications.

PreToolUse β€” Gate tool calls before execution
PostToolUse β€” Audit trail after tool execution
SubagentStart β€” Before subagent spawn
SubagentStop β€” After subagent completes
PreCompact β€” Before context compaction
Notification β€” External event triggers
session/hooks.ts β€” HookEngine: YAML-configurable lifecycle hooks executed as local shell commands
πŸ’‘

Architectural Innovations

What makes Kimi Code's architecture uniquely powerful among coding agents.

Profile Inheritance

YAML-based extends chain lets subagents inherit base capabilities while layering role-specific constraints β€” zero code duplication. Coder/explore/plan share base agent template.

Resource-Aware Scheduling

File-level access tracking enables maximum safe parallelism. Reads run concurrently; writes serialize only on path conflicts β€” not globally. Shell commands declare ALL access for safety.

Swarm Rate-Limit Resilience

Dual-phase batch scheduler with exponential backoff, capacity recovery, and solitary-task fallback. Makes 128-agent swarms production-viable against real API rate limits.

Overflow-Learning Compaction

Observes actual provider rejection limits and continuously adjusts effective context window per model. Never repeats a compaction that cannot shrink the context further.

Multi-Transport Architecture

Single klient client facade supports WS/HTTP/IPC/memory transports. Same agent core runs in TUI, IDE (via ACP), web, or programmatic contexts without code changes.

Prompt-as-Closure Pattern

System prompt is a lazy renderer that captures template+vars at profile load time and applies runtime context at render time. Enables post-compaction refresh without re-parsing profiles.