SessionManager in Maka: Core Responsibilities and Runtime Architecture
The SessionManager in Apache Maka serves as the core public façade of the Runtime, orchestrating persistence, sandboxing, and backend communication while providing a unified API for session lifecycle management, turn handling, and recovery operations.
In the apache/maka repository, the SessionManager acts as the central orchestrator that stitches together storage, execution boundaries, and model backends. This critical component exposes a clean, version-controlled API to desktop clients, TUIs, and CLIs while internally coordinating SQLite persistence, LLM adapter activation, and sandbox enforcement. Understanding the SessionManager's responsibilities is essential for developers extending Maka's runtime capabilities or debugging session-related issues.
Core Architecture: The Three-Pillar Design
The SessionManager integrates three essential components defined in packages/runtime/src/session-manager.ts:
- SessionStore – A SQLite-backed persistence layer that manages the session header, messages, and turn records.
- AgentBackend – The model-SDK adapter (such as
AiSdkBackend) that communicates with LLM providers. - ExecutionBoundary – The sandbox that enforces what the agent is allowed to do during a turn.
This architecture allows the SessionManager to present a unified interface while delegating specialized operations to dedicated subsystems.
Session Lifecycle Management
The SessionManager handles complete session lifecycle operations including creation, listing, renaming, and deletion. The createSession() method in packages/runtime/src/session-manager.ts initializes new sessions with specified backends and permission modes.
Beyond basic CRUD operations, the manager exposes live run state via the RuntimeKernel and projects "running" turn IDs onto session summaries through the private #projectLiveRunState() method. This projection ensures that clients receive real-time visibility into active computation states.
Turn Handling and Message Retrieval
At the turn level, the SessionManager provides APIs that interface directly with the persistence layer. Methods such as listTurns(), getMessages(), and listShellRunUpdates() read from both the SessionStore and the optional RuntimeEventStore.
These operations allow external interfaces to reconstruct conversation history and monitor shell execution updates without direct database access, maintaining clean separation between storage internals and public APIs.
Configuration Management and Safety Enforcement
Session configuration changes flow through transitionSessionConfiguration(), which validates updates to backends, permission modes, collaboration settings, and workspace locations. The implementation uses VersionedSessionHeader for optimistic concurrency checks, preventing conflicting modifications when multiple clients interact with the same session.
Safety enforcement occurs through permission-mode guards and interaction-authority checks defined in the SessionManagerInteractionDeps interface, ensuring that tool usage requests and user interactions respect configured boundaries.
Advanced Orchestration Capabilities
Child-Session Management
The SessionManager supports hierarchical agent structures through spawnChildSession() and provisionChildWorkspace(). These methods create "sub-agent" sessions with dedicated work-tree workspaces and resolved tool sets. The manager tracks pending spawns to prevent duplicate provisioning operations.
Graph-Intent Execution
For claimed Agent-Graph intents, runClaimedAgentGraphIntent() handles host-side admission, safety checks, and lifecycle callbacks. This method bridges high-level intent declarations with actual runtime execution.
Runtime Recovery
When crashes occur, runtimeLedgerRepair() enables event replay and ledger reconstruction. Working with RuntimeLedgerRepair, the manager restores sessions to consistent states by replaying persisted events from the storage layer.
Backend Registry Integration
Through BackendRegistry, the SessionManager registers, prepares, and disposes of backend factories. The refreshIdleBackends() method maintains backend health by cycling idle connections, ensuring that LLM adapters remain responsive without resource leakage.
Working with SessionManager: Code Examples
// Create a new session with specific backend and permissions
const summary = await manager.createSession({
name: 'My first session',
backend: { kind: 'ai_sdk', model: 'gpt-4' },
permissionMode: 'explore',
});
// List all sessions with live turn projection
const sessions = await manager.listSessions();
// Safely update permission mode with optimistic concurrency
await manager.transitionSessionConfiguration(sessionId, {
expectedRevision: currentRevision,
clearConnectionBlock: false,
configuration: {
permissionMode: 'edit',
},
});
// Spawn a child sub-agent session
const childResult = await manager.spawnChildSession({
spawnedBy: { /* parent session reference */ },
agentProfile: myAgentProfile,
prompt: 'Summarize the above conversation',
onEvent: (ev) => console.log('Child event:', ev),
});
Summary
- The SessionManager in Apache Maka serves as the primary public façade for all runtime operations, coordinating between persistence, sandboxing, and model backends.
- It manages the complete session lifecycle including creation, configuration updates, and real-time state projection through methods like
createSession()and#projectLiveRunState(). - Turn-level operations such as
listTurns()andgetMessages()abstract database access while maintaining data consistency viaSessionStore. - Safety and concurrency are enforced through
transitionSessionConfiguration()usingVersionedSessionHeaderfor optimistic locking. - Advanced features include child-session orchestration via
spawnChildSession(), graph-intent execution throughrunClaimedAgentGraphIntent(), and crash recovery usingruntimeLedgerRepair(). - Backend lifecycle management flows through
BackendRegistryandrefreshIdleBackends()to maintain healthy LLM provider connections.
Frequently Asked Questions
What are the three main components orchestrated by SessionManager in Maka?
The SessionManager coordinates the SessionStore (SQLite persistence), AgentBackend (model SDK adapter), and ExecutionBoundary (permission sandbox). These components are wired together in packages/runtime/src/session-manager.ts to provide a unified runtime interface.
How does SessionManager prevent configuration conflicts during concurrent updates?
The manager implements optimistic concurrency control through VersionedSessionHeader checks within transitionSessionConfiguration(). When updating session parameters like permission modes or backend settings, clients must provide an expectedRevision. If the stored revision differs, the operation fails, forcing clients to refresh and retry.
What distinguishes child-session orchestration from regular session management?
Child sessions created via spawnChildSession() and provisionChildWorkspace() represent sub-agent contexts with isolated work-tree workspaces and tool sets. The SessionManager tracks pending spawns to prevent duplicate work and handles the parent-child relationship resolution required for hierarchical agent delegation.
How does SessionManager recover from runtime crashes?
Through runtimeLedgerRepair(), the manager replays persisted events from the SessionStore to rebuild the runtime ledger. This repair process reconstructs session state by reapplying historical operations, ensuring consistency even after unexpected termination.
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 →