# Session Seed Mechanism in agent-core-v2: How Kimi Code Initializes Session Scopes

> Understand the session seed mechanism in agent-core-v2. Discover how Kimi Code initializes session scopes with context data and workspace adapters.

- Repository: [Moonshot AI/kimi-code](https://github.com/MoonshotAI/kimi-code)
- Tags: internals
- Published: 2026-08-13

---

**The session seed mechanism pre-populates newly created Session scopes with immutable context data and live workspace adapters before any on-demand service factories execute.**

In the MoonshotAI/kimi-code repository, the `agent-core-v2` package implements a sophisticated Dependency Injection (DI) container that uses the session seed mechanism to bridge workspace-level resources and isolated session contexts. This deterministic initialization pattern ensures every Session scope receives both static configuration and dynamic, live-updating service adapters at creation time.

## What Is a Session Seed?

A **session seed** is a `ScopeSeed`—an array of `[ServiceIdentifier, value]` tuples passed to a child scope when it is instantiated. The container uses these tuples to `provide` services immediately, before any lazy factories run.

In `agent-core-v2`, seeds compose two distinct layers:

1. Immutable session metadata (IDs, directories, working paths)
2. Live adapters that project mutable workspace data into the session scope

This design allows sessions to maintain isolation while remaining synchronized with shared workspace state.

## Core Components of the Session Seed

### Session Context: Immutable Facts

The foundation of every session seed is the `ISessionContext` object, which carries immutable facts about the session's identity and filesystem locations.

In [`packages/agent-core-v2/src/session/sessionContext/sessionContext.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core-v2/src/session/sessionContext/sessionContext.ts), the `sessionContextSeed` helper factory creates the initial seed entry:

```ts
export function sessionContextSeed(ctx: ISessionContext): ScopeSeed {
  return [[ISessionContext as ServiceIdentifier<unknown>, ctx]];
}

```

This function returns a single-element array containing the `ISessionContext` token bound to the provided context object. The context includes properties like `sessionId`, `workspaceId`, `sessionDir`, `sessionScope`, `metaScope`, and `cwd`.

### Workspace-to-Session Adapters: Dynamic Data

Beyond static context, the seed includes five adapter services that expose workspace resources as session-scoped tokens. Each adapter registers an **`ISession*`** service identifier and forwards live updates from the workspace:

- `ISessionSkillCatalogData`
- `ISessionInstructionsProvider`
- `ISessionMcpHandle`
- `ISessionWorkspaceInfo`
- `ISessionToolPolicyGate`

In [`packages/agent-core-v2/src/session/sessionSeed/sessionSeedAdapters.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core-v2/src/session/sessionSeed/sessionSeedAdapters.ts), the `SessionSkillCatalogDataAdapter` demonstrates this pattern:

```ts
export class SessionSkillCatalogDataAdapter extends Service {
  constructor(
    @IInstantiationService instantiation: IInstantiationService,
    @ref(IWorkspaceSkillCatalog) upstream: LiveRef<IWorkspaceSkillCatalog>,
  ) {
    super();
    if (upstream.current === undefined) return;
    const change = this._register(new Emitter<string>());
    let backing = upstream.current.sessionData();
    // ... initialization logic ...
    const data: ISessionSkillCatalogData = { /* ... */ };
    instantiation.provide(ISessionSkillCatalogData, data);
  }
}

```

These adapters subscribe to workspace-level `onDidChange` events and propagate updates to the session scope, ensuring the session always accesses current data without recreating services.

## Installing Session Seed Adapters

The `installSessionSeedAdapters` function binds the adapter lifecycle to the session container. Called during the Session's container configuration (`configureContainer` hook), this function constructs each adapter and anchors its disposal to the session container's ledger.

From [`packages/agent-core-v2/src/session/sessionSeed/sessionSeedAdapters.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core-v2/src/session/sessionSeed/sessionSeedAdapters.ts) (lines 66-73):

```ts
export function installSessionSeedAdapters(container: InstantiationService): void {
  for (const recipe of SESSION_SEED_ADAPTERS) {
    const adapter = container.fiberHost.constructService(recipe, undefined) as Partial<IDisposable>;
    container.anchorKernelEntry(() => {
      adapter.dispose?.();
    }, `sessionSeed:${recipe.name}`);
  }
}

```

This registration guarantees that disposing the session automatically disposes all seeded adapters, preventing memory leaks and ensuring proper cleanup of event listeners.

## Composite Seed Construction and Usage

When creating a Session scope, the host combines `sessionContextSeed` and `installSessionSeedAdapters` to form a composite seed. This seed is passed as the third argument to `host.child(LifecycleScope.Session, ...)`.

The test suite in [`packages/agent-core-v2/test/session/sessionLog/sessionLogService.test.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core-v2/test/session/sessionLog/sessionLogService.test.ts) demonstrates this pattern (lines 62-74):

```ts
function testSessionSeed() {
  return [
    ...sessionContextSeed(makeSessionContext({
      sessionId: 's1',
      workspaceId: 'test-workspace',
      sessionDir,
      sessionScope: 'sessions/test-workspace/s1',
      metaScope: 'sessions/test-workspace/s1/session-meta',
      cwd: sessionDir,
    })),
    [IWorkspaceStateService, new WorkspaceStateService()] as const,
  ];
}

const host = buildHost();
const session = host.child(LifecycleScope.Session, 's1', testSessionSeed());

```

In production code, the `SessionLifecycleService` orchestrates this process, ensuring the composite seed contains both the immutable context and the five live adapters before the session begins processing requests.

## Why the Session Seed Mechanism Matters

The session seed mechanism in `agent-core-v2` provides three critical architectural benefits:

- **Live Data Propagation**: Adapters forward `onDidChange` events from workspace services, allowing sessions to react to skill catalog updates or policy changes without polling or service recreation.
- **Scope Isolation**: Each Session receives its own `ISessionMcpHandle` and other session-scoped tokens, preventing cross-session contamination while maintaining access to shared workspace resources.
- **Lifecycle Safety**: By anchoring adapter disposal to the session container via `anchorKernelEntry`, the system guarantees automatic cleanup when a session terminates, regardless of how the termination occurs.

## Summary

- The **session seed mechanism** initializes Session scopes using `ScopeSeed` tuples that pre-populate the DI container with required services.
- **Immutable context** is injected via `sessionContextSeed` in [`sessionContext.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/sessionContext.ts), providing session IDs and directory paths.
- **Live adapters** in [`sessionSeedAdapters.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/sessionSeedAdapters.ts) project workspace data into session-scoped tokens (`ISessionSkillCatalogData`, etc.) and forward update events.
- The **`installSessionSeedAdapters`** function anchors adapter lifecycles to the session container, ensuring automatic disposal.
- Seeds are passed to **`host.child(LifecycleScope.Session, id, seed)`** to create fully initialized, isolated session scopes.

## Frequently Asked Questions

### How does the session seed mechanism differ from standard DI container initialization?

Standard DI containers typically resolve services on demand through factory functions. The session seed mechanism pre-populates the container with concrete instances before any resolution occurs, ensuring that critical context and live data adapters exist immediately when the session scope starts. This "seed then resolve" pattern eliminates race conditions and guarantees that workspace-to-session adapters are active before any session logic executes.

### What happens if a workspace service changes after a session is seeded?

The adapter pattern handles live updates automatically. Each adapter (such as `SessionSkillCatalogDataAdapter`) maintains a reference to the upstream workspace service and forwards `onDidChange` events to the session-scoped token. When the underlying workspace data changes, the adapter updates the session's view without requiring the session to re-fetch or recreate the service, maintaining both isolation and synchronization.

### Can custom services be added to the session seed?

Yes. The `ScopeSeed` type accepts any `[ServiceIdentifier, value]` tuple. When constructing a session, you can spread the standard seed (`...sessionContextSeed(ctx)`) and append additional service tuples, as shown in the test examples. However, production code typically relies on the standard `SESSION_SEED_ADAPTERS` array to ensure consistency across the `agent-core-v2` architecture.

### Where is the session seed mechanism invoked during session creation?

The `SessionLifecycleService` (located in [`packages/agent-core-v2/src/workspace/sessionLifecycle/sessionLifecycleService.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core-v2/src/workspace/sessionLifecycle/sessionLifecycleService.ts)) orchestrates session creation. It calls `installSessionSeedAdapters` during the `configureContainer` hook, which executes before the session scope becomes active. This ensures the composite seed is fully populated before any session-scoped service resolution begins.