# Execution Flow Through Maka's Runtime Core: How AgentRun Orchestrates AI Turns

> Discover Maka's runtime core execution flow. AgentRun orchestrates AI turns through a six-stage pipeline from initialization to finalization. Understand how Maka processes agent actions.

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

---

**The execution flow through Maka's runtime core follows a six-stage pipeline governed by the `AgentRun` class, beginning with run initialization and session reservation, proceeding through event draining and persistence, and concluding with terminal fact finalization.**

Apache Maka's runtime core provides the durable, reliable backbone for agent execution. At the heart of this system lies the **`AgentRun`** class found in [`packages/runtime/src/agent-run.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/agent-run.ts), which manages the complete lifecycle of a conversational turn—from user input to model response, event persistence, and graceful shutdown.

## The Six-Stage Execution Pipeline

Every turn (user message → model response) follows a strict pipeline orchestrated by `AgentRun`. Understanding these stages is essential for developers extending Maka or debugging complex session behaviors.

### 1. Run Initialization and Session Reservation

The execution flow begins when **`AgentRun.begin()`** is invoked (L665‑L675 in [`packages/runtime/src/agent-run.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/agent-run.ts)). This method performs three critical operations:

- Calls **`beginUserTurn()`** (L447‑L557) to open the invocation via `openInvocation()` and record the initial user runtime event through `recordInitialRuntimeEvent()` (L1002‑L1017)
- Reserves the run through the **`reserveRun`** hook, which acquires exclusive access to the session
- Updates the session status to `"running"` via `updateStatus`

Concurrent host work is coordinated by **`SessionActivityRegistry`** in [`packages/runtime/src/goal-turn-lifecycle.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/goal-turn-lifecycle.ts). The registry's **`acquire()`** method (L84‑L91) blocks until the session is idle, granting a lease that ensures exclusive access during the turn:

```typescript
// packages/runtime/src/goal-turn-lifecycle.ts
export class SessionActivityRegistry {
  reserve(sessionId: string): SessionActivityLease { … }   // L52‑L74
  async acquire(sessionId: string, abortSignal?: AbortSignal): Promise<SessionActivityLease> { … } // L84‑L91
}

```

### 2. Draining the Backend Event Stream

Once initialized, the runtime enters the event consumption phase via **`drainGoalTurn()`**. This function iterates over the backend's `SessionEvent` stream, updating the session projection and determining the turn outcome:

```typescript
// packages/runtime/src/goal-turn-lifecycle.ts
export async function drainGoalTurn(input: DrainGoalTurnInput): Promise<GoalTurnOutcome> {
  for await (const event of input.events) {
    observedOutcome = observeGoalTurnOutcome(observedOutcome, event);
    await input.onEvent?.(event);
  }
  …
}

```

The helper **`observeGoalTurnOutcome()`** (L86‑L104) classifies each event to determine whether the turn completed, suspended, aborted, or encountered an error.

### 3. Recording Runtime Events

Every `SessionEvent` is transformed into a **`RuntimeEvent`** and durably persisted. The **`recordRuntimeEvents()`** method in `AgentRun` handles this via the **`RuntimeEventStore`**:

```typescript
// packages/runtime/src/agent-run.ts
public async recordRuntimeEvents(events: readonly RuntimeEvent[], options = {}): Promise<void> {
  for (const event of events) {
    const terminal = isTerminalRuntimeEvent(event);
    const eventForStore = terminal ? this.reserveTerminalEvent(event) : event;
    …
    this.enqueueRuntimeEventStore('append runtime event', async () => {
      await this.input.runtimeEventStore?.appendRuntimeEvent(this.sessionId, this.runId, eventForStore, {
        durable: terminal || options.requireDurableWrite === true,
      });
    });
  }
}

```

Terminal events receive special handling through **`reserveTerminalEvent()`** (L278‑L285) to guarantee exactly-once semantics for final state records.

### 4. Cooperative Handoff Handling

When tools require transferring control between agents, the runtime initiates a cooperative handoff via **`requestHandoff()`**:

```typescript
// packages/runtime/src/agent-run.ts
public requestHandoff(pause: RuntimeHandoffIntent, signal: AbortSignal): AgentRunHandoffRequest {
  …
  const pending = { pause, preview: undefined, committed: false, … };
  this.handoffRequest = pending;
  const gate = this.handoffGate.request(signal);
  …
  return { ready: gate.ready, sealed, cancel, preview, commit };
}

```

The handoff boundary is reached through **`reachHandoffBoundary()`** (L360‑L387), which constructs a preview event and pauses execution if the **`RunHandoffGate`** determines the run should halt.

### 5. Finalization and Terminal Fact Commitment

When the turn terminates—whether completed, aborted, or errored—**`settleStopTerminal()`** ensures durable consistency:

```typescript
// packages/runtime/src/agent-run.ts
public async settleStopTerminal(): Promise<void> {
  if (this.terminalClaim?.owner !== 'stop' || this.terminalRunFactCommitted) return;
  …
  await this.flushRuntimePartialBuffer(true);
  const finalStatus = { status: 'aborted' };
  this.finalStatus ??= finalStatus;
  this.reserveFinalizationTerminal(finalStatus, ts);
  await this.commitTerminalRun(finalStatus, ts);
}

```

This method flushes the runtime partial buffer, reserves the finalization terminal, and commits the terminal run fact to the **`AgentRunStore`**, ensuring the session status remains consistent even during crashes.

### 6. Run Composition and Persistence

Throughout execution, the runtime maintains run-level metadata through **`AgentRunStore`**. Methods like **`recordRunComposition()`** store trace information and agent hierarchies, while `recordRuntimeEvents()` persists the event log. These writes happen asynchronously through queued operations to maximize throughput while maintaining durability guarantees.

## Practical Implementation Example

The following TypeScript demonstrates the minimal steps required to execute a turn through Maka's runtime core:

```typescript
import { AgentRun } from '@maka/runtime';
import { createHooks } from './my-session-manager';

// 1️⃣ Create an AgentRun instance
const run = new AgentRun({
  sessionId: 'sess‑123',
  header: mySessionHeader,
  userInput: { turnId: 'turn‑1', text: 'Explain the flow.' },
  newId: () => crypto.randomUUID(),
  now: () => Date.now(),
  hooks: createHooks(),
});

// 2️⃣ Begin the turn (initialisation + status update)
const { backend, backendInput, initialRuntimeEvent } = await run.begin();

// 3️⃣ Send the input to the backend (e.g. OpenAI)
backend.send(backendInput);

// 4️⃣ Drain the event stream and record runtime facts
await drainGoalTurn({
  turnId: run.turnId,
  events: backend.eventStream(),
  activity: await sessionActivityRegistry.acquire('sess‑123'),
  onEvent: async ev => await run.recordRuntimeEvents([ev.runtimeEvent]),
  onDrained: outcome => console.log('Turn finished', outcome),
});

```

This example illustrates how hosts initialize runs, reserve session activity, consume backend streams, and delegate persistence to the runtime core.

## Key Source Files in the Runtime Core

- **[`packages/runtime/src/agent-run.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/agent-run.ts)** – Core orchestration class (`AgentRun`) managing the complete turn lifecycle, handoff coordination, and terminal fact commitment
- **[`packages/runtime/src/goal-turn-lifecycle.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/goal-turn-lifecycle.ts)** – Session activity registry (`SessionActivityRegistry`) and turn-draining logic (`drainGoalTurn`)
- **[`packages/runtime/src/run-handoff-gate.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/run-handoff-gate.ts)** – Coordination primitive (`RunHandoffGate`) managing cooperative handoff boundaries
- **[`packages/runtime/src/runtime-event-store.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/runtime-event-store.ts)** – Interface for durable storage of `RuntimeEvent` records
- **[`packages/runtime/src/agent-run-store.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/agent-run-store.ts)** – Interface for run-level fact persistence including traces and composition metadata

## Summary

- The **execution flow through Maka's runtime core** centers on the `AgentRun` class in [`packages/runtime/src/agent-run.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/agent-run.ts), which implements a six-stage pipeline for turn management.
- **Session exclusivity** is guaranteed by `SessionActivityRegistry.acquire()`, preventing concurrent host work during active turns.
- **Event persistence** occurs through `recordRuntimeEvents()`, which writes to `RuntimeEventStore` with special handling for terminal events via `reserveTerminalEvent()`.
- **Cooperative handoffs** are mediated through `requestHandoff()` and `reachHandoffBoundary()`, utilizing `RunHandoffGate` for synchronization.
- **Durability** is ensured by `settleStopTerminal()`, which commits terminal facts to `AgentRunStore` even when turns are aborted or interrupted.

## Frequently Asked Questions

### What is the role of SessionActivityRegistry in Maka's runtime?

`SessionActivityRegistry` prevents race conditions by ensuring only one turn executes per session at any time. Its `acquire()` method blocks until the session is idle, returning a `SessionActivityLease` that must be released when the turn completes. This mechanism, found in [`packages/runtime/src/goal-turn-lifecycle.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/goal-turn-lifecycle.ts), coordinates concurrent access between the host and backend event processing.

### How does Maka handle cooperative handoffs during execution?

When a tool requires transferring control between agents, `AgentRun.requestHandoff()` creates a pending handoff intent and returns an `AgentRunHandoffRequest` with a `ready` promise. The runtime reaches the handoff boundary via `reachHandoffBoundary()`, which constructs a preview event and checks the `RunHandoffGate` to determine whether to pause execution or continue. This allows graceful transitions between agents without losing runtime context.

### What happens when a turn is interrupted or aborted?

If a turn stops prematurely, `AgentRun.settleStopTerminal()` executes to ensure consistency. This method flushes the runtime partial buffer, reserves a terminal event via `reserveFinalizationTerminal()`, and commits the final status to `AgentRunStore`. The terminal claim system guarantees that exactly one terminal fact is written per run, preventing duplicate or missing finalization records during crashes.

### Where are runtime events persisted in Maka's architecture?

Runtime events are durably stored through **`RuntimeEventStore`**, accessed via `recordRuntimeEvents()` in `AgentRun`. Run-level metadata—including traces, composition facts, and terminal states—is persisted to **`AgentRunStore`**. Both stores operate asynchronously through queued operations, with terminal events receiving immediate durable writes to ensure consistency guarantees.