How Subagents and Task Tools Enable Isolated Workflows in Harness

This lesson explains how Harness uses Subagents—isolated execution units created via the Task tool—to offload heavy, multi‑step operations into separate context windows, custom prompts, and limited toolsets, and how to configure built‑in and custom Subagents with the Claude Code SDK.

AI Digital Ideal
AI Digital Ideal
AI Digital Ideal
How Subagents and Task Tools Enable Isolated Workflows in Harness

Background

In the first four lessons we covered Harness' loop, tools, context handling, hooks, and permissions. A common real‑world need is to delegate "dirty work" to a separate worker so that the main Agent’s context does not get flooded with intermediate data.

What is a Subagent?

A Subagent is an isolated execution unit derived from the Task tool (now called Agent). It is decoupled from the main Agent in three dimensions:

Context window : a fresh context that the main Agent cannot see; only the final result is returned.

System prompt : a custom markdown prompt that replaces the default Claude Code system prompt.

Tool set : a whitelist of tools (e.g., only Read, Grep, Glob) that the Subagent may use.

Position in the Agentic Loop

When the main Agent reaches step ③ (tool execution) it can emit a special tool_use block of type Agent. The Subagent then runs its own loop, performing any number of tool calls, and finally returns a single text message that the main Agent records as one tool_result entry.

Key insight: a Subagent may execute 100 tool calls, but the main Agent’s history grows by only one message.

Agent tool input schema

type AgentInput = {
  description: string; // 3‑5 word task summary for Harness
  prompt: string;       // full instruction for the Subagent
  subagent_type: string; // e.g. "Explore" / "code‑reviewer"
  model?: "sonnet" | "opus" | "haiku" | "fable"; // optional model override
  resume?: string;      // resume a previous Subagent session
  run_in_background?: boolean;
  max_turns?: number;   // maximum loop iterations
  name?: string;
  mode?: "acceptEdits" | "bypassPermissions" | "default" | "dontAsk" | "plan";
  isolation?: "worktree"; // file‑system isolation
};

Processing steps after tool_use

Look up the subagent_type to find its definition.

Create a fresh context window.

Load the Subagent’s custom system prompt (markdown body).

Mount only the tools allowed by the Subagent.

Insert the prompt as the Subagent’s first user message.

Run the Subagent’s loop until it finishes or reaches max_turns.

When the Subagent ends, Harness writes its final text output as a single tool_result back to the main history.

Built‑in Subagents

Explore – tools: Read, Glob, Grep. Typical use: research a codebase, read documentation, find files. Special point: skips CLAUDE.md and parent git state for speed.

Plan – same tool set as Explore. Typical use: outline a task, list implementation steps. Special point: also skips CLAUDE.md.

general‑purpose – inherits all tools. Typical use: complex multi‑step tasks that require both reading and writing. Special point: inherits the main session model (e.g., Opus).

Anthropic designed Explore and Plan to be fast, cheap, and read‑only, matching the philosophy that temporary workers should not inherit the whole company’s internal state.

Custom Subagents

A custom Subagent is defined by a markdown file with YAML front‑matter. Two discovery scopes are supported:

User‑level : ~/.claude/agents/ – shared across projects.

Project‑level : .claude/agents/ – version‑controlled, team‑shared.

The name field must be unique within its scope. Example code‑reviewer definition:

---
name: code-reviewer
description: Reviews code for correctness, security, and maintainability
tools: Read, Grep, Glob
model: sonnet
---

You are a senior code reviewer. Review for:

1. Correctness: logic errors, edge cases, null handling
2. Security: injection, auth bypass, data exposure
3. Maintainability: naming, complexity, duplication

The front‑matter fields have the following meanings:

name (required) – identifier used by the main Agent.

description (required) – short English sentence that the LLM matches against when deciding whether to invoke the Subagent.

tools – whitelist; omitted means inherit all main Agent tools.

model – optional model override.

Defining Subagents via the Python SDK

from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

async for message in query(
    prompt="Use the code‑reviewer agent to review this codebase",
    options=ClaudeAgentOptions(
        allowed_tools=["Read", "Glob", "Grep", "Agent"],
        agents={
            "code‑reviewer": AgentDefinition(
                description="Expert code reviewer. Use proactively after code changes.",
                prompt="You are a senior code reviewer. Focus on code quality, security, and best practices.",
                tools=["Read", "Glob", "Grep"],
                model="sonnet",
                maxTurns=3,
            )
        },
    ),
):
    print(message)

The full AgentDefinition dataclass includes optional fields such as disallowedTools, memory, mcpServers, initialPrompt, background, effort, and permissionMode.

CLI shortcut: pass JSON via --agents to register a temporary Subagent for a single session.

Result schema returned to the main Agent

{
  "result": str,          // final text from the Subagent
  "usage": dict | null,   // token usage statistics
  "total_cost_usd": float | null,
  "duration_ms": int
}

The main Agent writes the result as a tool_result. It may optionally summarize the text again before replying to the user.

To force the raw Subagent output to the user, add a sentence to the main Agent’s system prompt: "When a subagent returns a result, present it verbatim without summarization."

File‑system isolation (worktree)

By default Subagents share the same Git repository as the main Agent. When multiple Subagents modify files concurrently, conflicts can arise. Adding isolation: "worktree" creates a temporary Git worktree (independent working directory and branch) for that Subagent. File changes stay inside the worktree and do not affect the main workspace; the worktree is cleaned up automatically if no changes are made, or the user is prompted to merge if there are modifications.

Two isolation layers can be combined: context isolation (default) plus worktree isolation.

When to use a Subagent

Researching an unfamiliar codebase – many Read / Grep calls whose intermediate output can be compressed into a short summary.

Running parallel independent analyses – different Subagent types can execute simultaneously.

Needing a specialized prompt (e.g., security audit) that is deeper than the main Agent’s generic prompt.

The main context is already near its token limit and you want to avoid polluting it.

When NOT to use a Subagent

Frequent back‑and‑forth between main Agent and Subagent – each round adds a full dispatch‑result cycle.

The intermediate result cannot be compressed and the main Agent needs to reference raw data.

The task is trivial (one or two steps) – using a Subagent would be overkill.

Decision rule (from Anthropic): if the result can be compressed to a few lines, exceeds 10 loops, or can run in parallel → use Subagent; otherwise → avoid.

Quiz recap

Context isolation: a Subagent that runs 30 Read calls adds only **one** message to the main history.

For a research task with a tight main context, the built‑in Explore Subagent is the correct choice.

A vague description like "Reviews code" may not be selected; a detailed description such as "Reviews code for security vulnerabilities in auth, input handling, and OWASP Top 10" improves matching.

Lesson summary

The core takeaway is that Subagents are isolated agents that run their own loop, keep intermediate steps hidden, and return a single final text result. The former SDK Task tool is now called Agent. Harness provides three built‑in Subagents (Explore, Plan, general‑purpose) and allows custom Subagents via markdown/YAML files or programmatic SDK definitions. Adding isolation: "worktree" gives file‑system isolation. Use Subagents when the work can be compressed, exceeds ten loops, or can be parallelized; avoid them for simple, tightly coupled interactions.

Recommended reading

Claude Code: Subagents (creation, configuration, usage)

Claude Agent SDK: Subagents ( AgentDefinition fields, programmatic definition)

Claude Code: Tools reference (Agent tool behavior and output schema)

Claude Code: Skill vs Subagent (when to use each – next lesson)

Claude Code: Worktrees (detailed file‑system isolation mechanism)

FAQ

Can the main Agent dispatch multiple Subagents in parallel?

Yes. Claude’s built‑in parallel tool calls allow the main Agent to emit several Agent blocks at once, launching multiple Subagents concurrently. All Subagents share the main session’s permissions, so differing permission requirements need separate permissionMode settings.

Can a Subagent spawn its own Subagents (nesting)?

Yes. A Subagent is a full Agent and can use the Agent tool itself, but nesting depth is limited; two levels are usually safe, deeper nesting often fails.

Can Subagents use Skills?

Yes. The AgentDefinition.skills field lists Skills to load for the Subagent, though each added Skill increases the system prompt size.

How does Harness handle Subagent failures?

Errors are returned as a tool_result marked as an error. The main Agent can retry or choose an alternative plan. A SubagentStop hook can be registered to inspect last_assistant_message for error signals.

Are built‑in Explore and a custom Subagent identical from the main Agent’s perspective?

Both appear in the combined list of available Subagents (built‑in + user‑level + project‑level). The difference lies in definition: Explore automatically skips CLAUDE.md, while a custom Subagent follows whatever defaults you set unless you explicitly add skipCLAUDEMd: true.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

IsolationPython SDKWorktreeClaude CodeSubagentAgentic LoopTask tool
AI Digital Ideal
Written by

AI Digital Ideal

Express ideas with code, expand imagination with AI.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.