Architecture Overview
The monorepo structure and 16 packages composing the complete coding agent system.
Main engine: loop, tools, prompts, compaction, subagents
~35%Next-gen engine with DI container, wire protocol
~25%Multi-transport client (WS, HTTP, IPC, memory)
~10%Process management β local + SSH execution
~8%Custom terminal UI framework
~7%Agent Protocol Server for editor integration
~5%LLM provider abstraction (OpenAI/Anthropic)
~4%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
Template Variable Resolution
| Variable | Source | Example |
|---|---|---|
| {{ KIMI_OS }} | kaos.osEnv.osKind | Linux / macOS / Windows |
| {{ KIMI_SHELL }} | kaos.osEnv.shellName | Bash (/bin/bash) |
| {{ KIMI_NOW }} | context.now | ISO 8601 timestamp |
| {{ KIMI_WORK_DIR }} | config.cwd | /home/user/project |
| {{ KIMI_WORK_DIR_LS }} | context.cwdListing | Directory tree view |
| {{ KIMI_AGENTS_MD }} | context.agentsMd | AGENTS.md project instructions |
| {{ KIMI_SKILLS }} | skills registry | Available skill listing |
| {{ ROLE_ADDITIONAL }} | promptVars + context.roleAdditional | Subagent-specific role |
Profile Inheritance Tree
The Agentic Loop Engine
The dual-layer turn-step execution loop that powers every Kimi Code agent interaction.
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
Tool Concurrency & Resource Conflict Detection
How Kimi Code maximizes parallel tool execution through file-level resource access tracking.
β 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)
Subagent & Swarm Orchestration
How Kimi Code delegates work to isolated subagents and coordinates parallel swarms with sophisticated rate-limit handling.
π€ 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
Context Compaction Intelligence
How Kimi Code autonomously manages conversation context through LLM-based summarization with overflow detection and adaptive recovery.
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.
Lifecycle Hooks & Safety Gates
Plugin hook architecture for gating risky tool calls, auditing decisions, and triggering external notifications.
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.