How SessionManager Orchestrates Agent Sessions in Apache Maka: A Deep Dive into the Runtime Façade

The SessionManager in Apache Maka serves as the public façade of the Maka Runtime, coordinating every aspect of an agent’s lifecycle through SQLite-backed persistence, backend resolution, kernel execution, and atomic child-session orchestration.

The SessionManager acts as the primary entry point for the Maka Runtime, abstracting the complexity of session persistence, backend selection, and turn execution into a unified API. According to the Apache Maka source code, this component manages everything from initial session creation to final compaction, ensuring durable state management while maintaining clean separation between storage, execution, and backend concerns.

Core Architectural Components

The orchestration capabilities of SessionManager rely on a distinct separation of concerns across four primary components. Each component handles a specific domain while the manager coordinates their interactions.

Persistence via SessionStore

Session persistence is handled by the SessionStore interface, with the default implementation using SQLite for durable storage. In packages/runtime/src/session-manager.ts at lines 91-108, the manager delegates all storage operations—such as create(), updateHeader(), and list()—to this store. This abstraction allows the manager to remain agnostic of the underlying storage mechanism while guaranteeing ACID properties for session headers, messages, and configuration data.

Backend Resolution

The SessionManager leverages a BackendRegistry to resolve the correct SDK or backend implementation for each session. As implemented at lines 66-78 in session-manager.ts, the manager calls deps.backends.prepare() to map a durable PersistedBackendKind to a concrete backend factory. This decouples session management from specific AI providers, enabling multi-backend deployments without changing session orchestration logic.

Runtime Execution Kernel

Turn execution is delegated to the RuntimeKernel, which the manager instantiates if not externally supplied (see session-manager.ts lines 28-30). The kernel drives actual turn execution, manages active runs, and performs compaction pipelines. The manager exposes live turn information through methods like runningTurnIds() while the kernel handles the computational heavy lifting.

Session Lifecycle Orchestration

The SessionManager orchestrates agent sessions through a deterministic lifecycle that ensures atomicity and durability at every stage.

Creating New Sessions

New sessions begin with the createSession() method, which initializes a session header via the SessionStore. This operation establishes the session’s identity, backend configuration, and initial metadata before any execution occurs. The manager assigns unique identifiers using the injected newId function and timestamps via the now dependency, ensuring consistent temporal tracking across distributed deployments.

Atomic Child Session Spawning

Child session spawning occurs through spawnChildSession(), implemented with idempotency guarantees to prevent duplicate session creation during network retries. The manager tracks in-flight spawns using internal maps and SpawnChildSessionResult objects (lines 63-94 in session-manager.ts). Once spawned, child sessions maintain a durable link to their parent, enabling hierarchical agent workflows where parent sessions can monitor or coordinate child execution contexts.

Graph Operator Provisioning

For graph-based agent workflows, the manager provides provisionAgentGraphOperator(), which inserts durable graph-operator records that downstream turns can claim. This operation, found at lines 17-25 in session-manager.ts, runs inside a runtime-admission mutation to maintain atomicity. The provisioned operator includes metadata such as graphId, workId, and operatorId, creating a reservation system that prevents race conditions when multiple agents attempt to execute the same graph intent.

Execution and Workspace Management

Beyond lifecycle management, the SessionManager coordinates execution environments and workspace isolation for complex agent deployments.

Running Claimed Intents

The runClaimedAgentGraphIntent() method (lines 31-38 in session-manager.ts) represents the primary execution entry point for verified intent claims. This method:

  • Accepts a pre-verified intent claim from the claim store
  • Optionally executes an admission gate for access control
  • Delegates to the RuntimeKernel for turn execution
  • Records lifecycle events through structured event emission

All execution paths emit events such as ExecutionStarted, PlanApproved, and ExecutionFailed via onContinuationLifecycleEvent, enabling external telemetry without blocking runtime correctness.

Workspace Isolation and Artifact Publishing

For agents utilizing worktree workspaces, the manager provisions isolated filesystem contexts through worktreeChildExecutor and captures patches after terminal runs. The finalizeChildWorkspacePatches() method (lines 89-115 in session-manager.ts) handles workspace cleanup and publishes patch artifacts, ensuring that agent file system mutations are captured as durable outputs rather than ephemeral side effects.

Maintenance and Compaction

Long-running sessions require periodic maintenance to prevent unbounded storage growth. The SessionManager exposes compactSession() and preflightContextCompaction() (lines 45-50 in session-manager.ts) to trigger the kernel’s compaction pipeline. These methods prune obsolete events, compact conversation history, and maintain ledger efficiency without disrupting active execution contexts.

Implementation Examples

The following examples demonstrate practical usage patterns for the SessionManager façade:

// Initialize the SessionManager with required dependencies
import { SessionManager } from '@maka/runtime';
import { SQLiteSessionStore } from '@maka/storage';

const manager = new SessionManager({
  store: new SQLiteSessionStore(),
  backends: new BackendRegistry(),
  newId: () => crypto.randomUUID(),
  now: () => Date.now(),
  runtimeKernel: new RuntimeKernel({ /* runtime dependencies */ }),
});
// Create a new top-level agent session
const summary = await manager.createSession({
  name: 'Data Analysis Agent',
  backend: { kind: 'ai_sdk', version: 1 },
});
console.log('Session created:', summary.id);
// Provision a graph-operator for hierarchical agent workflows
await manager.provisionAgentGraphOperator({
  graphId: 'graph-123',
  workId: 'work-alpha',
  operatorId: 'operator-42',
  source: { sessionId: summary.id, runId: 'run-1', turnId: 'turn-1' },
  edges: [],
  expectedScheduleRevision: 0,
});
// Spawn a linked child session with idempotency guarantees
const childResult = await manager.spawnChildSession(summary.id, {
  spawnedBy: { spawnedBy: 'user' },
  agentProfile: 'child-analyzer',
  prompt: 'Analyze the quarterly revenue trends from the provided dataset.',
});
console.log('Child session ID:', childResult.childSessionId);
// Execute a claimed intent through the runtime kernel
await manager.runClaimedAgentGraphIntent({
  claimStore: claimStore,
  intent: runnableIntent,
  graphId: 'graph-123',
  intentId: 'intent-7',
  prompt: 'Generate executive summary of findings.',
});
// Compact session history to optimize storage
for await (const event of manager.compactSession(summary.id)) {
  console.log('Compaction event:', event.type);
}

Summary

  • The SessionManager acts as the public façade of the Maka Runtime, coordinating persistence, backend selection, and execution through the SessionStore, BackendRegistry, and RuntimeKernel components.
  • Session lifecycle management includes atomic creation, idempotent child-session spawning via spawnChildSession(), and durable graph-operator provisioning through provisionAgentGraphOperator().
  • Execution orchestration delegates to the RuntimeKernel while the manager handles admission gates, workspace isolation for worktree agents, and artifact publishing.
  • Maintenance operations such as compactSession() prune obsolete events and maintain ledger efficiency without disrupting active runs.
  • All operations emit structured lifecycle events (ExecutionStarted, ExecutionFailed, etc.) enabling external observability through onContinuationLifecycleEvent.

Frequently Asked Questions

What is the role of SessionManager in Apache Maka?

The SessionManager serves as the primary public API for the Maka Runtime, responsible for orchestrating the complete lifecycle of agent sessions from creation through execution to compaction. According to the source code in packages/runtime/src/session-manager.ts, it coordinates between the SessionStore for persistence, the BackendRegistry for backend resolution, and the RuntimeKernel for actual execution, providing a unified façade that hides implementation complexity from consumers.

How does SessionManager handle child sessions?

Child sessions are spawned atomically through the spawnChildSession() method, which guarantees idempotency to prevent duplicate sessions during retry scenarios. The manager tracks in-flight spawns using internal maps and SpawnChildSessionResult objects, maintaining durable links between parent and child sessions as implemented in session-manager.ts lines 63-94. This enables hierarchical agent workflows where parent sessions can monitor or coordinate child execution contexts.

What is the difference between SessionStore and RuntimeKernel?

The SessionStore handles durable persistence of session headers, messages, and configuration—typically backed by SQLite—while the RuntimeKernel manages the actual computational execution of agent turns. The SessionManager uses the store for CRUD operations at lines 91-108 of session-manager.ts, whereas the kernel is instantiated at lines 28-30 to drive turn execution and manage active runs. This separation ensures that storage concerns remain independent of execution logic.

How does SessionManager ensure data durability?

Durability is achieved through multiple mechanisms: the SessionStore provides ACID guarantees for all session metadata, graph-operator provisioning uses runtime-admission mutations to maintain atomicity (lines 17-25), and child-session spawning includes idempotency checks to prevent state corruption during retries. Additionally, the compactSession() method (lines 45-50) ensures long-term storage efficiency without losing critical execution history.

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 →