Skip to content

docs: expand sub-agent architecture guide#419

Merged
claude-code-best merged 1 commit into
claude-code-best:mainfrom
suger-m:codex/sub-agents-docs
May 6, 2026
Merged

docs: expand sub-agent architecture guide#419
claude-code-best merged 1 commit into
claude-code-best:mainfrom
suger-m:codex/sub-agents-docs

Conversation

@suger-m
Copy link
Copy Markdown
Contributor

@suger-m suger-m commented May 6, 2026

Summary

  • Rewrite the sub-agent architecture guide around AgentTool routing, permissions, and sync/async execution paths.
  • Document task notifications, SendMessage continuation, TaskOutput/TaskStop behavior, failure cleanup, fork modes, worktree isolation, and result schemas.
  • Add practical examples, troubleshooting notes, and source-reading paths for future maintenance.

View in Codesmith
Need help on this PR? Tag @codesmith with what you need.

  • Let Codesmith autofix CI failures and bot reviews

Summary by CodeRabbit

  • Documentation
    • Substantially expanded sub-agent documentation with comprehensive guidance on execution paths, lifecycle state machines, permission models, synchronous/asynchronous patterns, fork behavior, and isolation mechanics. New sections cover MCP wait logic, agent definition strategies, runtime orchestration, and tool pool management with extensive usage examples and troubleshooting guidance.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 6, 2026

📝 Walkthrough

Walkthrough

The docs/agent/sub-agents.mdx documentation file is substantially rewritten and expanded from roughly 168 lines to 949 lines (net +781). The new version comprehensively covers sub-agent mechanics: four execution paths, permission models, synchronous and asynchronous lifecycles, fork behavior, Worktree isolation, MCP orchestration, routing rules, lifecycle state machines, extensive usage examples, troubleshooting guidance, and source code reading recommendations.

Changes

Sub-Agent Documentation Expansion

Layer / File(s) Summary
Document Header & Navigation
docs/agent/sub-agents.mdx (lines 2–7)
Title, description, keywords, and goal statement updated to reflect broader sub-agent mechanics coverage.
Core Concepts & Execution Paths
docs/agent/sub-agents.mdx (lines 9–51)
Introduction of four execution paths (named agent, AgentTool fork, slash command fork, runForkedAgent), main flow overview from model tool_use through AgentTool to finalization, and gate conditions.
AgentTool Input Parameters & Agent Definitions
docs/agent/sub-agents.mdx (lines 52–129)
Comprehensive parameter descriptions (基础参数, teammate-related, isolation, cwd), visibility rules, precedence rules among inputs and agent definitions, and frontmatter field documentation with example blocks.
Permission & Lifecycle Models
docs/agent/sub-agents.mdx (lines 147–301)
MCP, hooks, and skills; routing rules; permission startup and tool pool models; fork recursion protection; synchronous sub-agent characteristics; asynchronous lifecycle management and progress updates.
Messaging, Queuing & State Management
docs/agent/sub-agents.mdx (lines 304–435)
Queue consumption semantics, task notifications, SendMessage routing, TaskOutput and TaskStop behavior, error handling, cleanup, and failure/cancellation paths for both sync and async flows.
Fork & Slash-Command Execution Paths
docs/agent/sub-agents.mdx (lines 457–567)
Fork workflow including gate controls, inheritance semantics, recursion protection, model resolution priority, slash command skill frontmatter translation, and runForkedAgent() internal service entry point.
Isolation & State Machine Details
docs/agent/sub-agents.mdx (lines 577–676)
Worktree lifecycle, creation, path translation, cleanup behavior, outputSchema handling, and high-level lifecycle state transitions across the three main branches.
Observable Outputs & Usage Patterns
docs/agent/sub-agents.mdx (lines 681–741)
Progress, UI, and transcript observability; typical call examples in JSON and natural language for synchronous, asynchronous, teammate, worktree, and slash-command flows.
Guidance & Maintenance
docs/agent/sub-agents.mdx (lines 793–859)
Troubleshooting checklist, path selection decision tree, common misunderstandings corrections, source code reading order for validation, and maintenance tips for key files.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • claude-code-best/claude-code#231: Overlapping changes to the same sub-agents documentation file covering execution paths, fork gates, model resolution, async lifecycle, and worktree/transcript details.

Poem

🐰 Through rabbit paths and branching trails,
Sub-agents leap where structure prevails,
Fork, sync, and async—three ways to go,
With docs expanded, now we all know!
Worktrees bloom where agents run free,
A burrow of wisdom for you and me. 🌿

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'docs: expand sub-agent architecture guide' accurately and concisely describes the main change: a substantial expansion and rewrite of the sub-agent architecture documentation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
docs/agent/sub-agents.mdx (1)

42-50: ⚡ Quick win

Make these source entry points clickable.

One of the main values of this guide is “按源码读”,but plain code spans are not navigable and can silently rot. Repo-relative links would make the section much easier to use and give link checking a chance to catch moved files.

✏️ Example approach
-| `src/tools/AgentTool/AgentTool.tsx` | `Agent` 工具定义、路由、同步/异步生命周期 |
+| [`src/tools/AgentTool/AgentTool.tsx`](../../src/tools/AgentTool/AgentTool.tsx) | `Agent` 工具定义、路由、同步/异步生命周期 |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/agent/sub-agents.mdx` around lines 42 - 50,
将文中列出的源码入口从普通代码片段改为仓库相对链接:把每个 ``src/...`` 代码片段(例如
`src/tools/AgentTool/AgentTool.tsx`, `src/tools/AgentTool/runAgent.ts`,
`src/services/tools/toolExecution.ts`, `src/query.ts`,
`src/tasks/LocalAgentTask/LocalAgentTask.tsx`)替换为 Markdown 链接格式
[文件名](../相对路径/到/该文件)(在 docs/agent/sub-agents.mdx
中直接使用相对路径即可),确保链接目标与仓库实际路径一致并在替换后运行链接检查(或 CI 提供的 markdown link
checker)以捕获移动或重命名的文件。
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/agent/sub-agents.mdx`:
- Around line 68-75: Clarify that the special teammate branch is taken when both
name and a team context are present, whether the team is provided explicitly via
team_name or inherited from appState.teamContext.teamName; update the text so
readers know that name combined with an inherited current team context also
routes to spawnTeammate() (returning teammate_spawned) rather than the normal
runAgent() local agent path, and explicitly note that only the flattened team
roster prevents nested teammate spawns with a name.
- Around line 463-467: Update the docs to clarify the environment variable
command is PowerShell-only and add a POSIX (bash/zsh) variant: label the
existing example as "PowerShell" and add a second fenced example labeled "bash /
zsh" that uses FEATURE_FORK_SUBAGENT=1 bun run dev; reference the feature name
FEATURE_FORK_SUBAGENT and the command bun run dev so reviewers can find and edit
the existing example.

---

Nitpick comments:
In `@docs/agent/sub-agents.mdx`:
- Around line 42-50: 将文中列出的源码入口从普通代码片段改为仓库相对链接:把每个 ``src/...`` 代码片段(例如
`src/tools/AgentTool/AgentTool.tsx`, `src/tools/AgentTool/runAgent.ts`,
`src/services/tools/toolExecution.ts`, `src/query.ts`,
`src/tasks/LocalAgentTask/LocalAgentTask.tsx`)替换为 Markdown 链接格式
[文件名](../相对路径/到/该文件)(在 docs/agent/sub-agents.mdx
中直接使用相对路径即可),确保链接目标与仓库实际路径一致并在替换后运行链接检查(或 CI 提供的 markdown link
checker)以捕获移动或重命名的文件。
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 90af4e5b-85fc-4a9d-9f2b-e812f037e3f0

📥 Commits

Reviewing files that changed from the base of the PR and between 5c107e5 and fd66ddc.

📒 Files selected for processing (1)
  • docs/agent/sub-agents.mdx

Comment thread docs/agent/sub-agents.mdx
Comment on lines +68 to +75
| 参数 | 类型 | 必填 | 作用 | 影响路径 |
|------|------|------|------|----------|
| `name` | `string` | 否 | 给 spawned agent 命名,使其可被 `SendMessage({ to: name })` 定向 | 与 `team_name` 或当前 team context 一起出现时触发 teammate spawn;普通后台子 Agent 中也会注册 `name -> agentId` 方便后续发送消息 |
| `team_name` | `string` | 否 | 指定要加入或使用的 team | 与 `name` 一起触发 `spawnTeammate()`;省略时可继承当前 `appState.teamContext.teamName` |
| `mode` | permission mode | 否 | teammate spawn 的权限模式提示 | 当前实现只用于 teammate 的 `plan_mode_required: spawnMode === 'plan'`;它不是普通本地子 Agent 的 `permissionMode` 覆盖 |

`name + team_name` 是一条独立分支:它不会进入普通 `runAgent()` 本地子 Agent 路径,而是调用 `spawnTeammate()`,返回 `teammate_spawned`。如果在 teammate 内继续带 `name` spawn teammate,会被拒绝,因为 team roster 是扁平结构。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Clarify that inherited team context also takes the teammate branch.

This section narrows the special case to name + team_name, but the table just above says name plus an inherited current team context can also route to spawnTeammate(). As written, readers may incorrectly conclude that name alone always stays on the normal runAgent() path.

✏️ Suggested wording
-`name + team_name` 是一条独立分支:它不会进入普通 `runAgent()` 本地子 Agent 路径,而是调用 `spawnTeammate()`,返回 `teammate_spawned`。如果在 teammate 内继续带 `name` spawn teammate,会被拒绝,因为 team roster 是扁平结构。
+`name + team_name`,或 `name` + 当前 team context 继承出来的 team name,是一条独立分支:它不会进入普通 `runAgent()` 本地子 Agent 路径,而是调用 `spawnTeammate()`,返回 `teammate_spawned`。如果在 teammate 内继续带 `name` spawn teammate,会被拒绝,因为 team roster 是扁平结构。
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
| 参数 | 类型 | 必填 | 作用 | 影响路径 |
|------|------|------|------|----------|
| `name` | `string` || 给 spawned agent 命名,使其可被 `SendMessage({ to: name })` 定向 |`team_name` 或当前 team context 一起出现时触发 teammate spawn;普通后台子 Agent 中也会注册 `name -> agentId` 方便后续发送消息 |
| `team_name` | `string` || 指定要加入或使用的 team |`name` 一起触发 `spawnTeammate()`;省略时可继承当前 `appState.teamContext.teamName` |
| `mode` | permission mode || teammate spawn 的权限模式提示 | 当前实现只用于 teammate 的 `plan_mode_required: spawnMode === 'plan'`;它不是普通本地子 Agent 的 `permissionMode` 覆盖 |
`name + team_name` 是一条独立分支:它不会进入普通 `runAgent()` 本地子 Agent 路径,而是调用 `spawnTeammate()`,返回 `teammate_spawned`。如果在 teammate 内继续带 `name` spawn teammate,会被拒绝,因为 team roster 是扁平结构。
| 参数 | 类型 | 必填 | 作用 | 影响路径 |
|------|------|------|------|----------|
| `name` | `string` || 给 spawned agent 命名,使其可被 `SendMessage({ to: name })` 定向 |`team_name` 或当前 team context 一起出现时触发 teammate spawn;普通后台子 Agent 中也会注册 `name -> agentId` 方便后续发送消息 |
| `team_name` | `string` || 指定要加入或使用的 team |`name` 一起触发 `spawnTeammate()`;省略时可继承当前 `appState.teamContext.teamName` |
| `mode` | permission mode || teammate spawn 的权限模式提示 | 当前实现只用于 teammate 的 `plan_mode_required: spawnMode === 'plan'`;它不是普通本地子 Agent 的 `permissionMode` 覆盖 |
`name + team_name`,或 `name` + 当前 team context 继承出来的 team name,是一条独立分支:它不会进入普通 `runAgent()` 本地子 Agent 路径,而是调用 `spawnTeammate()`,返回 `teammate_spawned`。如果在 teammate 内继续带 `name` spawn teammate,会被拒绝,因为 team roster 是扁平结构。
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/agent/sub-agents.mdx` around lines 68 - 75, Clarify that the special
teammate branch is taken when both name and a team context are present, whether
the team is provided explicitly via team_name or inherited from
appState.teamContext.teamName; update the text so readers know that name
combined with an inherited current team context also routes to spawnTeammate()
(returning teammate_spawned) rather than the normal runAgent() local agent path,
and explicitly note that only the flattened team roster prevents nested teammate
spawns with a name.

Comment thread docs/agent/sub-agents.mdx
Comment on lines +463 to 467
fork 默认关闭。需要构建/运行时启用 `FORK_SUBAGENT` feature,例如开发时显式设置:

```powershell
$env:FEATURE_FORK_SUBAGENT='1'; bun run dev
```
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Label this command as PowerShell-only or add a POSIX variant.

$env:FEATURE_FORK_SUBAGENT='1' only works in PowerShell. Without a note, Bash/Zsh users are likely to copy it verbatim and think the feature flag is broken.

✏️ Suggested wording
 ```powershell
+# PowerShell
 $env:FEATURE_FORK_SUBAGENT='1'; bun run dev

+bash +# bash / zsh +FEATURE_FORK_SUBAGENT=1 bun run dev +

</details>

<!-- suggestion_start -->

<details>
<summary>📝 Committable suggestion</summary>

> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

```suggestion
fork 默认关闭。需要构建/运行时启用 `FORK_SUBAGENT` feature,例如开发时显式设置:

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/agent/sub-agents.mdx` around lines 463 - 467, Update the docs to clarify
the environment variable command is PowerShell-only and add a POSIX (bash/zsh)
variant: label the existing example as "PowerShell" and add a second fenced
example labeled "bash / zsh" that uses FEATURE_FORK_SUBAGENT=1 bun run dev;
reference the feature name FEATURE_FORK_SUBAGENT and the command bun run dev so
reviewers can find and edit the existing example.

@claude-code-best claude-code-best merged commit 68c7ebb into claude-code-best:main May 6, 2026
3 checks passed
y574444354 pushed a commit to y574444354/csc that referenced this pull request May 12, 2026
…-docs

docs: expand sub-agent architecture guide
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants