What Is agent-core in MoonshotAI/kimi-code? The TypeScript Engine Powering Kimi AI
agent-core is the foundational TypeScript library in the MoonshotAI/kimi-code repository that implements the runtime engine for autonomous AI agents, providing a turn-based execution loop, skill management system, and dependency injection infrastructure.
This package serves as the backbone of the Kimi AI platform, exposing a stateless, test-driven core that higher-level packages like node-sdk, kap-server, and klient consume to build AI-driven tooling. Located at packages/agent-core, it exports its public API through src/index.ts while keeping implementation details modularized across functional domains.
Core Responsibilities of agent-core
The package orchestrates agent behavior through several specialized subsystems. The architecture is deliberately stateless between turns, with all mutable state managed via dependency-injection (DI) containers to ensure reproducibility.
Turn-Based Execution Loop
The engine implements a deterministic turn-based execution loop centered on the runTurn function in src/loop/run-turn.ts. This loop orchestrates LLM calls, schedules tool executions via src/loop/tool-scheduler.ts, handles retries with exponential backoff, and manages streaming responses through src/loop/tool-call.ts. Each turn is atomic and reproducible, allowing sessions to be snapshotted or replayed for debugging.
Skill System Management
agent-core parses, registers, and executes skills through modules in src/skill/. The registry.ts file maintains the skill catalog and lookup mechanisms, while parser.ts processes skill definitions (typically YAML front-matter) and scanner.ts discovers built-in and custom skills at runtime. This system enables dynamic extension of agent capabilities without modifying core engine code.
Hierarchical Lifecycle Scopes
The library defines strict lifecycle scopes—App → Workspace → Session → Agent—each with its own DI container. This hierarchy isolates configuration and state management across different granularity levels. Workspace-level services reside in src/services/workspace/workspaceRegistry.ts, which acts as the DI container for workspace-specific instances, while session state persists through injectable SessionStore services.
MCP Configuration and OAuth
The MCP (multi-client-provider) subsystem in src/mcp/ centralizes configuration management. The global-config.ts module handles global and per-workspace settings, while the oauth/ directory manages token handling and server-side authentication flows. This configuration layer allows different workspaces to maintain separate provider credentials and server endpoints.
Telemetry and Error Handling
Structured logging flows through src/logging/logger.ts, which provides standardized log sinks across the engine. Typed error codes and serialization utilities live in src/errors/, while the feature-flag system in src/flags/registry.ts and src/flags/resolver.ts enables safe rollout of experimental capabilities and A/B testing of agent behaviors.
Architectural Overview
The package organizes functionality into distinct layers that higher-level SDKs compose into complete applications:
- Core Engine (
src/loop/*): Housesrun-turn.ts,tool-scheduler.ts, andtool-call.tsfor execution management. - Skill System (
src/skill/*): Containsregistry.ts,parser.ts, andscanner.tsfor skill operations. - DI Services (
src/services/*): Provides injectable containers for workspace registry, session stores, and provider management. - Configuration (
src/mcp/*): Manages global MCP settings, OAuth tokens, and workspace-specific configs. - Infrastructure (
src/flags/*,src/logging/*,src/errors/*): Supports feature gating via the flags registry, structured logging, and typed error serialization.
Because the engine maintains no state between turns, parallelizing sessions or implementing distributed execution requires only spinning up additional DI container instances.
Working with agent-core
While most developers interact with agent-core through the node-sdk, you can import types directly from the core package to build custom implementations.
Installation
Install the core package directly:
pnpm add @moonshot-ai/agent-core
Or use the SDK which bundles and configures agent-core automatically:
pnpm add @moonshot-ai/node-sdk
Basic Implementation Example
The following example demonstrates creating a session and executing a turn using the SDK, which internally wires the agent-core engine:
// demo.ts
import { createKimiHarness } from '@moonshot-ai/node-sdk'
import { Config } from '@moonshot-ai/agent-core'
// 1. Configure workspace and model defaults
const cfg: Config = {
workspace: { root: '/tmp/kimi-workspace' },
model: { default: 'gpt-4o-mini' },
}
// 2. Initialize harness (wires AgentCore DI containers)
const harness = await createKimiHarness({ config: cfg })
// 3. Create isolated session context
const session = await harness.createSession({ name: 'demo-session' })
// 4. Execute turn (core loop handles LLM call and tool scheduling)
await session.sendMessage({
role: 'user',
content: 'Explain the concept of dependency injection.'
})
await session.runTurn()
// 5. Retrieve conversation transcript
const transcript = await session.transcript()
console.log(transcript.map(m => `${m.role}: ${m.content}`).join('\n'))
The createKimiHarness function in packages/node-sdk/src/index.ts instantiates the agent-core engine, configures the hierarchical DI containers, and returns a harness that manages the App → Workspace → Session lifecycle automatically.
Key Source Files
Understanding the entry points and critical modules helps when extending or debugging the engine:
packages/agent-core/src/index.ts: Public export barrel and entry point for the@moonshot-ai/agent-corepackage.src/loop/run-turn.ts: Core turn execution logic including LLM invocation, tool scheduling, and retry handling.src/skill/registry.ts: Skill registration, lookup, and loading mechanisms for built-in and custom skills.src/mcp/global-config.ts: Global MCP configuration read/write operations and default value management.src/services/workspace/workspaceRegistry.ts: Workspace-level DI container implementation and service registry.src/logging/logger.ts: Structured logger interface used across all engine subsystems.src/flags/registry.ts: Feature-flag registry for gating experimental agent capabilities.src/errors/*.ts: Typed error codes, error classes, and serialization utilities.
Summary
- agent-core is the foundational TypeScript runtime engine for Kimi AI agents, located at
packages/agent-corein the MoonshotAI/kimi-code repository. - It provides a stateless, turn-based execution loop via
src/loop/run-turn.tsthat manages LLM calls, tool scheduling, and retry logic. - The skill system in
src/skill/enables dynamic registration and execution of custom commands and prompts parsed from YAML definitions. - Hierarchical DI containers manage scoped state across App, Workspace, Session, and Agent lifecycles, with registries defined in
src/services/. - The MCP subsystem handles multi-provider configuration and OAuth flows, while structured logging and typed errors provide production-grade observability.
Frequently Asked Questions
What is agent-core in MoonshotAI/kimi-code?
agent-core is the foundational TypeScript library that powers the Kimi AI agent platform. It provides the runtime engine for autonomous agents, including a turn-based execution loop, skill management system, dependency injection infrastructure, and MCP configuration handling. Higher-level packages like node-sdk import @moonshot-ai/agent-core to leverage its test-driven engine without reimplementing agent lifecycle management.
How does the turn-based execution loop work in agent-core?
The loop is implemented in src/loop/run-turn.ts and operates deterministically to process each interaction turn. It orchestrates LLM API calls, schedules tool executions via the tool scheduler, manages streaming responses, and implements retry logic for transient failures. Because the engine maintains no state between turns, all context persists through DI-provided services like SessionStore, making turns atomic and reproducible.
What is the skill system in agent-core?
The skill system is a modular framework in src/skill/ that parses, registers, and executes custom agent capabilities. The registry.ts module maintains the skill catalog, parser.ts processes YAML front-matter definitions, and scanner.ts discovers available skills at runtime. This architecture allows developers to extend agent behavior with custom commands and prompts without modifying the core engine source code.
Can I use agent-core independently of the Kimi node-sdk?
Yes, you can import @moonshot-ai/agent-core directly to build custom agent implementations, though most developers use the node-sdk wrapper for simplified configuration. Direct usage requires manual instantiation of the DI containers and management of the lifecycle scopes (App → Workspace → Session → Agent) that the SDK typically handles automatically via the createKimiHarness function.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →