What Is AgentRun in Apache Maka? A Deep Dive into the Execution Engine
AgentRun is the core execution component in Apache Maka that owns the complete lifecycle of an agent, managing session identity, tool orchestration, and deterministic recovery through checkpointing.
AgentRun functions as the "brain" inside Maka's Runtime Host, ensuring that every unit of work—whether a tool call, model inference, or user command—executes reliably within its session context. Located directly beneath the SessionManager and alongside the RuntimeKernel, this component coordinates how agents transition from creation to termination while maintaining immutable state logs for replay and recovery.
AgentRun Architecture and Placement in the Runtime Stack
In Maka's layered architecture, AgentRun occupies a critical position in the Runtime Host stack. The execution flow follows a strict hierarchy: client interfaces (Desktop, TUI, CLI, or Bot) communicate with the Runtime Host, which delegates session management to the SessionManager, which in turn instantiates and controls AgentRun instances alongside the RuntimeKernel.
According to the architecture diagram in ARCHITECTURE.md (lines 26-34), the relationship is hierarchical:
Desktop / TUI / CLI / Bot → Runtime Host → SessionManager → AgentRun + RuntimeKernel
This placement ensures that AgentRun receives sanitized, session-scoped input while maintaining direct access to the execution kernel and persistence layers. Unlike the SessionManager, which tracks meta-level session state, AgentRun possesses granular control over the active turn and agent-specific execution context.
Core Responsibilities of AgentRun in Maka
AgentRun manages four critical domains of the execution lifecycle, each implemented in packages/core/src/agentRun.ts and orchestrated through the RuntimeHost.
Session and Turn Identity Management
AgentRun maintains authoritative knowledge of which session a request belongs to and which conversation turn is being processed. This identity tracking prevents cross-contamination between concurrent sessions and ensures that multi-turn conversations maintain coherent state. The component validates session tokens at initialization and binds all subsequent operations—tool calls, model requests, and logging—to that specific session context.
Agent Lifecycle Orchestration
The component handles the complete state machine of an agent through explicit lifecycle methods: start(), activation, pausing, resuming, and shutdown(). When invoked via AgentRun.start(), the component initializes the execution environment, allocates resources from the RuntimeKernel, and prepares the agent graph for evaluation. The shutdown() method ensures graceful termination, flushing pending events to the Runtime Event Log and releasing kernel resources.
Continuation and Crash Recovery
AgentRun implements deterministic execution through checkpointing and replay mechanisms. In the event of a crash or interruption, the AgentRun.resume() method re-hydrates the agent state from the persisted event log, allowing execution to continue from the exact point of failure. This capability is documented in the Runtime resume design specification and implemented through coordination with the RuntimeHost singleton, which locates the last persisted state via RuntimeHost.getInstance().
Tool Orchestration and Event Logging
When an agent requires external capabilities, AgentRun invokes the Tool Runtime for executing tool calls such as search or fileRead. It records both invocations and results in the Runtime Event Log, creating an immutable audit trail. This logging serves dual purposes: it enables the recovery mechanisms mentioned above and feeds the Agent Graph Control Plane, which schedules dependent work as child sessions.
How AgentRun Interacts with the Maka Runtime
AgentRun operates as a coordination hub between three distinct subsystems:
-
Input Layer: Receives scoped requests from
SessionManager(defined inpackages/runtime/src/SessionManager.ts), which handles session creation and turn tracking before handing off control. -
Persistence Layer: Publishes structured events to the
Runtime Event Log, ensuring that every tool invocation, model response, and state transition is durably recorded for replay and auditing. -
Scheduling Layer: Communicates with the Agent Graph Control Plane (implemented in
packages/runtime/src/AgentGraph.ts) to spawn child sessions when the current agent generates dependent work units, enabling complex multi-agent workflows.
This interaction pattern ensures that AgentRun remains stateless with respect to session metadata (handled by SessionManager) while maintaining full authority over execution semantics and tool invocation.
Working with AgentRun: Practical Code Examples
The following snippets demonstrate idiomatic usage patterns via the Maka SDK, mapping directly to the components described in the architecture.
Creating and Starting an AgentRun from a CLI Command
This example shows how packages/cli/src/commands/run.ts instantiates an AgentRun for interactive use:
import { AgentRun } from '@maka/core';
import { RuntimeHost } from '@maka/runtime-host';
// Create a runtime host (singleton for the process)
const host = new RuntimeHost();
// A simple CLI entry point
async function main() {
// Initialise a new session for the current user
const session = await host.createSession({ user: 'alice' });
// Start an AgentRun that will handle the upcoming turn
const agent = await AgentRun.start({
sessionId: session.id,
// Optional: provide a tool list the agent may invoke
tools: ['search', 'fileRead'],
});
// Send the user prompt to the agent
const response = await agent.runTurn({ prompt: 'What is the weather in Berlin?' });
console.log('Agent response:', response);
// When finished, gracefully shut down the run
await agent.shutdown();
}
main().catch(console.error);
Using the AgentRun API from a Bot Integration
For automated integrations, AgentRun provides a lightweight interface that handles session continuity across discrete messages:
import { AgentRun } from '@maka/core';
import { BotClient } from '@maka/bot';
const bot = new BotClient();
bot.onMessage(async (msg) => {
const agent = await AgentRun.start({ sessionId: msg.sessionId });
const reply = await agent.runTurn({ prompt: msg.text });
await bot.sendMessage(msg.channel, reply);
await agent.shutdown(); // clean up after each turn
});
Recovering from a Crash with Runtime Resume
The AgentRun.resume() method enables fault-tolerant execution by reconstructing state from the event log:
import { RuntimeHost, AgentRun } from '@maka/runtime';
async function resumeAgent(sessionId: string) {
// RuntimeHost knows how to locate the last persisted state
const host = RuntimeHost.getInstance();
// Re‑hydrate the AgentRun from the event log
const agent = await AgentRun.resume({ sessionId });
// Continue processing the next turn
const next = await agent.runTurn({ prompt: 'continue' });
console.log(next);
}
Key Source Files and Implementation Details
Understanding AgentRun requires familiarity with these specific locations in the Apache Maka repository:
| Component | Source File | Purpose |
|---|---|---|
| AgentRun Core | packages/core/src/agentRun.ts |
Defines the AgentRun class, its lifecycle methods (start, runTurn, shutdown, resume), and the execution state machine. |
| Runtime Host | packages/runtime-host/src/RuntimeHost.ts |
The singleton execution authority that creates sessions, owns the SessionManager, and orchestrates AgentRun instances. |
| Session Management | packages/runtime/src/SessionManager.ts |
Handles session creation, turn tracking, and delegates execution control to AgentRun. |
| Agent Graph | packages/runtime/src/AgentGraph.ts |
Implements the control plane for scheduling dependent work and child sessions triggered by AgentRun. |
| CLI Entry Point | packages/cli/src/commands/run.ts |
Demonstrates the public maka run command that instantiates AgentRun for end-user access. |
| Architecture Docs | ARCHITECTURE.md |
Contains the system diagram and textual description of AgentRun's position in the execution stack. |
Summary
-
AgentRun is the execution authority within Apache Maka's Runtime Host, positioned beneath the
SessionManagerand alongside theRuntimeKernel. -
It manages four critical responsibilities: session/turn identity, complete agent lifecycle (start to shutdown), crash recovery via checkpointing, and tool orchestration with immutable event logging.
-
The component exposes a deterministic API through methods like
AgentRun.start(),runTurn(), andAgentRun.resume(), enabling both interactive CLI usage and automated bot integrations. -
All state mutations are persisted to the Runtime Event Log, allowing AgentRun to reconstruct exact execution context after failures or interruptions.
-
Source code implementation resides primarily in
packages/core/src/agentRun.ts, with orchestration support fromRuntimeHostandSessionManager.
Frequently Asked Questions
What is the difference between AgentRun and SessionManager in Maka?
SessionManager handles session creation, user authentication, and turn tracking at the meta level, while AgentRun owns the actual execution of an agent within a specific session. The SessionManager decides which session should process a request; AgentRun determines how that request executes, manages tool calls, and handles the agent's internal state transitions.
How does AgentRun handle crashes and recovery?
AgentRun implements deterministic replay through the AgentRun.resume() method. When a crash occurs, the RuntimeHost locates the last persisted checkpoint in the Runtime Event Log. AgentRun then re-hydrates its state from this log and continues execution from the exact point of interruption, ensuring no work is lost and side effects remain consistent.
Can AgentRun execute multiple tools in parallel?
While AgentRun maintains a single execution context per session turn, it coordinates with the Tool Runtime to invoke external tools. The current implementation in packages/core/src/agentRun.ts processes tool results sequentially within a turn to ensure deterministic ordering in the event log, though child sessions spawned via the Agent Graph Control Plane can execute concurrent work units.
Where is the AgentRun class defined in the Apache Maka source code?
The AgentRun class is defined in packages/core/src/agentRun.ts, which exports the primary interface including start(), runTurn(), shutdown(), and resume() methods. The runtime instantiation and lifecycle management are orchestrated through packages/runtime-host/src/RuntimeHost.ts, which serves as the singleton entry point for creating AgentRun instances.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →