How Maka’s Runtime Host Manages Session and Turn Identity Across Desktop, TUI, and CLI Clients

Maka’s Runtime Host enforces a three-layer identity validation system—host-level, session-level, and turn-level—that ensures all clients share a consistent view of session state and turn ordering through stateless, validation-heavy connections.

The Apache Maka project provides a unified runtime architecture where graphical Desktop applications, Terminal User Interface (TUI) tools, and headless Command Line Interface (CLI) scripts interact with conversation sessions. Understanding how Maka’s Runtime Host manages session and turn identity reveals why these distinct client types can safely operate on the same conversation state without conflicts or desynchronization.

Three Layers of Identity Validation

The Runtime Host treats every client connection as stateless, pushing identity verification into explicit wire-format checks. This design guarantees that Desktop, TUI, and CLI clients all observe identical session and turn sequences.

Host-Level Identity

When a client initiates a connection, the handshake embeds a clientInstanceId, the host’s hostEpoch, compositionId, and compositionRevision. The client stores these values in the RuntimeHostConnection object and re-verifies them on every status check and subscription call. If these values drift—indicating a host restart or composition change—the connection aborts immediately.

In packages/runtime-host/src/client/connection.ts, the RuntimeHostConnectionImpl.status() method performs this validation (lines 29-49):

// Validates hostEpoch, compositionId, and compositionRevision
await connection.status(); // Throws RuntimeHostConnectionError on mismatch

This ensures that long-lived CLI scripts or TUI sessions detect host restarts before attempting to submit new turns.

Session-Level Identity

After establishing the host connection, a client opens a session subscription via openSessionSubscription({ sessionId }). The host returns a SubscriptionOpenResult containing a server-generated subscriptionId and a snapshot of the session. The client immediately verifies that snapshot.session.sessionId matches the requested sessionId; any mismatch triggers a RuntimeHostSubscriptionError.

The validation logic resides in RuntimeHostConnectionImpl.openSessionSubscription() in packages/runtime-host/src/client/connection.ts (lines 55-73):

const subscription = await connection.openSessionSubscription({
  sessionId: 'session-abc-123',
  subscriptionMode: 'projection', // or 'delta' / 'event'
});
// Internal validation ensures returned sessionId matches 'session-abc-123'

This check prevents race conditions where a session might be deleted and recreated with different content between the request and subscription acknowledgment.

Turn-Level Identity

Within an active subscription, every transmitted frame carries a monotonic sequence number and, for message-centric frames, a turnId. The ClientSessionSubscription class tracks the expected sequence (#expectedSequence) and validates every inbound frame through its accept() method.

Located in packages/runtime-host/src/client/session-subscription.ts (lines 95-108), this method performs four critical validations:

  • Host epoch verification: frame.hostEpoch === this.hostEpoch
  • Subscription binding: frame.subscriptionId === this.subscriptionId
  • Sequence integrity: Ensures the frame's sequence matches the expected counter to detect gaps or reordering
  • Session consistency: Confirms session-related frames reference the original sessionId

If any check fails, the subscription raises a RuntimeHostSubscriptionError and tears down the connection. Turn ordering emerges implicitly from the strict sequence monotonicity and the host-generated turnId embedded in user and assistant message payloads.

Stateless Architecture Across Client Types

All Maka clients—Desktop GUI, TUI, and CLI—consume the same runtime-host client library located in packages/runtime-host/src/client/*. The host itself maintains no per-client process state; identity checks are pure functions of the wire data exchanged.

This architecture enables:

  • Concurrent access: Multiple independent CLI processes and a TUI can simultaneously subscribe to the same sessionId without interfering with each other’s turns
  • Connection resilience: Liveness probes (#startLivenessProbe) periodically re-validate host identity via host.status requests, ensuring clients detect host epoch changes before submitting new turns
  • UI agnosticism: The Desktop TUI (terminal-client) and pure CLI (maka run) use identical connectRuntimeHost APIs—the only difference is the presentation layer consuming the subscription iterator

Practical Implementation Example

The following TypeScript example demonstrates the complete flow for connecting to the Runtime Host and consuming turn-aware session updates. This code works identically for Desktop TUI and CLI clients:

import { connectRuntimeHost } from '@maka/runtime-host/client';

// 1. Establish connection with protocol negotiation
const { connection } = await connectRuntimeHost({
  rootPath: '/home/user/.maka',
  protocol: { min: 1, max: 2 },
  clientInstanceId: 'my-cli-123', // Optional: for testing or logging
});

// 2. Verify host identity (optional, usually implicit)
await connection.status(); // Throws on hostEpoch/composition mismatch

// 3. Subscribe to a specific session with turn tracking
const subscription = await connection.openSessionSubscription({
  sessionId: 'session-abc-123',
  subscriptionMode: 'projection',
});

// 4. Consume frames with sequence and turnId validation
for await (const frame of subscription) {
  switch (frame.kind) {
    case 'subscription.session_delta':
      // frame.turnId corresponds to the specific conversation turn
      console.log('Processing turn:', frame.turnId);
      break;
    case 'subscription.session_projection':
      // Full projection includes ordered messages with turnIds
      console.log('Total turns:', frame.messages.length);
      break;
  }
}

// 5. Clean shutdown
await subscription.close();
await connection.close();

Key implementation details illustrated:

  • The connectRuntimeHost function handles the initial handshake and clientInstanceId registration
  • openSessionSubscription guarantees the returned subscription is bound to the exact sessionId requested
  • Turn ordering is preserved because the host sends frames in strict sequence order, validated by ClientSessionSubscription.accept()

Summary

  • Three-layer validation: Host epoch/composition checks, session ID matching, and per-frame sequence/turnId verification ensure consistency across all client types
  • Stateless design: The Runtime Host stores no per-client state, allowing Desktop, TUI, and CLI clients to connect simultaneously without conflicts
  • Wire-format enforcement: Identity validation occurs in RuntimeHostConnectionImpl.status(), RuntimeHostConnectionImpl.openSessionSubscription(), and ClientSessionSubscription.accept() within packages/runtime-host/src/client/
  • Turn ordering: Monotonic sequence numbers and explicit turnId fields in message payloads guarantee that every client observes the same conversation history
  • Shared client library: All client types use identical APIs from @maka/runtime-host/client, differing only in UI presentation layers

Frequently Asked Questions

How does the Runtime Host handle simultaneous connections from CLI and TUI clients?

The Runtime Host treats every connection as stateless and independent. Each client maintains its own RuntimeHostConnection and ClientSessionSubscription instances, validating host epoch and sequence numbers locally. Since the host does not track client-specific state, multiple CLI processes and a TUI can safely subscribe to the same sessionId without blocking each other, provided they all pass the identity validation checks on every frame.

What happens if the Runtime Host restarts while a client is connected?

The host’s hostEpoch value increments on restart. When the client’s liveness probe (triggered by #startLivenessProbe) calls connection.status() or when the next frame arrives, the hostEpoch comparison in RuntimeHostConnectionImpl.status() or ClientSessionSubscription.accept() will fail. This mismatch immediately triggers a RuntimeHostConnectionError or RuntimeHostSubscriptionError, forcing the client to reconnect and re-validate the session.

Where is the turn ordering guaranteed in the protocol?

Turn ordering is enforced in packages/runtime-host/src/client/session-subscription.ts via the accept() method (lines 95-108). This method validates that each frame's sequence number matches the expected counter and that message payloads contain the correct turnId. The host generates these identifiers monotonically, ensuring that Desktop, TUI, and CLI clients all receive turns in identical order.

Can a client request a specific turnId to resume from?

No. Clients request session subscriptions by sessionId only, receiving a live stream of frames starting from the current state. The turnId values are opaque identifiers generated by the host and embedded within message payloads. Clients must consume the subscription iterator from the opening frame, relying on the sequence validation logic to detect gaps, rather than seeking to arbitrary turn positions.

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 →