How Apache Maka Handles Child Agent Coordination and Root Turn Orchestration

Apache Maka handles child agent coordination through a pluggable callback system in AiSdkBackend while orchestrating root turns via the TurnScope object, which enforces strict concurrency limits and deterministic finalization prompts to ensure isolated, bounded execution.

Every interaction with a language model in the apache/maka repository is treated as a turn. The root turn—the initial user-facing interaction—creates a TurnScope that manages all mutable state and child agent spawning, keeping the core runtime agnostic to specific execution environments while maintaining strict safety boundaries.

Root Turn Architecture and the TurnScope Lifecycle

When a root turn begins, the AiSdkBackend instantiates a TurnScope object that encapsulates all ephemeral state for that specific interaction. According to the source code in packages/runtime/src/ai-sdk-backend.ts (lines 109-131), this scope tracks the abort controller, active tools, injected steering messages, and image budgets.

The TurnScope serves as the single source of truth for the turn's lifecycle. It prevents overlapping turns from interfering with each other through properties like abort and loopStopRequested, ensuring that child agents spawned during the turn cannot corrupt the parent state. This isolation is fundamental to Maka’s deterministic execution model.

Child Agent Coordination via Pluggable Callbacks

Maka avoids hard-wiring child agent implementations. Instead, the runtime delegates execution to host-provided callbacks supplied during backend instantiation. In packages/runtime/src/ai-sdk-backend.ts (lines 66-78), the AiSdkBackendInput interface accepts the following optional callbacks:

spawnChildAgent?: (input: {
  parentRunId: string;
  spec: AgentSpec;
  prompt: string;
  abortSignal: AbortSignal;
  …
}) => Promise<unknown>;

spawnChildSession?: ToolRuntimeInput['spawnChildSession'];
prepareChildAgentResume?: ToolRuntimeInput['prepareChildAgentResume'];
resumeChildAgent?: ToolRuntimeInput['resumeChildAgent'];
retryChildAgent?: (input: { … }) => Promise<unknown>;
readChildAgentOutput?: ToolRuntimeInput['readChildAgentOutput'];

When a tool or the backend needs to delegate work to a child agent, it invokes spawnChildAgent with the parent run ID and abort signal. The host environment—whether a local process, container, or remote service—handles the actual instantiation. This design decouples the orchestration logic from the execution environment, allowing the same runtime to operate in serverless functions, long-running servers, or local development setups.

Root Turn Orchestration Strategies

The root turn does not merely spawn children arbitrarily. It employs a multi-layered orchestration strategy to enforce capacity limits and deterministic completion.

Effective Orchestration Resolution

Before executing a turn, the backend resolves the effective orchestration strategy via resolveEffectiveOrchestration. This strategy object defines hard limits defined in packages/runtime/src/ai-sdk-backend.ts:

  • MAX_ACTIVE_CHILD_AGENT_RUNS_PER_TURN (line 445) bounds the number of concurrent child processes.
  • MAX_ACTIVE_SUBAGENT_TOOLS_PER_TURN (line 446) limits active sub-agent tool instances.

These constants prevent runaway parallelism that could exhaust compute budgets or trigger rate limits.

Concurrency Limits and ToolRuntime Enforcement

The TurnScope stores a ToolRuntime instance that enforces per-turn capacity constraints. When spawnChildAgent is invoked, the runtime checks the current active count against MAX_ACTIVE_CHILD_AGENT_RUNS_PER_TURN as defined in packages/runtime/src/tool-runtime.js (line 447). If the limit is reached, the request is rejected immediately, protecting the root turn from resource starvation.

Deterministic Finalization with Budget Prompts

To guarantee that child turns conclude with usable output, Maka injects a finalization prompt at the end of a child agent’s execution. Defined as CHILD_STEP_BUDGET_FINALIZATION_PROMPT in packages/runtime/src/ai-sdk-backend.ts (lines 302-307), this prompt forces the model to produce a concise answer without invoking additional tools:

const CHILD_STEP_BUDGET_FINALIZATION_PROMPT = [
  '<step_budget_finalization>',
  'This is the final budgeted step for this child-agent turn.',
  'Do not call tools. Return the best concise final answer now using evidence already gathered.',
  'Clearly separate verified findings from inference and explicitly name any remaining gaps.',
  '</step_budget_finalization>',
].join('\n');

This ensures the root turn receives a deterministic payload when the child session resumes, eliminating non-termination risks.

Event Correlation and Session Linking

Child agents generate events linked to their parent via unique session identifiers. The SessionEvent type defined in packages/core/events.ts (line 639) includes a childSessionId field. When the root turn processes the event stream, it correlates child events to their originating sessions, enabling proper ordering, replay, and debugging across distributed executions.

Implementation Examples

The following snippets demonstrate how to integrate child agent coordination into your Maka application.

Supplying Child Agent Callbacks

Configure the backend with host-specific spawning logic:

import { AiSdkBackend } from '@maka/runtime';

const backend = new AiSdkBackend({
  // … other required fields …
  spawnChildAgent: async ({ parentRunId, spec, prompt, abortSignal }) => {
    // Host-specific logic: start a new process or container
    const child = await startChildProcess({ spec, prompt, signal: abortSignal });
    return child;                      // Must resolve when the child is ready
  },

  readChildAgentOutput: async ({ childSessionId }) => {
    const output = await fetchChildOutput(childSessionId);
    return output;                     // Returns a SessionEvent[] for the root turn
  },
});

Spawning Child Agents Within Tools

Implement tools that delegate to child agents:

export const myTool: MakaTool = {
  name: 'run_subtask',
  async exec({ input, runtime }) {
    // Ask the backend to spawn a child agent
    const child = await runtime.spawnChildAgent({
      parentRunId: runtime.runId,
      spec: { /* agent spec */ },
      prompt: 'Please solve sub‑task X',
      abortSignal: runtime.abortSignal,
    });

    // Wait for the child’s output before proceeding
    const childEvents = await runtime.readChildAgentOutput({
      childSessionId: child.sessionId,
    });

    // Return the child’s result as a normal tool result
    return { type: 'content', value: childEvents };
  },
};

Summary

  • TurnScope isolation: Every root turn creates a TurnScope in AiSdkBackend (lines 109-131) that encapsulates mutable state and prevents cross-turn interference.
  • Pluggable callbacks: Child agent coordination relies on host-provided functions like spawnChildAgent passed during backend construction (lines 66-78), keeping the runtime environment-agnostic.
  • Hard concurrency limits: The runtime enforces MAX_ACTIVE_CHILD_AGENT_RUNS_PER_TURN and MAX_ACTIVE_SUBAGENT_TOOLS_PER_TURN via ToolRuntime (lines 445-447 in tool-runtime.js).
  • Deterministic completion: Child turns always end with the CHILD_STEP_BUDGET_FINALIZATION_PROMPT (lines 302-307), ensuring concise, tool-free final outputs.
  • Event correlation: The childSessionId field in SessionEvent (@maka/core/events.ts, line 639) enables the root turn to track and merge child agent results.

Frequently Asked Questions

How does Maka prevent a root turn from spawning unlimited child agents?

Maka enforces a hard limit through MAX_ACTIVE_CHILD_AGENT_RUNS_PER_TURN defined in the orchestration strategy. The ToolRuntime instance stored in TurnScope tracks active child runs and rejects spawn requests that exceed this threshold, preventing resource exhaustion and runaway parallelism.

Can I use custom infrastructure to run child agents in Maka?

Yes. The runtime does not hard-wire child agent execution. You provide spawnChildAgent and related callbacks when constructing AiSdkBackend. The runtime forwards all spawn requests to your implementation, allowing integration with Kubernetes, AWS Lambda, local processes, or any other execution environment.

How does the root turn know when a child agent has finished?

Child agents conclude their execution after receiving the CHILD_STEP_BUDGET_FINALIZATION_PROMPT, which forces a final answer without tool calls. The host implementation then resolves the spawnChildAgent promise or signals completion via readChildAgentOutput. The root turn correlates these results using the childSessionId field present in all child-generated SessionEvent objects.

What happens if a child agent exceeds the turn budget?

Maka’s TurnScope manages an image budget and step counters. If a child agent consumes its allocated budget, the finalization prompt forces immediate termination with the best available answer. The abortSignal passed during spawning also allows the root turn to cancel children that exceed time or resource limits.

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 →