How the SessionManager Works in Apache Maka: Complete Runtime Architecture
The SessionManager serves as Apache Maka's central runtime orchestrator, managing session lifecycles, provisioning graph operators for agent execution, coordinating intent claims, and enforcing role-based permissions while delegating heavy processing to specialized storage and coordination layers.
The SessionManager is the authoritative runtime component in the Apache Maka framework that governs every unit of work—from agent conversations to tool-execution graphs. Located in packages/runtime/src/session-manager.ts, this core facade coordinates session creation, validates identifiers, publishes events, and delegates heavy processing to the Stream Graph Coordinator and storage backends.
Core Responsibilities of the SessionManager
Public Runtime Facade
The SessionManager exposes a clean API surface that the rest of the system and external callers consume. Key methods include createSession for initialization, runClaimedAgentGraphIntent for execution, and stopSession for termination. This design maintains a thin facade while heavy lifting—such as graph traversal and tool execution—is delegated to specialized collaborators.
Session Creation and ID Management
Around lines 900-950 in session-manager.ts, the manager generates unique session identifiers and validates them through assertSafeSessionId. It records session metadata including parent/child relationships and role scopes, ensuring that every session maintains proper lineage and isolation boundaries. The implementation supports hierarchical session structures where sub-agents operate within scoped contexts derived from parent sessions.
Graph Operator Provisioning
The provisionAgentGraphOperator method supplies a thin wrapper around agent graphs that the Stream Graph Coordinator consumes to drive execution. This operator provisioning occurs in packages/runtime/src/session-manager.ts and is referenced from packages/runtime/src/stream-graph-coordinator.ts. By separating operator creation from execution logic, the manager maintains its role as a state coordinator rather than an execution engine.
Intent Claim and Execution
Between lines 1000-1200, the SessionManager handles the claim-repair saga for graph intents. When a session claims a graph intent, the manager validates the claim through internal state checks, then executes via runClaimedAgentGraphIntent. This method orchestrates the transition from intent description to actual agent graph operation, ensuring that only valid, claimed intents proceed to execution.
Graceful Shutdown and Resource Cleanup
The stopSession method (lines 1300-1350) terminates sessions, cleans up resources, and notifies dependent components such as the internal AsyncQueue. This ensures that event listeners and pending operations receive proper termination signals, preventing resource leaks and maintaining system stability during scale-down operations.
Permission and Role Enforcement
The manager enforces read/write permissions by integrating with packages/storage/src/sqlite-session-role-scope.ts. It works with session-role stores to validate access rights, particularly for sub-agents requiring isolated scopes. This enforcement happens at session creation boundaries and during intent execution to maintain security invariants.
Recovery and Event Publishing
At lines 4600-4700, recovery logic reproduces exact session headers after system crashes, patching runtime state to maintain consistency. The manager publishes session-level events (creation, mutation, termination) using the internal AsyncQueue from packages/runtime/src/async-queue.ts, draining events in order to packages/storage/src/task-ledger-store.ts. This ensures UI components and observers maintain synchronization with runtime state.
Key Source Files and Collaborators
Understanding the SessionManager requires familiarity with its primary collaborators across the Maka codebase:
-
packages/runtime/src/session-manager.ts– Contains the core implementation includingcreateSession,runClaimedAgentGraphIntent, andstopSessionmethods. -
packages/runtime/src/stream-graph-coordinator.ts– Coordinates graph execution and relies on the SessionManager for operator provisioning viaprovisionAgentGraphOperator. -
packages/runtime/src/async-queue.ts– Provides the ordered async iterator used by the manager to drain session events. -
packages/storage/src/sqlite-session-role-scope.ts– Stores and enforces role-based access controls that the SessionManager queries during permission checks. -
packages/storage/src/sqlite-session-metadata-store.ts– Persists session headers and patches that the manager reads during recovery and writes during state transitions. -
packages/storage/src/task-ledger-store.ts– Maintains the ordered ledger of session events that the manager publishes to. -
packages/runtime/src/__tests__/session-manager.test.ts– Demonstrates the API contract and edge-case handling for the manager's public interface.
Working with the SessionManager API
Initializing the Manager
Create a SessionManager instance by supplying dependencies that satisfy the SessionManagerDeps interface:
import { SessionManager } from '@maka/runtime';
import { createInMemoryStore } from '@maka/storage';
const store = createInMemoryStore();
const manager = new SessionManager({
store,
backends: [], // LLM backend factories
newId: () => crypto.randomUUID(),
now: () => Date.now(),
// Additional dependencies: permission checks, logging, etc.
});
Creating and Managing Sessions
Generate new sessions with optional parent relationships and metadata:
const sessionId = await manager.createSession({
parentSessionId: undefined, // Optional: for hierarchical sessions
// Additional metadata: role, scope, etc.
});
// Use sessionId to drive agent graphs
Provisioning Graph Operators
Supply graph definitions to obtain an operator for the Stream Graph Coordinator:
const operator = manager.provisionAgentGraphOperator({
sessionId,
graphDefinition, // Agents, tools, and edges definition
});
Executing Claimed Intents
Run high-level intents through the claim-repair saga:
const intent = {
type: 'run',
target: 'someTool',
args: { foo: 'bar' },
};
await manager.runClaimedAgentGraphIntent({
sessionId,
intent,
});
Graceful Shutdown
Terminate sessions cleanly to trigger resource cleanup:
await manager.stopSession({ sessionId });
Subscribing to Lifecycle Events
Observe session events for UI synchronization or logging:
manager.subscribeSessionEvents((event) => {
console.log('Session event:', event);
});
Summary
- The SessionManager in
packages/runtime/src/session-manager.tsacts as the single source of truth for session state and coordination. - Graph execution is delegated to the Stream Graph Coordinator via
provisionAgentGraphOperator, keeping the manager thin. - Session identifiers are validated through
assertSafeSessionIdand tracked with parent/child lineage (lines 900-950). - Intent execution follows a claim-repair pattern handled by
runClaimedAgentGraphIntentbetween lines 1000-1200. - Role-based permissions are enforced through integration with
sqlite-session-role-scope.tsfor scoped access control. - Crash recovery logic at lines 4600-4700 reproduces exact session headers from persistent storage.
- Event ordering is maintained through the internal AsyncQueue and persisted to
task-ledger-store.tsfor observer synchronization.
Frequently Asked Questions
How does SessionManager validate session identifiers?
The implementation uses the internal assertSafeSessionId method located around lines 900-950 to validate uniqueness and safety constraints before recording metadata. This validation ensures that session IDs meet formatting requirements and do not collide with existing active sessions in the metadata store.
What is the relationship between SessionManager and the Stream Graph Coordinator?
The SessionManager provisions graph operators through provisionAgentGraphOperator, which returns a thin wrapper consumed by the Stream Graph Coordinator in packages/runtime/src/stream-graph-coordinator.ts. This separation of concerns allows the manager to handle state and permissions while the coordinator manages actual agent execution and graph traversal.
How does SessionManager handle system crashes?
Recovery mechanisms at lines 4600-4700 reproduce the exact session header from sqlite-session-metadata-store.ts and patch runtime state to maintain consistency. The manager restores session metadata, role scopes, and pending intents to resume operations without losing the conversational or execution context.
How are session events propagated to external observers?
The manager publishes lifecycle events (creation, mutation, termination) via subscribeSessionEvents, which interfaces with the internal AsyncQueue from packages/runtime/src/async-queue.ts. Events drain in order and persist to task-ledger-store.ts, ensuring that UI components and logging systems receive deterministic, ordered updates.
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 →