Skip to content

Chapter 9 · Subagents: Expert Delegation ​

Chapter goals: Master defining expert sub-agents with useSubagent(), understand the "fresh context delegation" mechanism and inheritance rules, and design主从协作 multi-Agent architectures.

9.1 Why Subagents Are Needed ​

A single agent's context window is a稀缺资源: asking it to同时 do research, write code, and run tests — intermediate artifacts blow up the context and dilute注意力.

Subagent = a named expert委托对象. The parent agent delegates a focused task to it; the subagent completes it independently in a全新上下文, returning only the final answer —中间推理, tool calls, file reads all stay out of the parent session:

text
Parent Agent (主会话)
   │ task(name='reproducer', prompt='Reproduce issue #42…')
   ▼
Subagent Reproducer (全新上下文) ── independently reads files, runs commands ──┐
   │                                                                            │
   └── ◀──────── only the final结论 returns ────────────────────────────────────┘

9.2 Declaring a Subagent ​

typescript
// src/agents/case-agent.ts
'use agent';
import { useModel, useSubagent } from '@flue/runtime';

// Note: Summarizer is故意【not exported】!
// Exported PascalCase functions get registered as top-level agents,
// while subagents are just一种能力 mounted on the parent agent
function Summarizer() {
  return 'Support summarizing cases into three sentences, highlighting the issue and impact.'; // Return value = subagent instructions
}

export function CaseAgent() {
  useModel('anthropic/claude-sonnet-4-6');

  // Three要素: name, description, agent function
  useSubagent({
    name: 'summarizer',
    // description is the parent model's sole basis for deciding to delegate — write it as carefully as a tool description
    description: 'Summarize a single support case. Use when compressing a long conversation or case details is needed.',
    agent: Summarizer,
  });

  return `
Investigate the support case and give handling建议.
After investigation, delegate the case summary work to the summarizer subagent.`;
}

The subagent's agent function is a普通 agent function: returns instructions,可组合 Hook capabilities. But it is a capability, not an实体 — no own session ID, no HTTP route.

9.3 Delegation Runtime Mechanism ​

Delegation is model-driven. Each agent's toolset has a framework自带的 task tool; declared subagents enter the system prompt as an "Available Agents"目录. Flow:

  1. Parent model judges a块 of work matches a subagent → calls the task tool (with name + task prompt);
  2. Runtime re-renders the subagent function fresh at delegation time, generating its instructions and toolset;
  3. The subagent runs as a分离会话 in the parent environment, uses its own context window to complete the task;
  4. Only the final message returns to the parent会话 as the task result.

Two推论 worth牢记:

  • The task prompt is the全部 briefing. The subagent cannot see the parent对话; the parent指令 must要求 "delegate with a complete,自包含 prompt";
  • Tasks are naturally parallel. The same batch of tool calls executes concurrently; five independent checks = five concurrent sub-sessions, each using its own window.

9.4 Inheritance Rules: Get What You Give ​

typescript
'use agent';
import { useModel, useSkill, useSubagent, useTool } from '@flue/runtime';
import { searchIssues } from '../tools/search-issues.ts';
import reproduce from '../skills/reproduce/SKILL.md';

function Reproducer() {
  // The subagent's own capability组合 — only what's declared here belongs to it
  useSkill(reproduce);
  return 'Verify whether the issue is reproducible per the reproduction skill流程.';
}

export function Triage() {
  useModel('anthropic/claude-sonnet-4-6');
  useTool(searchIssues);      // ← parent's tool; the subagent does NOT inherit
  useSubagent({
    name: 'reproducer',
    description: 'Verify whether a bug report is reproducible.',
    agent: Reproducer,
    // Optional: override the inherited model (if unset, uses the parent's model)
    model: 'anthropic/claude-haiku-4-5',
  });
  return 'Triage the issue. Delegate to reproducer when reproducibility needs confirming.';
}
Inherited ✅Not Inherited ❌
Sandbox and its内置 toolsParent's conversation history
Workspace context (AGENTS.md etc.)Parent's instructions, own tools
Parent's model and reasoning tier*Parent's skills and other subagents
(*unless overridden at definition)Parent's persistent state and initial data

One sentence: 环境继承, 对话隔离. The subagent's world = everything you组合 in its render.

9.5 Collaboration Patterns and Limits ​

typescript
'use agent';
import { useModel, useSubagent } from '@flue/runtime';

function SecurityCheck() { return 'Perform a security audit on the given module; output a risk清单.'; }
function PerfCheck()     { return 'Analyze performance bottlenecks in the given module and量化.'; }

export function ReleaseManager() {
  useModel('anthropic/claude-opus-4-6');

  // Parallel pre-release体检团: three independent checks,互不干扰
  useSubagent({ name: 'security', description: 'Security audit. Required before release.', agent: SecurityCheck });
  useSubagent({ name: 'perf',     description: 'Performance analysis. Use when regression is detected.', agent: PerfCheck });

  return `
Execute pre-release checks:
1. Parallel-delegate security and perf checks;
2. After collecting both conclusions, summarize into a release/block建议.
When delegating,使用包含目标模块路径的完整 prompt.`; // ← explicitly要求自包含 briefing
}

Key constraints:

typescript
// The type signature of subagent definitions — understand the契约 behind the three要素
interface SubagentDefinition {
  name: string;          // Unique identifier in the目录; duplicate names throw
  description: string;   // Parent model's delegation basis;务必写清 "what + when"
  agent: () => string;   // Ordinary agent function;可组合 Hook; do NOT export
  model?: string;        // Optional: override the inherited model, e.g. 'anthropic/claude-haiku-4-5'
}
// Delegation depth上限: 4 layers — parent → child → grandchild → great-grandchild; deeper is拒绝 by runtime
  • Same-name subagents can only be declared once per render; duplicates throw;
  • Delegation depth上限 is 4 layers (subagents can themselves declare their own subagents);
  • Conditional declaration supported — only enters the目录 after a stage flag flips; runtime播报s the变化;
  • Application code can also delegate: naming a subagent in harness.prompt()指令强制路由.

9.6 Chapter Summary ​

  • Subagent = named expert委托: fresh context, returns only the final answer;
  • useSubagent({ name, description, agent }) three要素; the delegate function must not be exported;
  • Delegation走框架保留的 task tool; the prompt is the全部 briefing —务必自包含;
  • Inherits sandbox/workspace/model; does not inherit conversation or parent resources; depth上限 4 layers;
  • Multiple subagents + parallel task =天然的多专家流水线.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. After a subagent completes, what content returns to the parent agent's session?

2. Why is the Summarizer这类 subagent function故意 not exported?

3. What is the delegation depth上限 in Flue?

4. Which of the following is inherited by a subagent from the parent?

🛠️ Hands-On Exercises ​

  1. Add a "refund specialist" subagent to the Chapter 6 customer service agent; compare token consumption before and after delegation.
  2. Design two parallel-check subagents; have the model发起 two tasks同批; observe whether the elapsed time approximates a single check's耗时.
  3. Verify隔离性: have the subagent尝试访问父会话中提到的临时变量信息; confirm it truly cannot see them.

Subagents mastered. Next, Channels: event接入 for Slack/GitHub etc..