Subagent Session Spawning Architecture and Lifecycle in Apache Maka

Apache Maka creates subagent sessions through a three-structure metadata system that links child sessions to parents via durable SQLite storage, with all subagents currently running in foreground mode under a shared Runtime Host.

Apache Maka's subagent session spawning architecture enables a parent session to delegate work to child sessions while maintaining full provenance and execution control. This article examines the complete lifecycle—from tool result generation through metadata persistence to session completion—based on the implementation in apache/maka.

The Three Core Data Structures

Every subagent session is defined by three immutable data structures that travel together through Maka's storage and runtime layers. These structures encode the complete identity, lineage, and execution context of a child session.

SubagentSessionParent

The SubagentSessionParent structure captures the parent-child relationship. It stores the parentSessionId, parentRunId, parentTurnId, optional graph identifiers, and swarm context that place the subagent within a larger computation graph.

SubagentSessionRuntime

The SubagentSessionRuntime structure contains a snapshot of the child's execution environment. This includes the agent ID, model prompt configuration, available tool list, and policy settings that govern how the subagent operates.

SubagentSessionSpawn

The SubagentSessionSpawn structure provides the immutable identity of the initial invocation. It holds the request fingerprint (for deduplication), initial turn ID, and initial run ID that mark the subagent's entry point.

These structures are defined in packages/core/src/session.ts (line 90 defines the allowed SUBAGENT_SESSION_LIFECYCLES) and persisted to SQLite via packages/storage/src/sqlite-session-metadata-store.ts in the session_metadata table columns subagent_parent_*, subagentRuntime (JSON), and subagentSpawn (JSON).

Lifecycle Phase 1: Tool Result Generation

The subagent spawning process begins when a tool execution returns a specialized result type. A ToolResultContent with kind: "subagent" signals the Runtime Host that a child session should be created.

// A tool result that triggers subagent creation
const subagentResult: ToolResultContent = {
  kind: 'subagent',
  status: 'running',
  // Additional UI rendering fields handled by packages/ui/src/tool-activity.tsx
};

The UI layer in packages/ui/src/tool-activity.tsx renders these results with appropriate visual indicators that distinguish subagent invocations from standard tool outputs.

Lifecycle Phase 2: Session Provisioning

When the Runtime Host detects a subagent result, it delegates to SessionManager.provisionSubagent in packages/runtime/src/session-manager.ts. This method orchestrates the complete child session creation.

The provisioning flow performs three critical operations:

  • Child workspace construction — creates an isolated execution context with resolved tool dependencies
  • Fresh ID generation — allocates unique identifiers for the initial turn and run
  • Structure assembly — builds the SubagentSessionParent, SubagentSessionRuntime, and SubagentSessionSpawn records (lines 915–224 in the provisioning request construction)
// SessionManager creates the child session with full provenance
const child = await sessionManager.provisionSubagent({
  source: {
    sessionId: parentId,
    runId: parentRunId,
    turnId: parentTurnId,
    toolCallId
  },
  graphId,      // Optional: graph context for swarm coordination
  workId,       // Optional: work unit identifier
  operatorId,   // Optional: executing operator reference
  // Preset configuration for model selection can also be provided
});

The resulting child.header contains all three subagent structures, ready for storage persistence.

Lifecycle Phase 3: Metadata Persistence

The storage layer in packages/storage/src/sqlite-session-metadata-store.ts enforces idempotent child creation. Before insertion, it validates that no existing record contains a subagentSpawn field for the target session (error thrown at lines 860–862).

// Storage layer validates and persists subagent metadata
const record = await store.readRecordSync(child.sessionId);
console.log(record.header.subagentParent?.parentSessionId);  // → parentId
console.log(record.header.subagentSpawn?.initialRunId);      // → first run id

The store uses INSERT OR IGNORE semantics to silently deduplicate attempts to recreate a child with the same requestFingerprint. This guarantees that network retries or duplicate tool results never spawn multiple orphaned sessions.

Lifecycle Phase 4: Execution

Once persisted, the child session executes under the same Runtime Host as its parent. The host tracks progress through the standard turn/run pipeline:

  • AgentRun orchestrates the agent's iterative execution loop
  • RuntimeKernel manages tool invocations and state transitions

The child session operates with its own subagentRuntime configuration, allowing different models, prompts, or tool sets than the parent while remaining visible in the same UI column.

Lifecycle Phase 5: Completion and UI Rendering

When the subagent finishes, its final status (completed, failed, or other terminal states) is recorded in durable storage. UI components such as packages/ui/src/titlebar-session-identity.tsx retrieve the subagentParent data to render the complete parent-child trail, enabling users to navigate hierarchical session trees.

Lifecycle Phase 6: Cleanup and Retention

Because all subagent metadata lives in SQLite, parent sessions can:

  • Retrieve historic child runs for debugging or auditing
  • Reconcile graph edges using stored graphId and workId references
  • Retry the same spawn using the stored requestFingerprint (automatically deduplicated by the storage layer)

Supported Lifecycle Modes

Apache Maka currently supports only one lifecycle mode for subagents:

Mode Behavior Use Case
foreground Child runs in same UI column as parent, visible to user Interactive delegation, step-by-step workflows

The foreground mode is defined in packages/core/src/session.ts in SUBAGENT_SESSION_LIFECYCLES at line 90. Background or detached subagent execution is not yet implemented.

Architectural Guarantees

The subagent spawning architecture provides three foundational properties:

  • Idempotent creation — Duplicate provisionSubagent calls with identical fingerprints produce a single session via INSERT OR IGNORE in sqlite-session-metadata-store.ts
  • Strong provenance — Every subagent carries complete lineage including parentSessionId, parentRunId, parentTurnId, and optional swarm identifiers
  • Clean separation — Core layer defines contracts, runtime layer orchestrates provisioning, storage layer handles persistence and lookup

Summary

  • Apache Maka subagents are created through a three-structure metadata system (SubagentSessionParent, SubagentSessionRuntime, SubagentSessionSpawn) defined in packages/core/src/session.ts
  • Provisioning happens via SessionManager.provisionSubagent in packages/runtime/src/session-manager.ts, which constructs child workspaces and allocates fresh IDs
  • Storage layer enforces idempotency through fingerprint-based deduplication in packages/storage/src/sqlite-session-metadata-store.ts (lines 860–862)
  • All subagents run in foreground lifecycle mode, visible in the same UI column as their parents
  • Complete lineage and retry capability is preserved through durable SQLite storage of parent references and request fingerprints

Frequently Asked Questions

What triggers a subagent session to spawn in Apache Maka?

A subagent spawns when any tool returns a ToolResultContent with kind: "subagent". The Runtime Host detects this result type and invokes SessionManager.provisionSubagent to create the child session with full metadata linking it to the parent.

How does Apache Maka prevent duplicate subagent creation?

The storage layer uses INSERT OR IGNORE semantics and validates that no subagentSpawn record exists before insertion (error at lines 860–862 of sqlite-session-metadata-store.ts). The requestFingerprint in SubagentSessionSpawn serves as the deduplication key.

Can subagents run in the background or detached from their parents?

No. Currently only the foreground lifecycle is supported, as defined by SUBAGENT_SESSION_LIFECYCLES in packages/core/src/session.ts at line 90. Background subagents would require additional runtime and UI infrastructure not yet present in the codebase.

Where is subagent metadata stored and how can it be inspected?

All metadata persists to SQLite in the session_metadata table: parent relationships in subagent_parent_* columns, runtime configuration in subagentRuntime (JSON), and spawn identity in subagentSpawn (JSON). Use store.readRecordSync(sessionId) to retrieve complete headers for inspection or parent-child navigation.

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 →