Understanding SessionManager and AgentRun in Apache Maka: Runtime Execution Architecture
SessionManager and AgentRun in Maka form a two-layer execution architecture where SessionManager provides a stable public façade for session CRUD and message handling, while AgentRun encapsulates durable per-turn execution with guaranteed persistence and recovery semantics.
Apache Maka is an open-source AI agent framework that separates external API stability from internal execution reliability through two core runtime components. Understanding SessionManager and AgentRun in Maka is essential for developers building interactive UI clients, headless bots, or automated testing suites. These components work in concert to ensure every user message results in a reliably persisted, recoverable turn execution.
What Is SessionManager in Maka?
The SessionManager serves as the public entry point and stable façade for all runtime operations. Located in packages/runtime/src/session-manager.ts, this class owns session lifecycle management and delegates turn execution to internal kernel components to maintain API consistency across UI, CLI, and bot integrations.
Session CRUD and Metadata Management
SessionManager handles creation, listing, and updates of sessions through the SessionStore (SQLite persistence). It manages session-level concerns including permission mode updates, sub-agent spawning, and graph operator provisioning, ensuring that session state remains consistent regardless of underlying execution changes.
The sendMessage API
External callers—whether desktop UI, CLI tools, bots, or tests—invoke the thin sendMessage() method. This method validates the session, updates metadata, and forwards the request to RuntimeKernel.startTurn() without exposing internal execution complexity to the caller.
What Is AgentRun in Maka?
The AgentRun class, defined in packages/runtime/src/agent-run.ts, represents a durable execution unit for a single turn. It ensures that runtime facts are recorded reliably and provides mechanisms for graceful shutdown, abort semantics, and crash recovery.
Turn Identification and Context
Each AgentRun instance carries a unique runId, sessionId, and turnId, establishing the execution context. This identification enables precise tracking and auditing of individual agent interactions across distributed systems and supports replay capabilities for debugging.
Event Buffering and Terminal Commitment
AgentRun manages the complete turn lifecycle: starting backend streams, buffering runtime events, flushing partial logs, and committing terminal facts to the AgentRunStore. The settleStopTerminal() method exemplifies this durability by ensuring aborted statuses are persisted atomically even during stop operations.
// In packages/runtime/src/agent-run.ts
public async settleStopTerminal(): Promise<void> {
if (this.terminalClaim?.owner !== 'stop' || this.terminalRunHeaderCommitted) return;
// Ensure durable writes exist
if (!this.input.runtimeEventStore || !this.input.runStore) return;
await this.flushRuntimePartialBuffer(true);
const events = await this.loadTurnRuntimeEvents();
// If any other terminal event already exists, we bail out
if (events.some(e => isTerminalRuntimeEvent(e) && e.id !== this.terminalClaim.event?.id)) return;
// Commit an aborted status as the final terminal fact
const finalStatus = { status: 'aborted' as const };
this.finalStatus ??= finalStatus;
// ...additional commit logic...
}
Architectural Integration: How SessionManager and AgentRun Collaborate
The relationship between these components follows a strict delegation pattern that keeps the public API thin while ensuring execution reliability. According to the Apache Maka source code, the flow operates as follows:
- External caller invokes
SessionManager.sendMessage(sessionId, input)—callers never interact with AgentRun directly. - SessionManager validates the session and delegates to
RuntimeKernel.startTurn(). - RuntimeKernel instantiates an AgentRun to encapsulate the turn's execution context.
- AgentRun drives the
AiSdkBackend, processes model/tool calls, buffers events, and commits terminal facts to persistent storage. - SessionManager updates session state based on AgentRun's reported outcome (completed, aborted, etc.).
This separation provides two critical architectural benefits:
- Thin façade: SessionManager remains stable while internal execution details evolve, allowing UI and bot code to remain unchanged across framework updates.
- Durable turn execution: AgentRun guarantees that each turn's facts are persisted atomically, enabling reliable recovery, replay, and auditing even during system interruptions.
Implementation Examples
The following patterns demonstrate real-world usage of SessionManager and AgentRun in Maka within a desktop host environment:
import { SessionManager } from '@maka/runtime';
import { SQLiteSessionStore } from '@maka/storage';
import { AiSdkBackend } from '@maka/ai-sdk';
// Assemble dependencies
const store = new SQLiteSessionStore({ /* …config… */ });
const backend = new AiSdkBackend({ /* …config… */ });
const manager = new SessionManager({
store,
backends: { default: backend },
newId: () => crypto.randomUUID(),
now: () => Date.now(),
});
// Send a user message – this call goes through SessionManager only
await manager.sendMessage('session-123', {
role: 'user',
content: { type: 'text', text: 'Explain the architecture of Maka.' },
});
Summary
- SessionManager provides the stable public API façade for session management and message entry in
packages/runtime/src/session-manager.ts. - AgentRun encapsulates durable per-turn execution with unique identifiers (
runId,sessionId,turnId) and atomic persistence toAgentRunStore. - The delegation pattern through
RuntimeKernelensures external code remains unchanged during internal execution engine evolution. - AgentRun handles backend streams, event buffering, and terminal commitment including
stop(),settleStopTerminal(), and recovery semantics. - External callers interact exclusively with SessionManager, never directly with AgentRun, maintaining clean architectural boundaries.
Frequently Asked Questions
What is the difference between SessionManager and AgentRun in Maka?
SessionManager is the public façade handling session CRUD and message routing through sendMessage(), while AgentRun is the internal durable execution engine for individual turns. SessionManager manages the "what" (session state and metadata), and AgentRun manages the "how" (turn execution with event buffering and persistence). This separation ensures API stability while allowing execution internals to evolve.
How does Maka ensure reliable turn execution during system interruptions?
AgentRun commits terminal facts atomically to the AgentRunStore even during stop or abort operations. The settleStopTerminal() method in packages/runtime/src/agent-run.ts ensures that partial runtime events are flushed and final statuses are persisted before shutdown, enabling reliable recovery and replay without data loss.
Can developers interact with AgentRun directly when building Maka applications?
No, direct interaction with AgentRun is intentionally encapsulated by the architecture. External callers must use SessionManager's sendMessage() API, which delegates to RuntimeKernel to instantiate and manage AgentRun instances. This abstraction prevents coupling between client code and execution internals, maintaining long-term API compatibility.
Where are SessionManager and AgentRun defined in the Maka source code?
SessionManager is implemented in packages/runtime/src/session-manager.ts and AgentRun in packages/runtime/src/agent-run.ts. Both reside within the @maka/runtime package and depend on storage interfaces like SQLiteSessionStore and AgentRunStore for persistence, as documented in the runtime package README and architecture drafts.
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 →