How Kimi-Code's Swarm Feature Enables Parallel Subagent Execution

The swarm feature in Kimi-Code enables parallel subagent execution through a metadata-driven coordination layer that tracks child agents in a roster while the underlying TaskScheduler dispatches their work concurrently.

The swarm capability is Kimi-Code's built-in mechanism for running multiple sub-agents (called members) simultaneously. Rather than managing threads or processes directly, it operates as a declarative coordination system that signals the engine to maintain a group of child agents while the v2 scheduler executes their tasks in parallel. This article breaks down the source code implementation in the MoonshotAI/kimi-code repository to show exactly how parallel execution is achieved.


Swarm Mode: The Metadata Foundation

At the heart of the swarm system is a session-level metadata flag that tracks whether the current context is operating in swarm mode. This flag lives in the session's meta object and serves as the single source of truth for the entire execution context.

In packages/transcript/src/model/meta.ts, the swarm state is stored in meta.modes.swarm:

  • When entering swarm mode: the flag is set to an empty object {}
  • When exiting swarm mode: the flag is cleared to undefined

This simple state management allows any component in the system to check meta.modes.swarm and immediately know whether it should treat child agents as part of a coordinated swarm group.


Swarm Lifecycle: Enter and Exit Markers

Every swarm session produces transcript markers that create an observable audit trail. These markers are generated in packages/transcript/src/history/foldFacts.ts:

  • swarm.enter – recorded when swarm mode begins
  • swarm.exit – recorded when swarm mode ends

These entries serve two purposes. First, they allow UI layers to render "swarm" badges that indicate parallel execution is active. Second, they provide the server with precise timestamps for when the coordination window opened and closed, enabling accurate billing and debugging.


The IAgentSwarmService Interface

The programmatic control surface for swarm mode is IAgentSwarmService, implemented in packages/node-sdk/src/sdk-rpc-client-v2.ts. This service provides three core operations for session-scoped agents:

interface IAgentSwarmService {
  enter(trigger: string): void;  // Activates swarm mode with a trigger identifier
  exit(): void;                   // Deactivates swarm mode
  isActive(): boolean;            // Checks current swarm state
}

The service is injected into every session-scope agent, ensuring that any code running within a session can query or modify the swarm state through a consistent interface.


High-Level SDK: session.swarm()

Most developers interact with swarm mode through the convenience method in packages/node-sdk/src/session.ts. The session.swarm(input) API encapsulates the entire lifecycle into a single turn:

// Enable swarm mode and run a user-prompt that spawns sub-agents
await session.swarm({
  input: [{ type: 'text', text: 'Plan a week-long trip' }],
});

Under the hood, this method executes three steps:

  1. Calls IAgentSwarmService.enter() with the user-provided trigger
  2. Runs the underlying prompt or tool as a one-shot task
  3. Automatically calls IAgentSwarmService.exit() to clean up

The automatic cleanup guarantees that swarm mode never leaks across turns, preventing resource exhaustion and billing ambiguity.


Subagent Roster: Tracking Parallel Members

When swarm mode is active, every spawned sub-agent is registered in a roster managed by SubagentRosterTracker. This component, tested in packages/kap-server/test/subagentRosterTracker.test.ts, performs critical bookkeeping:

  • Stores each child agent's transcript independently
  • Updates the parent session's swarm meta to reflect active members
  • Enables the UI to display live "swarm cards" for every member

The roster decouples registration (knowing which agents exist) from execution (running their tasks), which is essential for true parallelism.


Parallel Execution: The TaskScheduler

Actual concurrency happens in the v2 engine's TaskScheduler, referenced in packages/agent-core-v2/AGENTS.md. The scheduler operates on the roster's task queue with these characteristics:

  • Pulls ready tasks from the roster without serialization
  • Dispatches each sub-agent to its own execution context
  • Leverages Node.js's event loop for concurrent I/O-bound work

Critically, the swarm metadata does not control scheduling. It only provides UI visibility and session management. The scheduler achieves parallelism because each roster member owns:

This separation of concerns—metadata for coordination, scheduler for execution—is what makes Kimi-Code's swarm both robust and performant.


Practical Implementation Examples

Spawning Parallel Sub-Agents in a Skill

Inside a custom skill, you can launch multiple sub-agents that execute concurrently:

export const travelPlannerSkill = createSkill({
  name: 'travelPlanner',
  async run(ctx) {
    // Spawn two sub-agents that will work in parallel
    const agentA = await ctx.session.subagent({ name: 'flightFinder' });
    const agentB = await ctx.session.subagent({ name: 'hotelFinder' });

    // Fire off their tasks without awaiting – they run concurrently
    agentA.runTask({ input: [{ type: 'text', text: 'Find cheap flights' }] });
    agentB.runTask({ input: [{ type: 'text', text: 'Find 4-star hotels' }] });
  },
});

Manual Swarm Service Access

For advanced use cases, access the service directly through the session accessor:

const swarm = session.accessor.get(IAgentSwarmService);
swarm.enter('manual-trigger');          // ← sets meta.modes.swarm = {}
// … launch many sub-agents here …
swarm.exit();                           // ← clears the flag

Inspecting Swarm State in Transcripts

Retrieve the swarm status from any transcript for debugging or analytics:

const tx = await session.transcript();   // returns a TranscriptStore
console.log(tx.getMeta().modes.swarm);   // {} while swarm active, undefined otherwise

Key Source Files

File Purpose
packages/transcript/src/model/meta.ts Defines meta.modes.swarm structure
packages/transcript/src/history/foldFacts.ts Generates swarm enter/exit markers
packages/node-sdk/src/session.ts Public session.swarm() API
packages/node-sdk/src/sdk-rpc-client-v2.ts IAgentSwarmService implementation
packages/kap-server/test/subagentRosterTracker.test.ts Roster tracking verification
packages/agent-core-v2/AGENTS.md v2 engine lifecycle documentation

Summary

  • Swarm mode is a metadata flag (meta.modes.swarm) that signals parallel execution context, not a threading primitive
  • IAgentSwarmService provides enter()/exit() boundaries with automatic cleanup via session.swarm()
  • SubagentRosterTracker maintains independent transcripts for each member without blocking dispatch
  • TaskScheduler achieves true parallelism by executing roster members concurrently through isolated context
  • Transcript markers (swarm.enter/swarm.exit) create observable, debuggable execution windows

Frequently Asked Questions

What is the difference between swarm mode and regular subagent spawning?

Regular session.subagent() calls create isolated agents that execute sequentially unless explicitly awaited in parallel. Swarm mode adds metadata coordination that groups these agents visually and logically, preserves their collective state in the transcript, and signals the scheduler that concurrent execution is expected. The roster tracking in swarm mode also ensures UI components can display live progress for all members.

Does swarm mode create OS-level threads or processes?

No. Kimi-Code's swarm mode operates at the application layer using Node.js's event loop and asynchronous I/O. The parallelism comes from the TaskScheduler dispatching multiple independent execution contexts, not from spawning threads. This design avoids the complexity of shared-memory concurrency while achieving practical parallelism for I/O-bound agent workloads.

How do I know if my subagents are actually running in parallel?

Check your transcript for the swarm.enter and swarm.exit markers, and inspect tx.getMeta().modes.swarm during execution. If the flag is {} while multiple sub-agents have pending tasks in the roster, the scheduler is treating them as parallel candidates. For definitive verification, add logging with timestamps in each sub-agent's skill code and observe overlapping execution periods.

Can swarm mode persist across multiple user turns?

No. The session.swarm() API is designed as a single-turn operation that automatically exits swarm mode when the underlying task completes. This prevents resource leaks and ensures clean billing boundaries. If you need multi-turn parallelism, you must call session.swarm() in each turn or use the lower-level IAgentSwarmService directly with careful manual lifecycle management.

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 →