Roger Oriol

Github RSS X Email

Build a Basic AI Agent From Scratch: Agents and Sub-agents


10 minute read · Artificial Intelligence

Previous parts of Build a Basic AI Agent From Scratch:

You can find and clone this code in this blog series' GitHub repo.

In the previous part we gave our agent context compaction and finished the session lifecycle. It can now preserve long work sessions without sending the entire transcript to the model on every request.

So far, however, our harness has had one general-purpose agent. The same agent has to understand a task, investigate the code, make changes and check its own work. On a large task, all of that exploration and implementation also accumulates in one conversation.

In this part we will let the user choose a specialist agent for the current phase, and let an agent delegate a smaller task to a sub-agent. The child will work in its own context and return a concise result, so the main agent can benefit from its work without carrying its whole conversation.

What Do We Mean By Agent?

An agent is not a separate kind of model. It's a definition that tells our harness how to configure a model run: which instructions to use, which tools to make available, and what defaults and limits to apply.

We represent that definition with AgentDefinition:

@dataclass
class AgentDefinition:
    name: str
    description: str = ""
    system_prompt: str = ""
    allowed_tools: set[str] | None = None
    permission_mode: str = "default"
    model: str | None = None
    temperature: float = 0.7
    can_spawn: bool = False
    subagents: set[str] | None = None

The system_prompt is the agent's identity and instructions. As many other agent harnesses do, we will define the system prompt of a custom agent in its SOUL file. The tool allowlist defines what it can do, while permission_mode sets the default permission behavior. We can also choose a model and temperature, and specify whether the agent can spawn children and which child agents it may use.

There are two ways we use these agents. We can switch the active top-level agent while keeping the current conversation, or we can spawn a sub-agent to do a scoped task inside the current agent's work. A top-level switch changes who handles the next turns; a sub-agent is a new run whose result is returned to its parent.

Choosing a Specialist

The harness comes with five built-in agents:

Agent Typical use Tools and behavior
general General coding and research Full toolset; can delegate to plan, explore or review
plan Investigate and prepare an approach Read and planning tools; does not edit files or run shell commands
explore Search and summarize a codebase Read-only file search; cannot spawn children
build Implement a change Full toolset; defaults to acceptEdits and can delegate to explore or review
review Inspect code or a change for issues Read-only tools; reports concrete findings

We can list the available definitions and start the agent best suited to the task:

$ uv run agents-subagents/agent.py --list-agents
$ uv run agents-subagents/agent.py --agent plan

During an interactive session, \agents lists the available agents and \agent explore switches to one. Switching replaces the system prompt and rebuilds the tool schemas for following turns, while keeping the conversation and session ID. This lets us, for example, investigate with a read-only agent and then switch to a build agent without having to start a new session.

An agent's settings are just defaults, they can be overwritten if necessary. For example, the --mode option can override its permission mode. The --tools option can further restrict its allowlist, but cannot add tools the agent definition does not already allow.

Defining Custom Agents

Aside from the agent definitions that come baked into the harness, we can define new agents tuned for a particular project or workflow. We can define one with a SOUL.md file in the project's .agents directory:

.agents/
  researcher/
    SOUL.md

For example:

---
name: researcher
description: Investigates the codebase and cites relevant files.
tools: [read_file, glob_files, grep, spawn_subagent]
can_spawn: true
subagents: [explore]
temperature: 0.2
---
# SOUL

You investigate thoroughly and cite file paths. Do not modify files.

The frontmatter configures the definition, and the Markdown body becomes its system prompt. Here, we give the researcher read tools and permission to ask an explore agent for help. We have not given it write tools, so it cannot edit files through the harness.

The registry loads built-in agents first, then definitions from ~/.agent-harness/agents/, and finally definitions from the project .agents/ directory. A later definition with the same name takes precedence, so a project can customize a built-in agent for that project.

Why Use Sub-agents?

Suppose we ask our agent to fix a bug. It may need to explore several parts of the repository before finding the relevant code. The parent needs to know the findings, but it does not necessarily need every detail on the full path it took to get to those findings.

A sub-agent gives us a way to separate that investigation. The parent calls a tool with an agent name, a short description and a complete task:

spawn_subagent(
    agent="explore",
    description="Find the cache implementation",
    prompt="Locate the cache implementation and identify where the cache key is built. Return relevant file paths, line numbers and a short explanation. Do not modify files."
)

The child starts with its own instructions and the task we supplied. It does not see the parent's conversation, so the prompt must include the goal, relevant constraints and what we want back. Once it finishes, the parent receives its final answer as the tool result and can use it to continue the original task.

The Agent Context

When a child is spawned, the harness first checks that the parent is allowed to spawn agents, that the requested child exists and is allowed, and that the nesting depth has not reached its limit. It then creates a fresh message list using the child's SOUL and the self-contained prompt.

Each child gets its own AgentContext, including its own scratchpad and to-do list. Its tool schemas are filtered to the child's allowlist. The harness runs it through the same reusable turn engine as the top-level agent:

child = AgentContext(
    definition=child_def,
    messages=child_messages,
    bindings=ToolBindings(
        planning=PlanningState(),
        memory=MemoryTools(parent.memory_store, child_id),
        ask=_child_ask,
    ),
    sandbox=parent.sandbox,
    cost_tracker=parent.cost_tracker,
    # Other runtime controls and shared services are passed here too.
)

answer = run_turn(child, prompt)

This creates separate working context, but it does not create a separate copy of the project. The parent and child use the same Docker sandbox and filesystem, so changes the child makes to project files are visible to the parent. They also share the audit log, cost tracker and abort controller.

The child's conversation does not get appended to the parent's message history. Only the child's final answer is returned, and the harness caps its size before handing it back. If session storage is enabled, the child also gets its own session record linked to the parent by parent_id. It is marked kind="subagent" and records the agent and depth. These child sessions are hidden from normal listings unless we request them with --include-subagents.

Permissions, Limits and Parallel Work

A sub-agent cannot pause to ask the user a question. This is because it doesn't actually run as the model in the interactive interface, it actually runs inside the parent's tool call. If one of its actions would require an interactive permission prompt, the harness denies that action and returns the reason. The normal hard policy checks still apply, too.

Delegation is bounded. We can limit nesting with --max-depth, and each agent can have its own turn and tool-call caps. The returned text is capped so a child cannot flood the parent's context. Model usage from parent and children is recorded against the same session cost tracker, so the shared cost limit still applies.

If the model requests several sub-agents in the same turn, the harness can run them concurrently. Their results are added back in the original tool-call order, and --max-concurrent-subagents limits how many run at once. This can speed up independent research tasks, but parallel children still share a filesystem. If two children edit the same file at the same time, their changes can conflict. For parallel work, read-only or non-overlapping tasks are safer.

Let's Test It!

We can first see which agents are available, then start the general agent and ask it to investigate a cache issue:

$ uv run agents-subagents/agent.py --list-agents
general  General-purpose agent with the full toolset.
plan     Read-only planner that proposes an approach for approval.
explore  Fast read-only search and summarise agent.
build    Implementation agent; auto-approves in-tree edits.
review   Read-only reviewer that inspects changes and reports issues.

$ uv run agents-subagents/agent.py
You: Find where the cache key is built and explain whether it includes the locale.

When useful, the parent can delegate the search to explore:

  [subagent] explore @ depth 1: Find the cache implementation
  [tool result] The cache key is built in src/cache.py:42. It includes the URL
  and user ID but not the locale. The request handler passes the locale at
  src/handlers/page.py:18, but it is not part of the key.
Assistant: The cache key does not include the locale, so requests in different
languages could reuse the same cached response. The key is built in src/cache.py.

The exact wording depends on the model, but the important behavior is that the parent gets the findings, not the child's full conversation. If we want to inspect the saved child session, we can list sessions with sub-agents included:

$ uv run agents-subagents/agent.py --list-sessions --include-subagents

What You've Built

Our harness can now use the agent that best fits each phase of work, and agents can delegate scoped tasks to children. This is everything we have built in this chapter:

  • Selectable agents give us different prompts, tool sets and defaults for planning, exploration, building and review.
  • Custom SOUL.md definitions let us add project- or user-specific agents.
  • Sub-agents run with separate messages and planning state, then return a concise, size-limited result.
  • Bounded delegation keeps permissions, depth, concurrency and shared cost under control, while child sessions and audit events make runs inspectable.

What's Next

In the next part of this series, we will explore an alternative way to customize the abilities of our agent. Instead of giving a whole new system prompt to each different agent to make it a specialist, we will toggle in and out different abilities from the same agent. These are called skills. We will implement skills into our harness and find out how we can leverage them to give our agents abilities specific to a concrete situation.