How Mako's SessionManager Manages the AI Agent Session Lifecycle: A Complete Guide

Mako's SessionManager orchestrates the complete lifecycle of an AI agent session through four distinct phases: creation and initialization, active turn tracking, runtime mutations and configuration changes, and final termination with cleanup.

The SessionManager in Apache Mako serves as the public Runtime API that governs every stage of an AI agent session's existence. Located in packages/runtime/src/session-manager.ts, this class coordinates between persistent storage, runtime execution kernels, and backend AI services to maintain consistent session state from creation through disposal.

The Four Phases of Session Lifecycle Management

Mako's session lifecycle follows a structured pipeline that ensures data integrity and resource management across the entire execution span.

Phase 1: Session Creation and Initialization

The lifecycle begins when SessionManager.createSession generates a new session entity and persists it to the SessionStore. This method delegates to SessionStore.create to write the initial session header to SQLite, generates a unique identifier via the injected newId function, and returns a SessionSummary object through the headerToSummary transformation. The implementation spans lines 19-25 in packages/runtime/src/session-manager.ts, establishing the foundational persistent record before any AI execution begins.

During initialization, the manager also coordinates with the BackendRegistry to provision the concrete AI backend (such as OpenAI or Azure) and hands this activation to the RuntimeKernel for subsequent turn execution.

Phase 2: Tracking Active Execution Turns

Once a session is active, the manager monitors ongoing work through the runningTurnIds method (lines 40-42 in session-manager.ts). This functionality delegates to RuntimeKernel, which maintains an in-memory map of active turn IDs per session. The private #projectLiveRunState method (lines 44-51) augments session listings with these live execution states, ensuring that calls to listSessions return real-time information about which sessions have active computational work in flight.

This tracking mechanism prevents premature termination of sessions with running operations and provides visibility into system workload.

Phase 3: Runtime Mutations and Configuration Changes

Active sessions frequently require mid-lifecycle modifications, which the manager handles through several specialized methods.

Configuration transitions validate and apply changes to revision numbers, permission modes, collaboration settings, and deep-research labels via transitionSessionConfiguration (lines 25-30). This method updates the persistent header through SessionStore.updateSessionConfiguration only after validation passes.

Workspace relocation allows moving a session's working directory through relocateSessionWorkspace (lines 85-92). This complex operation ensures no active turns are executing, disposes the current backend, updates the session header with the new path, and re-opens any shell runs in the new location.

Child-session handling manages sub-agent spawning by provisioning work-tree bindings and recording workspace patches for crash recovery, tracked internally through the childSessionSpawns map.

Phase 4: Termination and Resource Cleanup

Session conclusion involves multiple cleanup stages to prevent resource leaks. The stopSession method (following patterns established in lines 21-27) aborts active runs, updates the session header status, clears sandbox boundaries, and removes the session from the RuntimeKernel.

For backend resource management, disposeSessionBackend forces release of cached AI backend state, while refreshIdleBackends triggers lazy cache invalidation across all idle sessions. The manager also finalizes pending workspace patches to ensure work-tree changes survive unexpected crashes, guaranteeing idempotent handling through careful tracking maps that prevent duplicate work on retry.

Key Implementation Files and Architecture

The session lifecycle relies on four core components working in concert:

Practical Code Examples for Session Lifecycle Operations

The following TypeScript examples demonstrate common session management patterns using an initialized SessionManager instance named manager:

// Create a new AI agent session
const summary = await manager.createSession({
  name: 'Chat with Copilot',
  backend: 'openai',
  permissionMode: 'explore',
});
// List all sessions with live running-turn IDs attached
const sessions = await manager.listSessions();
console.log(sessions.map(s => 
  `${s.name} – running turns: ${s.runningTurnIds?.join(', ')}`
));
// Update session configuration (e.g., change permission mode)
await manager.transitionSessionConfiguration(summary.id, {
  expectedRevision: 1,
  configuration: {
    backend: 'openai',
    llmConnectionId: undefined,
    llmConnectionSlug: 'openai',
    connectionLocked: false,
    model: 'gpt-4',
    thinkingLevel: 'normal',
    permissionMode: 'reflect',
    collaborationMode: 'solo',
    orchestrationMode: 'auto',
    labels: [],
  },
  clearConnectionBlock: false,
});
// Relocate session workspace to a new directory
await manager.relocateSessionWorkspace(summary.id, {
  expectedRevision: 2,
  cwd: '/new/workspace/path',
  projectId: null,
});
// Gracefully stop a session and clean up resources
await manager.stopSession(summary.id, { 
  source: 'stop_button', 
  mode: 'graceful' 
});

Summary

  • Mako's SessionManager in packages/runtime/src/session-manager.ts provides the primary public API for AI agent session lifecycle management in the Apache Mako runtime.

  • The lifecycle progresses through four distinct phases: creation and initialization (SQLite persistence via SessionStore), active turn tracking (RuntimeKernel coordination), runtime mutations (configuration transitions and workspace relocation), and termination cleanup (backend disposal and resource release).

  • RuntimeKernel maintains in-memory execution state through runningTurnIds, while BackendRegistry handles AI provider activation and caching.

  • Methods like transitionSessionConfiguration and relocateSessionWorkspace ensure atomic, validated updates to persistent session state, preventing data corruption during mid-lifecycle changes.

  • Idempotency guarantees are maintained through internal maps (childSessionSpawns, claimedAgentGraphIntentRuns) that prevent duplicate work when operations retry after failures.

Frequently Asked Questions

How does SessionManager track which sessions have active AI work in progress?

The manager delegates to RuntimeKernel, which maintains an in-memory map of active turn IDs per session. The runningTurnIds method exposes this data, while #projectLiveRunState augments session listings with live execution states. This allows the UI and host services to see real-time execution status when calling listSessions.

What happens when I change a session's backend configuration mid-conversation?

The transitionSessionConfiguration method validates the requested changes against the current revision number, then persists the update via SessionStore.updateSessionConfiguration. This ensures that permission modes, model selections, and collaboration settings transition atomically without interrupting active turns, provided no execution is currently running.

Can I move a session to a different working directory without losing context?

Yes, through the relocateSessionWorkspace method. This operation verifies no active turns are executing, disposes the current backend to prevent file handle conflicts, updates the session header with the new path in SQLite, and re-opens any shell runs in the relocated directory. Child-session workspace patches are preserved and finalized during this process.

How does Mako prevent resource leaks when sessions terminate?

The manager implements a multi-stage cleanup protocol through stopSession, which aborts active runs, updates the persistent header status, clears sandbox boundaries, and removes the session from RuntimeKernel. For backend resources, disposeSessionBackend explicitly releases cached AI connections, while refreshIdleBackends performs lazy cache invalidation to reclaim memory from inactive sessions.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →