How Maka's SessionManager Manages Session Lifecycles and Turn Execution
Maka's SessionManager serves as the public façade for all runtime-level session operations, mediating between persistent storage, AI backends, and sandboxed execution boundaries to coordinate session lifecycles and drive turn-by-turn execution.
The SessionManager in Apache Maka is the central orchestrator that transforms static session headers into live, executing conversations. According to the Maka source code, this class wires together three core dependencies—SessionStore for persistence, AgentBackend for AI SDK integration, and ExecutionBoundary for security enforcement—while delegating actual turn execution to an internal RuntimeKernel. This article examines how these components collaborate to create, configure, and run sessions atomically and securely.
Understanding the SessionManager Architecture
The SessionManager is instantiated with a dependency bundle that includes:
| Component | Responsibility |
|---|---|
| SessionStore | Persists session headers, messages, and turn records durably |
| AgentBackend | Runs agent code (e.g., AiSdkBackend) |
| ExecutionBoundary | Enforces permission modes and security constraints |
| RuntimeKernel | Drives the turn-by-turn execution engine (constructed internally) |
These dependencies are wired together in the class constructor, establishing the foundation for all lifecycle operations. The kernel maintains an in-memory view of active runs, enabling the manager to present "live" status even when the persistent header only reflects state after turn completion.
Session Lifecycle Management
Creating Sessions
The entry point for new sessions is SessionManager#createSession (lines 2480–2482 in packages/runtime/src/session-manager.ts). This method delegates to SessionStore.create to generate a fresh SessionHeader, then returns a summarized view:
import { SessionManager } from '@maka/runtime';
const manager = new SessionManager(deps);
const summary = await manager.createSession({
name: 'Data Analysis Session',
backend: 'ai_sdk',
permissionMode: 'explore',
// additional CreateSessionInput fields
});
console.log('Created session:', summary.id);
Querying Active Sessions
To list sessions with live execution status, SessionManager#listSessions (lines 1010–1012) enriches persisted data with runtime information:
const sessions = await manager.listSessions();
for (const s of sessions) {
console.log(
`${s.id}: ${s.name} – running turns: ${s.runningTurnIds?.join(', ') ?? 'none'}`
);
}
The runningTurnIds projection comes from SessionManager#runningTurnIds (lines 998–1000), which queries the RuntimeKernel for active turn IDs per session.
Configuration and Maintenance Operations
| Operation | Method | Key Behavior |
|---|---|---|
| Rename session | store.rename |
Thin wrapper forwarding to SessionStore |
| Flag/unflag session | store.setFlagged |
Persistent boolean marker |
| Remove session | store.remove |
Hard deletion of session record |
| Transition configuration | transitionSessionConfiguration (lines 1060–1095) |
Atomic update of permission mode, collaboration mode, labels with conflict detection for "waiting_for_user" states |
| Relocate workspace | relocateSessionWorkspace (lines 1153–1190) |
Moves working directory after confirming session quiescence |
Stopping Sessions
Graceful shutdown is handled by SessionManager#stopSession (lines 254–259), which accepts an optional BackendStopMode:
await manager.stopSession({ source: 'stop_button', mode: 'graceful' });
Turn Execution: Running Claimed Graph Intents
A turn represents the atomic unit of interaction: user message → agent run → RuntimeEvent stream. The primary entry point is runClaimedAgentGraphIntent, which implements a five-phase validation and execution protocol.
Phase 1: Host Capability Validation
In hosted deployments, the method verifies that a trusted RuntimeHostedAgentGraphExecutionCapability is available (lines 2489–2495):
const hosted = isRuntimeHostedRootAuthority(this.deps.messageAuthority);
const hostedGraphExecution = hosted ? this.deps.hostedAgentGraphExecution : undefined;
if (hosted && !hostedGraphExecution) {
throw new RuntimeMessageAuthorityInvariantError(...);
}
Phase 2-4: Claim Resolution and Verification
The method fetches the durable claim from either the host capability or caller-supplied claimStore, decodes it, validates IDs, and builds a resolved execution context (lines 2499–2519):
const storedClaim = await (hostedGraphExecution ?? input.claimStore)
.readAgentGraphIntentClaim(input.graphId, input.intentId);
// ... decoding, verification, intent validation ...
const resolved: ResolvedClaimedAgentGraphIntentInput = {
// admitExecution gate, abort signal, callbacks
onReady: ({ turnId, runId }) => console.log('Turn started', turnId, runId),
onEvent: (ev) => console.log('Event:', ev.type),
};
Phase 5: Kernel Delegation
The heavy execution lifts to RuntimeKernel.runClaimedAgentGraphIntentOnce (~line 2565), which:
- Allocates turn ID — generates
newIdand records start event - Invokes backend — runs
AgentBackendwith prompt, tools, and permission mode - Captures events — writes each
RuntimeEventtoRuntimeEventStoreand mirrors to session messages viastore.appendMessage - Commits turn — finalizes status, updates
SessionHeader, emitsCompleteEvent
Complete Turn Execution Example
const result = await manager.runClaimedAgentGraphIntent({
claimStore, // implements readAgentGraphIntentClaim()
intent: myIntent, // AgentGraphRunnableIntent
graphId: 'my-graph',
intentId: 'intent-123',
prompt: 'Explain the diagram.',
onReady: ({ turnId, runId }) => console.log('Started:', turnId),
onEvent: (ev) => handleEvent(ev),
});
console.log('Completed:', result.summary);
The kernel maintains per-session turn queues, enabling concurrent execution across multiple sessions without blocking.
Core Implementation Files
| File | Purpose |
|---|---|
packages/runtime/src/session-manager.ts |
Public API for creation, configuration, turn execution, cleanup |
packages/runtime/src/runtime-kernel.ts |
Turn queue, backend activation, event recording |
packages/runtime/src/runtime-read-model.ts |
Session state projections, headerToSummary utilities |
packages/runtime/src/stream-graph-admission.ts |
Graph intent fingerprinting and admission verification |
packages/runtime/src/agent-catalog.ts |
Sub-agent definitions and graph operator provisioning |
Summary
- SessionManager acts as façade — coordinates
SessionStore,AgentBackend, andExecutionBoundarywithout direct persistence or execution logic - Lifecycle operations delegate — creation, listing, configuration changes, and termination all forward to specialized subsystems
- Turn execution is claim-based —
runClaimedAgentGraphIntentvalidates durable claims before streaming execution throughRuntimeKernel - RuntimeKernel maintains live state — in-memory turn tracking enables real-time status without premature persistence writes
- Per-session queuing enables concurrency — multiple sessions execute turns simultaneously without cross-session blocking
Frequently Asked Questions
What is the difference between SessionStore and SessionManager?
SessionStore handles durable persistence of session headers, messages, and turn records. SessionManager is the public API façade that coordinates SessionStore with runtime concerns—adding live execution status, validating configuration transitions, and orchestrating turn execution through the RuntimeKernel.
How does Maka ensure turn execution security?
Turns execute through claimed graph intents—durable, pre-recorded execution plans verified via stream-graph-admission.ts before any backend invocation. Hosted deployments additionally require RuntimeHostedAgentGraphExecutionCapability validation. The ExecutionBoundary enforces permission modes throughout.
Can multiple turns run simultaneously in one session?
The RuntimeKernel maintains a per-session turn queue, serializing turns within a single session while allowing concurrent execution across different sessions. This prevents race conditions on session state while maximizing overall throughput.
What happens when a session configuration conflicts with active execution?
transitionSessionConfiguration (lines 1060–1095) performs atomic conflict detection—for example, rejecting permission mode changes when the session status is waiting_for_user. The method returns errors rather than allowing inconsistent state transitions.
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 →