# How Maka's SessionManager Manages Session Lifecycles and Turn Execution

> Discover how Maka's SessionManager orchestrates session lifecycles and turn execution, coordinating persistent storage, AI backends, and sandboxed environments for seamless runtime operations.

- Repository: [The Apache Software Foundation/maka](https://github.com/apache/maka)
- Tags: internals
- Published: 2026-08-31

---

**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`](https://github.com/apache/maka/blob/main/packages/runtime/src/session-manager.ts)). This method delegates to `SessionStore.create` to generate a fresh `SessionHeader`, then returns a summarized view:

```typescript
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:

```typescript
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`:

```typescript
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):

```typescript
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):

```typescript
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:

1. **Allocates turn ID** — generates `newId` and records start event
2. **Invokes backend** — runs `AgentBackend` with prompt, tools, and permission mode
3. **Captures events** — writes each `RuntimeEvent` to `RuntimeEventStore` and mirrors to session messages via `store.appendMessage`
4. **Commits turn** — finalizes status, updates `SessionHeader`, emits `CompleteEvent`

### Complete Turn Execution Example

```typescript
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`](https://github.com/apache/maka/blob/main/packages/runtime/src/session-manager.ts) | Public API for creation, configuration, turn execution, cleanup |
| [`packages/runtime/src/runtime-kernel.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/runtime-kernel.ts) | Turn queue, backend activation, event recording |
| [`packages/runtime/src/runtime-read-model.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/runtime-read-model.ts) | Session state projections, `headerToSummary` utilities |
| [`packages/runtime/src/stream-graph-admission.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/stream-graph-admission.ts) | Graph intent fingerprinting and admission verification |
| [`packages/runtime/src/agent-catalog.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/agent-catalog.ts) | Sub-agent definitions and graph operator provisioning |

## Summary

- **SessionManager acts as façade** — coordinates `SessionStore`, `AgentBackend`, and `ExecutionBoundary` without direct persistence or execution logic
- **Lifecycle operations delegate** — creation, listing, configuration changes, and termination all forward to specialized subsystems
- **Turn execution is claim-based** — `runClaimedAgentGraphIntent` validates durable claims before streaming execution through `RuntimeKernel`
- **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`](https://github.com/apache/maka/blob/main/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.