SessionManager Responsibilities in Apache Maka: A Complete Guide to Session Lifecycle and Runtime Coordination
The SessionManager serves as the public façade of Maka’s Runtime and the central coordinator for all session-related operations, managing everything from creation and persistence to live turn tracking, workspace relocation, and sub-agent provisioning.
Apache Maka’s SessionManager responsibilities bridge persistent storage and live execution environments, acting as the single source of truth for agent workspaces. Located in packages/runtime/src/session-manager.ts, this component wraps the SessionStore (SQLite persistence) and augments stored data with the live state kept by RuntimeKernel. Whether you are terminating sessions, updating backend configurations, or spawning isolated child agents, the SessionManager orchestrates these operations while maintaining atomicity and consistency.
Core SessionManager Responsibilities
Session Lifecycle Management
The SessionManager handles the complete lifecycle of a workspace, including create, list, rename, remove, and retrieval operations. In packages/runtime/src/session-manager.ts, the createSession method (lines 38‑44) initializes new session headers, while listSessions (lines 72‑74) provides paginated access to existing workspaces with their current metadata. This lifecycle management persists data through the SessionStore interface while maintaining in-memory references for active sessions.
Running-Turn Tracking and Live State
To expose which turns are currently executing, the SessionManager queries RuntimeKernel for in-memory turn IDs via runningTurnIds (lines 59‑61). This responsibility allows external observers and UI components to distinguish between idle sessions and those actively processing agent operations, providing real-time visibility into runtime state without directly accessing the kernel’s internal execution queues.
Safe Configuration Transitions
The transitionSessionConfiguration method (lines 44‑85) enables atomic updates to backend settings, model selections, and permission modes. This responsibility includes revision validation using versioned headers to prevent conflicting updates, optional execution boundary adjustments, and conflict resolution when configuration changes occur during active runs. The method ensures that updates to the PersistedBackendKind or model parameters maintain session integrity.
Workspace Relocation
When sessions need to move between working directories or project IDs, the relocateSessionWorkspace method (lines 27‑80) manages the migration without disrupting active runs. This involves ensuring a quiescent state, disposing backend caches through the BackendRegistry, and recreating session headers with updated paths. The SessionManager prevents data loss during relocation by coordinating with both the storage layer and the runtime host.
Child Session and Sub-Agent Handling
The SessionManager provisions isolated workspaces for sub-agents through provisionChildWorkspace (lines 81‑95) and related helpers like ensureChildWorkspace and finalizeChildWorkspacePatches. These responsibilities support Maka’s multi-agent architecture by creating child sessions that run in isolated worktrees, spawned via spawnChildSession with specific agentProfile configurations and parent-child relationship tracking.
Graph-Operator Provisioning and Intent Execution
For graph-based agent execution, the SessionManager exposes APIs including provisionAgentGraphOperator and runClaimedAgentGraphIntent. These methods forward execution requests to the backend via BackendRegistry and enforce fingerprint verification for security. The type definitions for ProvisionAgentGraphOperatorInput (lines 51‑60) and RunClaimedAgentGraphIntentInput (lines 66‑78) define the contracts for these operations.
Session Stopping and Termination
The SessionManager handles termination requests from multiple sources through stopSession, accepting both UI-initiated stops (via the stop button) and backend-initiated stops from WorkHub actions. The StopSessionInput type (lines 65‑74) supports both graceful and force modes, allowing the manager to coordinate shutdown sequences that respect ongoing turn executions or terminate them immediately based on the source and urgency.
Backend Resolution and Registry Integration
Acting as the intermediary between session headers and execution backends, the SessionManager resolves the correct AgentBackend implementation through BackendRegistry.prepare (referenced in constructor lines 29‑33). This responsibility includes instantiating backend factories based on the PersistedBackendKind specified in the session configuration and managing backend lifecycle events such as cache disposal during workspace relocation.
Runtime Ledger and History Compaction
When runStore and runtimeEventStore dependencies are present, the SessionManager supports runtime commitment and ledger repair (lines 15‑19) through runtimeLedgerRepair creation. Additionally, the manager controls mid-turn history compaction via the allowMidTurnHistoryCompaction flag defined in SessionManagerBaseDeps (lines 19‑27), determining whether sessions may compact their own history while turns remain active.
Key Source Files and Architecture
Understanding the SessionManager responsibilities requires familiarity with several interconnected components:
packages/runtime/src/session-manager.ts– Core implementation containing all methods described above, including lifecycle management, configuration transitions, and child session handling.packages/runtime/src/runtime-kernel.ts– The Runtime Host that manages live turn execution, backend caching, and disposal; the SessionManager delegates to this component for in-memory state.packages/storage/src/session-store.ts– SQLite-based persistence layer for session headers, messages, and configuration data.packages/runtime/src/backend-registry.ts– Registry mappingPersistedBackendKindto backend factories; used by the SessionManager to instantiate correct backends.packages/runtime/src/session-projection-helpers.ts– Utility functions for building session-header patches and normalizing stop-session inputs.
Practical Usage Examples
Creating and Listing Sessions
import { SessionManager } from '@maka/runtime';
import type { CreateSessionInput } from '@maka/core/runtime-inputs';
const manager = new SessionManager(deps);
const input: CreateSessionInput = {
name: 'My New Session',
backend: 'openai',
model: 'gpt-4o-mini',
permissionMode: 'explore',
};
const summary = await manager.createSession(input);
console.log('Created session:', summary.id);
// List existing sessions and check running turns
const sessions = await manager.listSessions();
for (const s of sessions) {
console.log(`${s.name} (id=${s.id})`);
if (s.runningTurnIds?.length) {
console.log(' Running turns:', s.runningTurnIds.join(', '));
}
}
Stopping Sessions from UI or WorkHub
// UI button click
await manager.stopSession({ source: 'stop_button', mode: 'graceful' });
// WorkHub direct stop
await manager.stopSession({
source: 'workhub_direct_stop',
workHubActionId: 'wh-12345',
mode: 'force',
});
Spawning Child Sub-Agent Sessions
const childResult = await manager.spawnChildSession({
spawnedBy: {
sessionId: parentId,
turnId: turnId,
runId: runId,
spawnReason: 'assistant'
},
agentProfile: myAgentProfile,
prompt: 'Analyze the attached document.',
name: 'Child Analysis',
});
console.log('Child session created with id', childResult.childSessionId);
Updating Configuration with Revision Safety
const header = await manager.getSessionHeader(sessionId);
const updatedHeader = await manager.transitionSessionConfiguration(sessionId, {
expectedRevision: header.revision,
configuration: {
backend: 'anthropic',
model: 'claude-3-5-sonnet',
permissionMode: 'explore',
},
clearConnectionBlock: false,
permissionModeOnly: false,
});
console.log('Configuration updated, new revision:', updatedHeader.revision);
Summary
- SessionManager responsibilities encompass the full lifecycle of Maka workspaces, from creation and persistence to termination and relocation.
- The component acts as a façade coordinating between
SessionStore(SQLite persistence) andRuntimeKernel(live execution state). - Key operations include atomic configuration transitions, child session provisioning for sub-agents, and multi-source session stopping (UI and WorkHub).
- The manager integrates with
BackendRegistryto resolve and instantiate the correctAgentBackendfor each session’s configuredPersistedBackendKind. - Advanced features include runtime ledger repair, mid-turn history compaction controls, and fingerprint-verified graph operator provisioning.
Frequently Asked Questions
What is the difference between SessionManager and RuntimeKernel in Apache Maka?
The SessionManager serves as the public API façade handling persistent session state and high-level operations, while RuntimeKernel manages the in-memory execution environment and active turn processing. According to the source code in packages/runtime/src/session-manager.ts, the manager queries the kernel for runningTurnIds (lines 59‑61) but delegates actual execution to the kernel, maintaining separation between storage concerns and live runtime behavior.
How does SessionManager prevent configuration conflicts during updates?
The transitionSessionConfiguration method (lines 44‑85) implements optimistic concurrency control using versioned headers. It validates the expectedRevision parameter against the current session header before applying changes, ensuring that concurrent modifications do not overwrite each other. If the revision check fails, the operation aborts, allowing the caller to fetch the latest state and retry.
What are child sessions and when should they be used?
Child sessions are isolated workspaces spawned by a parent session to run sub-agents or specialized analysis tasks. The SessionManager provisions these via provisionChildWorkspace (lines 81‑95) and spawnChildSession, creating separate worktrees that prevent sub-agent operations from contaminating the parent session’s state. Use child sessions when delegating specific tasks (such as document analysis or tool execution) to specialized agent profiles.
How does SessionManager handle session termination gracefully?
The manager accepts termination requests through stopSession with configurable modes defined in StopSessionInput (lines 65‑74). In graceful mode, the manager coordinates with RuntimeKernel to complete active turns before shutting down, while force mode terminates execution immediately. This dual-mode approach supports both user-initiated UI stops and automated WorkHub action triggers.
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 →