# How Maka Manages Agent Lifecycle and Continuation: A Deep Dive into the Runtime Host Architecture

> Explore how Maka manages agent lifecycle and continuation using its Runtime Host architecture and immutable SQLite event stream. Learn about ephemeral and service modes.

- Repository: [The Apache Software Foundation/maka](https://github.com/apache/maka)
- Tags: deep-dive
- Published: 2026-09-04

---

**Maka manages agent lifecycle through a single-owner Runtime Host with configurable ephemeral or service modes, while continuation relies on an immutable SQLite-backed AgentRun event stream validated through cryptographic continuation claims.**

The `apache/maka` repository implements a deterministic agent runtime built around orthogonal concerns: **lifecycle management** (how long a Runtime Host lives) and **continuation** (how interrupted agent runs safely resume). Understanding these mechanisms requires examining the interplay between the host kernel in `packages/runtime-host` and the durable storage layer in `packages/storage`.

## The Two Pillars: Lifecycle vs. Continuation

Maka’s architecture separates host longevity from execution recovery. The **Runtime Host** controls process lifetime through `lifecycleMode` configuration, while the **AgentRun event stream** provides an append-only ledger that makes continuation possible across crashes or user suspensions.

This separation ensures that a host can shut down cleanly without losing execution context, and that resumed runs maintain exact causal consistency with their predecessors.

## Agent Lifecycle Management

The `RuntimeHostKernel` class in [`packages/runtime-host/src/server/host-kernel.ts`](https://github.com/apache/maka/blob/main/packages/runtime-host/src/server/host-kernel.ts) orchestrates process lifetime. Host behavior is determined by the `normalizeLifecycle` function, which validates `RuntimeHostKernelOptions` and constructs a concrete `RuntimeHostLifecycle` value.

### Ephemeral Mode for Desktop and CLI

**Ephemeral mode** (`lifecycleMode: 'ephemeral'`) is the default for interactive sessions. The host monitors connection state through two timers:

- **`initialConnectionTimeoutMs`**: If no client connects before this timer expires, the host shuts down automatically.
- **`idleGraceMs`**: After the first connection, this timer monitors activity. When it expires without active operations, the host drains and shuts down.

These timers are managed by private methods including `#idleTimer`, `#cancelIdle`, and `#armShutdownDeadline` within the host kernel.

### Service Mode for Background Operations

**Service mode** (`lifecycleMode: 'service'`) is designed for long-running background services. In this mode, idle-related options are prohibited—`initialConnectionTimeoutMs` and `idleGraceMs` cannot be specified. The host runs indefinitely until receiving an explicit shutdown request.

The `normalizeLifecycle` function enforces this restriction early in the initialization sequence (lines 51-57 of [`host-kernel.ts`](https://github.com/apache/maka/blob/main/host-kernel.ts)).

### Graceful Shutdown Flow

When shutdown is requested via `close()` or triggered by an internal error, the host executes a deterministic sequence:

1. Cancels idle and connection timers.
2. Invokes `#requestDrain()` to stop accepting new transports and finish pending operations.
3. Resolves the `closed` promise once all operations complete.

If graceful shutdown fails, the kernel throws an aggregated error containing both the original startup failure and subsequent shutdown errors (lines 41-49 of [`host-kernel.ts`](https://github.com/apache/maka/blob/main/host-kernel.ts)).

## Continuation Mechanism

While lifecycle management controls the host process, **continuation** ensures that agent execution can pause and resume without losing state. This relies on the `AgentRun` event stream stored in SQLite.

### The Immutable AgentRun Event Stream

Every agent action—model calls, tool invocations, and UI updates—is recorded as an `AgentRunEvent` in the SQLite store ([`packages/storage/src/agent-run-store.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/agent-run-store.ts), lines 325-340). This append-only stream serves as the **single source of truth** for recovery and deterministic replay.

### Continuation Claims in SQLite

When a turn is interrupted (due to user suspension, crashes, or token limits), the runtime creates a **continuation claim** stored in the `runtime_continuation_claims` table. Each claim records:

- A unique `claim_id`.
- A JSON snapshot (`target_opening_json`) describing the exact runtime state needed to resume.
- The protocol version and `RUNTIME_CONTINUATION_AUTHORITY_CAPABILITY`.

### Validation and Resumption

Before resuming, the runtime validates the continuation claim against the existing AgentRun ledger in [`packages/storage/src/sqlite-runtime-store.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/sqlite-runtime-store.ts) (lines 4187-4282). The validation checks:

- The claim’s authority matches the host’s continuation capability.
- The target sequence is reserved for this continuation (`continuationStartEventMatchesClaim`).
- The claim’s protocol version is supported.

Failure results in specific errors such as "Invalid continuation‑start authority event" or "Continuation target identity conflict" (lines 4271-4282).

Once validated, the host appends a `continuationStart` event to the AgentRun stream and continues processing. Because the stream is durable, later recovery can replay from the exact continuation point.

## Implementation Examples

### Starting a Runtime Host with Ephemeral Lifecycle

```typescript
import { RuntimeHostKernel } from '@maka/runtime-host';
import { authenticateInteractiveRootOwner } from '@maka/runtime-host/src/server/auth';

// Assume `owner` is an authenticated InteractiveRootOwner instance
await RuntimeHostKernel.start({
  owner,
  composition: { descriptor: /* … */ },
  handshakeTimeoutMs: 10_000,
  shutdownGraceMs: 5_000,
  // Ephemeral lifecycle (default) – idle after 30s, shut down automatically
  idleGraceMs: 30_000,
});

```

The `idleGraceMs` parameter is only accepted when `lifecycleMode` is omitted or explicitly set to `'ephemeral'`. The host automatically closes after a quiet period of 30 seconds.

### Creating a Continuation Claim

```typescript
import { createSqliteAgentRunStore } from '@maka/storage';

// `workspaceRoot` points to the Electron userData folder
const runStore = createSqliteAgentRunStore(workspaceRoot);

// When a turn is about to be paused, request a continuation claim
const claim = await runStore.appendContinuationClaim({
  claimId: crypto.randomUUID(),
  targetOpeningJson: JSON.stringify({ /* runtime state */ }),
  protocolVersion: 1,
});

```

The store inserts the claim into `runtime_continuation_claims`. Upon resumption, the runtime reads this claim, validates it, and inserts a `continuationStart` event.

### Resuming from a Continuation

```typescript
// The Runtime Host automatically detects pending claims on startup
await RuntimeHostKernel.start({
  owner,
  composition: {/* … */},
  lifecycleMode: 'ephemeral',
});

```

During startup, the host queries the `AgentRun` ledger for unfinished continuations, validates the claim, and injects the continuation start event, allowing the agent to continue exactly where it left off.

## Summary

- **Runtime Host Lifecycle**: Controlled by `lifecycleMode` (`'ephemeral'` or `'service'`) in [`packages/runtime-host/src/server/host-kernel.ts`](https://github.com/apache/maka/blob/main/packages/runtime-host/src/server/host-kernel.ts), determining connection timeouts, idle grace periods, and shutdown behavior.
- **Ephemeral Mode**: Uses `initialConnectionTimeoutMs` and `idleGraceMs` timers managed by `#idleTimer` and related helpers to auto-shutdown inactive hosts.
- **Service Mode**: Prohibits idle timers; runs until explicit `close()` invocation.
- **Continuation Safety**: Depends on the `AgentRun` event stream in [`packages/storage/src/agent-run-store.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/agent-run-store.ts) as an immutable, append-only ledger.
- **Continuation Claims**: Stored in the `runtime_continuation_claims` table and validated in [`packages/storage/src/sqlite-runtime-store.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/sqlite-runtime-store.ts) to ensure authority matches and sequence integrity before resumption.
- **Capability Requirements**: Continuation requires the `runtime_continuation_authority` capability (`RUNTIME_CONTINUATION_AUTHORITY_CAPABILITY`) advertised by the storage layer.

## Frequently Asked Questions

### What is the difference between ephemeral and service lifecycle modes in Maka?

**Ephemeral mode** is designed for desktop and CLI sessions where the host should shut down automatically when idle, using timers like `initialConnectionTimeoutMs` and `idleGraceMs`. **Service mode** is for long-running background processes that must remain active indefinitely; it explicitly forbids idle timeout parameters and only shuts down upon receiving a `close()` request according to the `normalizeLifecycle` validation logic.

### How does Maka ensure that a continued agent run is identical to the original?

Maka ensures deterministic continuation by validating **continuation claims** against the immutable `AgentRun` event stream. Before resuming, the runtime in [`packages/storage/src/sqlite-runtime-store.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/sqlite-runtime-store.ts) verifies that the claim authority matches the host capability, the target sequence is reserved, and the protocol version is compatible. Execution then resumes by appending a `continuationStart` event to the existing ledger, preserving exact causal history.

### What happens if a Runtime Host shuts down during an active agent turn?

If a host shuts down during an active turn, the runtime creates a continuation claim in the `runtime_continuation_claims` table containing a JSON snapshot of the runtime state. When the host restarts, it detects this pending claim, validates it, and injects a `continuationStart` event into the `AgentRun` stream, allowing seamless resumption from the interruption point without data loss.

### Where is the continuation capability defined, and what happens if it is unavailable?

The continuation capability is defined as `RUNTIME_CONTINUATION_AUTHORITY_CAPABILITY` in [`packages/storage/src/sqlite-runtime-schema.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/sqlite-runtime-schema.ts) (lines 36-38). If the underlying SQLite store does not advertise this capability, the UI surface reports `continuation_authority_unavailable`, and the system prevents continuation attempts, ensuring that resumption only occurs when the storage layer can guarantee durable, validated event streams.