从 Background Tasks 到 Agent Teams:Claude Code 的自动化生态

从 Background Tasks 到 Agent Teams:Claude Code 的自动化生态

上一篇我们看了 Claude Code 在"推理自主性"这条轴上的进化。这篇看另一条轴:从单线程终端工具到多端协同的自动化平台

Claude Code 最初只是"你在终端里打字,它回答"。现在呢?它能后台跑任务、事件驱动响应、定时调度、手机远程操控、浏览器里直接开 session、多个实例组队协作。这些特性组合起来,构成了一个完整的"Agent 自动化生态"。

源文件:luongnv89/claude-howto/09-advanced-features/README.md


Background Tasks:让 Agent 边聊边干活

是什么

Background Tasks 让长时间运行的操作异步执行------跑测试、构建 Docker、部署------你可以继续和 Claude 聊别的。

vbnet 复制代码
User: Run the full test suite in the background

Claude: Starting tests in background (task-id: bg-1234)
You can continue working while tests run.

[你继续和 Claude 聊别的]

Claude: Background task bg-1234 completed:
  245 tests passed
  3 tests failed

翻译:后台任务让你在等待长时间操作时不被阻塞------跑测试的同时可以让 Claude 帮你做别的事。

管理命令

bash 复制代码
/task list           # 列出所有任务
/task status bg-1234 # 查看进度
/task show bg-1234   # 查看输出
/task cancel bg-1234 # 取消任务

配置

json 复制代码
{
  "backgroundTasks": {
    "enabled": true,
    "maxConcurrentTasks": 5,
    "notifyOnCompletion": true,
    "autoCleanup": true,
    "logOutput": true
  }
}

实践模式:并行开发

vbnet 复制代码
User: Run the build in the background       → bg-5001
User: Also run the linter in background     → bg-5002
User: While those run, let's implement the new API endpoint

[Claude 一边实现 API,后台在跑 build 和 lint]

Claude: Build completed successfully (bg-5001)
Claude: Linter found 12 issues (bg-5002)

这就是 Claude Code 的"多线程"体验------一个对话窗口,多个并行任务。


Monitor Tool:事件驱动,零 token 等待

是什么

Monitor(v2.1.98)解决的是一个 token 经济学问题:以前用 /loopsleep 轮询,每次循环都烧一个完整的 API round-trip,不管有没有变化。Monitor 在命令静默时消耗 零 token,有事件时立即唤醒。

Polling with /loop or sleep burns a full API round-trip every cycle, whether or not anything changed. Monitor stays silent until an event fires, consuming zero tokens while the command is quiet.
翻译:用 /loopsleep 轮询,每个循环都消耗完整的 API round-trip,不管有没有变化。Monitor 在命令静默时保持沉默------消耗零 token------事件触发时立即响应。

两种模式

Stream filter ------ 监听持续输出的流:

bash 复制代码
tail -f /var/log/app.log | grep --line-buffered "ERROR"

Poll-and-emit filter ------ 周期性检查,有变化时才输出:

bash 复制代码
last=$(date -u +%Y-%m-%dT%H:%M:%SZ)
while true; do
  gh api "repos/owner/repo/issues/123/comments?since=$last" || true
  last=$(date -u +%Y-%m-%dT%H:%M:%SZ)
  sleep 30
done

实际场景

"Start my dev server and monitor it for errors."

Claude 启动服务器作为后台任务,挂上 Monitor filter(tail -F server.log | grep --line-buffered -E "ERROR|FATAL"),然后 session 进入静默。日志出现错误的瞬间,Claude 被唤醒------自动重启服务器、修 bug、或通知你。

关键陷阱

Warning : When piping into grep, always use grep --line-buffered. Without it, grep buffers stdout in 4KB chunks, which can delay events by minutes on low-traffic streams. This is the #1 way Monitor breaks in practice.
翻译(警告):当 pipe 到 grep 时,必须grep --line-buffered。否则 grep 会以 4KB 为块缓冲 stdout,在低流量流上可能延迟几分钟。这是 Monitor 实践中最常见的故障原因。


Scheduled Tasks:定时调度

三种调度方式

1. /loop ------ 间隔执行

bash 复制代码
/loop 5m check if the deployment finished
/loop check build status every 30 minutes

2. 一次性提醒

arduino 复制代码
remind me at 3pm to push the release branch
in 45 minutes, run the integration tests

3. /schedule ------ 云端持久调度

bash 复制代码
/schedule daily at 9am run the test suite and report failures

/loop vs /schedule 的区别

维度 /loop (CronCreate) /schedule (Cloud)
持久性 Session-scoped,重启后消失 云端持久,不需要本地运行
限制 最多 50 个/session,3 天自动过期 持久
要求 Pro/Max OAuth(API key 用户不可用)
漏跑 不补跑 云端保证执行

行为细节

维度 说明
循环抖动 最多 10% 间隔(最大 15 分钟)
一次性抖动 :00/:30 边界上最多 90 秒
漏跑处理 不补跑------Claude Code 没运行就跳过
上限 50 个/session

API key 用户的限制

/schedule auto-disabled by API-key tiers (v2.1.139): Cloud /schedule is silently unavailable when any of ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, or apiKeyHelper is set --- even if you are also logged in with claude.ai.
翻译:当设置了 ANTHROPIC_API_KEYANTHROPIC_AUTH_TOKENapiKeyHelper 时,云端 /schedule 被静默禁用------即使你同时登录了 claude.ai

实用模式:部署监控

vbnet 复制代码
/loop 5m check the deployment status of the staging environment.
        If the deploy succeeded, notify me and stop looping.
        If it failed, show the error logs.

Routines :Anthropic 在 2026-05-14 的产品博客中把这个特性称为"Routines"。CLI 命令仍然是 /schedule


Headless Mode / Print Mode:CI/CD 集成

是什么

claude -p(Print Mode)是非交互模式------输入一段 prompt,Claude 执行完输出结果,不需要人工交互。这是把 Claude Code 嵌入 CI/CD 的关键。

bash 复制代码
# 基本用法
claude -p "Run all tests and generate coverage report"

# 结构化输出
claude -p --output-format json "Analyze code quality"

# 限制自主轮数
claude -p --max-turns 5 "refactor this module"

# Schema 验证
claude -p --json-schema '{"type":"object","properties":{"issues":{"type":"array"}}}' \
  "find bugs in this code"

GitHub Actions 示例

yaml 复制代码
# .github/workflows/code-review.yml
name: AI Code Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code
      - name: Run Claude Code Review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p --output-format json \
            --max-turns 3 \
            "Review this PR for:
            - Code quality issues
            - Security vulnerabilities
            - Performance concerns
            - Test coverage
            Output results as JSON" > review.json
      - name: Post Review Comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const review = JSON.parse(fs.readFileSync('review.json', 'utf8'));
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: JSON.stringify(review, null, 2)
            });

源文件参考:09-advanced-features/README.md#headless-mode

Safe Mode(排障模式)

bash 复制代码
claude --safe-mode
# 或
CLAUDE_CODE_SAFE_MODE=1 claude

--safe-mode starts Claude Code with all customizations disabled --- CLAUDE.md, plugins, skills, hooks, and MCP servers are all turned off.
翻译:--safe-mode 以禁用所有自定义的方式启动 Claude Code------CLAUDE.md、插件、技能、钩子和 MCP 服务器全部关闭。用于排查是配置问题还是 Claude Code 自身问题。


Remote Control:手机操控本地 Agent

是什么

Remote Control(v2.1.51+)让你从手机、平板或任何浏览器继续控制本地运行的 Claude Code session。本地在跑,远程在看------不是把代码搬到云上。

bash 复制代码
# 启动
claude remote-control
claude remote-control --name "Auth Refactor"

# 或在 session 内
/remote-control

连接方式

方式 说明
Session URL 启动时打印,浏览器打开即可
QR Code 按空格键显示可扫描的二维码
按名查找 claude.ai/code 或 Claude 手机 app 里找到

安全模型

diff 复制代码
- 不在本机开任何入站端口
- 仅出站 HTTPS over TLS
- 多个短期、窄范围 token
- Session 隔离

Remote Control vs Claude Code on Web

维度 Remote Control Claude Code on Web
执行位置 你的机器 Anthropic 云端
本地工具 完整访问 MCP、文件、CLI 无本地依赖
场景 从手机继续本地工作 从任何浏览器开始全新工作

Push Notifications(v2.1.110)

Remote Control 激活时,在 /config 里启用"Push when Claude decides",Claude 会在长任务完成或需要你输入时发手机推送。

企业管控

json 复制代码
{
  "disableRemoteControl": true
}

翻译:管理员可以在组织级别完全禁用 Remote Control------设置在 managed/policy scope 下,用户无法覆盖。


Web Sessions:浏览器里的 Claude Code

bash 复制代码
# 从 CLI 创建云端 session
claude --remote "implement the new API endpoints"

# 从云端拉回本地
claude --teleport
# 或在 session 内
/teleport

Web Sessions 跑在 Anthropic 云端------关掉浏览器 session 还在跑。和 Remote Control 的区别:Remote Control 是"本地跑,远程看",Web Sessions 是"云端跑,随时看"。


Desktop App:独立应用的完整体验

Desktop App(macOS + Windows)提供了比终端更丰富的界面:

Feature 说明
Diff view 文件级 visual review + inline comments,Claude 读评论后修改
App preview 自动启动 dev server + 内嵌浏览器实时验证
PR monitoring GitHub CLI 集成,CI 失败自动修复,checks 全过自动 merge
Parallel sessions 侧边栏多 session + 自动 Git worktree 隔离
Scheduled tasks 循环任务(每小时/每天/工作日/每周),app 打开时执行
Connectors GitHub / Slack / Linear / Notion / Asana / Calendar

App Preview 配置

json 复制代码
// .claude/launch.json
{
  "command": "npm run dev",
  "port": 3000,
  "readyPattern": "ready on",
  "persistCookies": true
}

/desktop 命令

从 CLI session 一键交接到 Desktop App:

bash 复制代码
/desktop

Channels:实时推送进 Session

是什么

Channels(Research Preview)让外部服务通过 MCP servers 把事件推送到运行中的 Claude Code session------不需要轮询。

bash 复制代码
claude --channels discord,telegram,imessage,webhooks
集成 能力
Discord 接收/回复 Discord 消息
Telegram 接收/回复 Telegram 消息
iMessage 接收 iMessage 通知
Webhooks 接收任意 webhook 事件

工作原理

markdown 复制代码
1. MCP servers 作为 channel plugins 连接外部服务
2. 消息/事件被推送到活跃的 Claude Code session
3. Claude 在 session context 中读取并回复
4. 不需要轮询------实时推送

企业管控

json 复制代码
{
  "allowedChannelPlugins": ["discord", "telegram"]
}

Auth 变更(v2.1.128+)

--channels now works with both Pro/Max OAuth and API-key (console) authentication. Earlier releases required OAuth.
翻译:--channels 现在支持 Pro/Max OAuth 和 API-key 两种认证方式。早期版本只支持 OAuth。


Chrome Integration:浏览器自动化

是什么

Chrome Integration(beta,v2.0.73+)连接 Claude Code 到你的 Chrome 或 Edge 浏览器,实现 live web automation 和调试。

bash 复制代码
claude --chrome      # 启用
claude --no-chrome   # 禁用
/chrome              # session 内切换

能力

能力 说明
Live debugging 实时读 console logs、检查 DOM、调试 JavaScript
Design verification 对比渲染页面和设计稿
Form validation 测试表单提交、输入验证、错误处理
Web app testing 操作有登录态的 app(Gmail、Notion 等)
Data extraction 抓取网页内容
Session recording 录制浏览器操作为 GIF

安全模型

Chrome extension 管理逐站权限------你授权哪个网站,Claude 才能操作哪个。遇到登录页或 CAPTCHA,Claude 暂停等你手动处理。

限制

  • 仅 Chrome 和 Edge(Brave、Arc 等不支持)
  • WSL 下不可用
  • Bedrock/Vertex/Foundry 不支持

Git Worktrees:隔离的并行工作空间

基本用法

bash 复制代码
claude --worktree   # 或 claude -w

启动后 Claude 在 <repo>/.claude/worktrees/<name> 创建隔离 worktree,不影响主 working directory。

核心配置

baseRef(v2.1.133)------worktree 从哪个 commit 分支:

json 复制代码
{
  "worktree": {
    "baseRef": "fresh"   // 默认:从 origin/<default-branch>
    // "head"            // 从本地 HEAD(保留 unpushed commits)
  }
}

bgIsolation(v2.1.143)------后台 session 是否隔离:

json 复制代码
{
  "worktree": {
    "bgIsolation": "none"   // 后台 session 直接编辑当前 working copy
    // 默认是创建独立 worktree
  }
}

Sparse Checkout for Monorepos

json 复制代码
{
  "worktree": {
    "sparsePaths": ["packages/my-package", "shared/"]
  }
}

Worktree 生命周期

工具/事件 说明
EnterWorktree 进入 worktree(v2.1.157 可中途切换)
ExitWorktree 退出并清理
WorktreeCreate hook worktree 创建时触发
WorktreeRemove hook worktree 移除时触发
无变更自动清理 session 结束时,没有改动的 worktree 自动删除

Sandboxing:OS 级隔离

是什么

Sandboxing 在 OS 层面限制 Claude 执行的 Bash 命令------文件系统访问和网络连接都被隔离。

bash 复制代码
claude --sandbox       # 启用
claude --no-sandbox    # 禁用
/sandbox               # session 内切换

配置示例

json 复制代码
{
  "sandbox": {
    "enabled": true,
    "failIfUnavailable": true,
    "filesystem": {
      "allowWrite": ["/Users/me/project"],
      "allowRead": ["/Users/me/project", "/usr/local/lib"],
      "denyRead": ["/Users/me/.ssh", "/Users/me/.aws"]
    },
    "network": {
      "allowedDomains": ["*.example.com"],
      "deniedDomains": ["evil.example.com"]
    },
    "enableWeakerNetworkIsolation": true
  }
}

deniedDomains 覆盖通配符(v2.1.113+)

json 复制代码
{
  "sandbox": {
    "network": {
      "allowedDomains": ["*.example.com"],
      "deniedDomains": ["evil.example.com"]
    }
  }
}

翻译:通配符放行 example.com 下所有域名,但 deniedDomains 仍然可以阻止特定命名的主机。

Linux/WSL 自定义路径(v2.1.133+)

json 复制代码
{
  "sandbox": {
    "bwrapPath": "/opt/bubblewrap/bin/bwrap",
    "socatPath": "/opt/socat/bin/socat"
  }
}

Agent Teams:多实例协作(实验性)

是什么

Agent Teams 让多个 Claude Code 实例协作完成一个任务------一个 team lead 协调,多个 teammates 独立工作。

bash 复制代码
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1

工作机制

sql 复制代码
Team Lead(协调者)
    ├── Teammate A(独立 context window)
    ├── Teammate B(独立 context window)
    └── Teammate C(独立 context window)
    
共享:Task List(自协调)
角色定义:.claude/agents/ 目录或 --agents 标志

A team lead coordinates the overall task and delegates subtasks to teammates. Teammates work independently, each with their own context window. A shared task list enables self-coordination between team members.
翻译:Team Lead 协调整体任务并委派子任务给 teammates。每个 teammate 有独立的 context window,通过共享的 task list 实现自协调。

显示模式

bash 复制代码
claude --teammate-mode in-process  # 默认:同一终端进程内
claude --teammate-mode tmux        # 每个 teammate 一个 tmux split pane
claude --teammate-mode auto        # 自动选择

适用场景

  • 大规模重构------不同 teammate 处理不同模块
  • 并行 code review 和实现
  • 跨多文件的协调变更

和 Dynamic Workflows 的区别

维度 Dynamic Workflows Agent Teams
编排方式 确定性脚本(Claude 编写并执行) Team Lead 动态协调
通信机制 输入/输出传递 共享 Task List
数量级 几十到几百 subagent 少量 teammates(通常 2-5)
状态 正式特性(v2.1.154) 实验性
适用 大规模并行覆盖(审计/迁移) 角色分工协作

全景:Claude Code 的多端自动化生态

把所有特性放到一张地图上:

scss 复制代码
                    ┌─────────────────────────────────────────┐
                    │          Claude Code 自动化生态          │
                    └─────────────────────────────────────────┘
                                      │
          ┌───────────────────────────┼───────────────────────────┐
          │                           │                           │
    ┌─────▼─────┐            ┌───────▼───────┐           ┌──────▼──────┐
    │  后台异步  │            │   多端接入     │           │  定时调度    │
    └─────┬─────┘            └───────┬───────┘           └──────┬──────┘
          │                          │                          │
  Background Tasks          Remote Control              /loop (session)
  Monitor Tool              Web Sessions                /schedule (cloud)
  Dynamic Workflows         Desktop App                 Routines
                            Chrome Integration
                            Channels (push)
                                      │
                            ┌─────────▼─────────┐
                            │   协作与隔离       │
                            └─────────┬─────────┘
                                      │
                            Agent Teams (多实例)
                            Git Worktrees (隔离)
                            Sandboxing (安全)

选型决策表

我想... 用什么
跑测试同时写代码 Background Tasks
监控日志,有错误自动响应 Monitor Tool
每天定时跑一个任务 /schedule (云端)
手机上看 Claude 进度 Remote Control
不在本地跑,纯云端 Web Sessions / Desktop Remote
Claude 响应 Discord 消息 Channels
自动化 CI/CD code review Headless Mode (claude -p)
多人分工大重构 Agent Teams
并行几十个审计任务 Dynamic Workflows (ultracode)
操作浏览器里的 web app Chrome Integration
安全隔离不信任的操作 Sandboxing + Worktrees

版本变更速查

版本 变更
v2.0.73 Chrome Integration beta
v2.1.51 Remote Control 上线
v2.1.72 Scheduled Tasks 上线
v2.1.98 Monitor Tool 上线
v2.1.110 TUI Mode + Push Notifications + Desktop App
v2.1.113 Sandbox deniedDomains
v2.1.128 Channels 支持 API-key auth
v2.1.133 worktree.baseRef + bwrapPath/socatPath
v2.1.139 /schedule 对 API-key 用户静默禁用
v2.1.143 worktree.bgIsolation + PowerShell default on Windows
v2.1.154 Dynamic Workflows + ultracode
v2.1.157 EnterWorktree 可中途切换

总结

Claude Code 的自动化能力在 2026 上半年经历了爆发式扩展:

后台异步层面:Background Tasks 让你不被阻塞,Monitor Tool 让事件驱动替代轮询(省 token、响应快),Dynamic Workflows 让多 Agent 确定性协作。

多端接入层面:Remote Control 让手机操控本地 Agent,Web Sessions 让云端全天候运行,Desktop App 提供比终端更丰富的 review 界面,Chrome Integration 打通浏览器自动化,Channels 让外部消息实时推送进 session。

调度与隔离层面:/loop 做 session 级调度,/schedule 做云端持久调度,Git Worktrees 提供隔离的并行工作空间,Sandboxing 在 OS 层面提供安全边界,Agent Teams 让多个实例角色分工。

核心判断:这些特性单独看都不复杂,组合使用时才展现真正的威力。一个完整的自动化工作流可能是这样的:

ini 复制代码
Auto Mode + Background Tasks + Monitor + Remote Control + /schedule
= 你设定好规则,Claude 自主运行,有事推送你手机,每天定时汇报

这已经不是"终端聊天工具"了------这是一个 Agent 操作系统的雏形。


本文素材来源:luongnv89/claude-howto/09-advanced-features