# 策展 · X (Twitter) 🔥

> 📖 本站完整內容索引（documentation index）：[llms.txt](/llms.txt)

> 作者：ClaudeDevs (@ClaudeDevs) · 平台：X (Twitter) · 日期：2026-05-07

> 原始來源：https://x.com/ClaudeDevs/status/2052069321355182447

## 中文摘要

Claude Managed Agents 新增多代理協調與夢境自學習功能。

@ClaudeDevs 介紹 Claude Managed Agents 的全新功能，包括 multiagent orchestration、基於 rubric 的 outcomes loop 自改善、夢境（dreaming）自學習，以及 webhooks 通知。這些更新讓 Agent 能協調子任務、自我迭代優化，並透過背景處理精煉記憶，提升複雜工作處理能力。所有 API 請求需使用 `managed-agents-2026-04-01` beta header，SDK 會自動設定。

**多代理協調（Multi-agent Orchestration）**

Multi-agent orchestration 讓 coordinator Agent 協調其他子代理完成複雜任務，每個子代理擁有獨立 context window，但共享 container 與檔案系統。適合平行化獨立子任務（如多來源搜尋、檔案分析）、專門化路由（如安全 Agent 或文件 Agent）、或升級複雜任務至更強模型。支援最大 25 個 concurrent threads，coordinator 只 delegate 一層，最多 20 個 unique agents，但可呼叫多個副本。

配置 coordinator 時設定 `multiagent` 宣告代理列表，例如 "Engineering Lead" 使用 `claude-opus-4-7` 模型，system prompt 為 "You coordinate engineering work. Delegate code review to the reviewer agent and test writing to the test agent."，tools 為 `[{"type": "agent_toolset_20260401"}]`

```bash
coordinator=$(curl -fsS https://api.anthropic.com/v1/agents \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01" \
  -H "content-type: application/json" \
  -d @- <<EOF
{
  "name": "Engineering Lead",
  "model": "claude-opus-4-7",
  "system": "You coordinate engineering work. Delegate code review to the reviewer agent and test writing to the test agent.",
  "tools": [
    {
      "type": "agent_toolset_20260401"
    }
  ],
  "multiagent": {
    "type": "coordinator",
    "agents": [
      {"type": "agent", "id": "$REVIEWER_AGENT_ID"},
      {"type": "agent", "id": "$TEST_WRITER_AGENT_ID"}
    ]
  }
}
EOF
)
```

```bash
ant beta:agents create <<YAML
name: Engineering Lead
model: claude-opus-4-7
system: You coordinate engineering work. Delegate code review to the reviewer agent and test writing to the test agent.
tools:
  - type: agent_toolset_20260401
multiagent:
  type: coordinator
  agents:
    - type: agent
      id: $REVIEWER_AGENT_ID
    - type: agent
      id: $TEST_WRITER_AGENT_ID
YAML
```

```python
coordinator = client.beta.agents.create(
    name="Engineering Lead",
    model="claude-opus-4-7",
    system="You coordinate engineering work. Delegate code review to the reviewer agent and test writing to the test agent.",
    tools=[
        {"type": "agent_toolset_20260401"},
    ],
    multiagent={
        "type": "coordinator",
        "agents": [
            {"type": "agent", "id": reviewer_agent.id},
            {"type": "agent", "id": test_writer_agent.id},
        ],
    },
)
```

`multiagent.agents` 可指定 `{"type": "agent", "id": agent.id}`（預設最新版本）、`{"type": "agent", "id": agent.id, "version": agent.version}`（固定版本）或 `{"type": "self"}`（產生自身副本）。建立 session 時參照 coordinator。

```bash
session=$(curl -fsSL https://api.anthropic.com/v1/sessions \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01" \
  -H "content-type: application/json" \
  -d @- <<EOF
{
  "agent": "$COORDINATOR_ID",
  "environment_id": "$ENVIRONMENT_ID"
}
EOF
)
SESSION_ID=$(jq -r '.id' <<< "$session")
```

```bash
ant beta:sessions create \
  --agent "$COORDINATOR_ID" \
  --environment-id "$ENVIRONMENT_ID"
```

```python
session = client.beta.sessions.create(
    agent=coordinator.id,
    environment_id=environment.id,
)
```

詳細文件見 [multi-agent 文件](https://platform.claude.com/docs/en/managed-agents/multi-agent)。

**會話執行緒管理（Session Threads）**

Session-level event stream (`/v1/sessions/:id/events/stream`) 提供 primary thread 視圖，濃縮所有 threads 活動；非 coordinator Agent 的完整活動不會顯示，但會呈現開始/結束及 blocking events 如工具權限請求。Session status 為所有 Agent 活動聚合，若任一 thread 為 `running`，整體即 `running`。

列出 threads：

```bash
curl -fsS "https://api.anthropic.com/v1/sessions/$SESSION_ID/threads" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01" \
  | jq -r '.data[] | "[\(.agent.name)] \(.status)"'
```

```bash
ant beta:sessions:threads list --session-id "$SESSION_ID"
```

```python
for thread in client.beta.sessions.threads.list(session.id):
    print(f"[{thread.agent.name}] {thread.status}")
```

中斷特定 thread（省略 `session_thread_id` 則針對 primary thread）：

```bash
curl -fsS "https://api.anthropic.com/v1/sessions/$SESSION_ID/events?beta=true" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01" \
  -H "content-type: application/json" \
  -d "{\"events\": [{\"type\": \"user.interrupt\", \"session_thread_id\": \"$THREAD_ID\"}]}"
```

對 blocked on `requires_action` 的 child thread，中斷會拒絕每個 pending tool call，並 emit `session.thread_status_idle` 帶 `stop_reason: end_turn`；已 `idle` 的 thread 則無效。

歸檔 thread（釋放 25 thread limit，僅限 `idle` 狀態）：

```bash
curl -fsS -X POST "https://api.anthropic.com/v1/sessions/$SESSION_ID/threads/$THREAD_ID/archive" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01"
```

若 `running` 或 blocked，先中斷再歸檔：

```bash
curl -fsS "https://api.anthropic.com/v1/sessions/$SESSION_ID/events?beta=true" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01" \
  -H "content-type: application/json" \
  -d "{\"events\": [{\"type\": \"user.interrupt\", \"session_thread_id\": \"$THREAD_ID\"}]}"

curl -fsS -X POST "https://api.anthropic.com/v1/sessions/$SESSION_ID/threads/$THREAD_ID/archive" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01"
```

**事件串流與監控（Event Streaming）**

Primary thread 顯示關鍵事件，如 `session.thread_created`、`session.thread_status_running`、`session.thread_status_idle`（含 `stop_reason`）、`session.thread_status_terminated`、`agent.thread_message_received`（含 `from_session_thread_id`、`from_agent_name`、`content`）、`agent.thread_message_sent`。

串流特定 thread events（bash）：

```bash
curl -fsSN "https://api.anthropic.com/v1/sessions/$SESSION_ID/threads/$THREAD_ID/stream?beta=true" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01" |
  while IFS= read -r line; do
    [[ $line == data:* ]] || continue
    json=${line#data: }
    case $(jq -r '.type' <<<"$json") in
      agent.message)
        printf '%s' "$(jq -j '.content[] | select(.type == "text") | .text' <<<"$json")"
        ;;
      session.thread_status_idle)
        break
        ;;
    esac
  done
```

Python 範例：

```python
with client.beta.sessions.threads.events.stream(
    thread.id,
    session_id=session.id,
) as stream:
    for event in stream:
        match event.type:
            case "agent.message":
                for block in event.content:
                    if block.type == "text":
                        print(block.text, end="")
            case "session.thread_status_idle":
                break
```

類似支援 TypeScript、C#、Go、Java、PHP、Ruby 的串流與 list events API。

工具確認範例（允許 `always_ask` 工具，Python）：

```python
for event_id in stop.event_ids:
    client.beta.sessions.events.send(
        session.id,
        events=[
            {
                "type": "user.tool_confirmation",
                "tool_use_id": event_id,
                "result": "allow",
            }
        ],
    )
```

詳細事件文件見 [define-outcomes 文件](https://platform.claude.com/docs/en/managed-agents/define-outcomes)。

**成果導向工作流程（Outcomes Loop）**

Outcomes 將 session 從對話轉為工作，定義最終成果外觀與品質 rubric，Agent 自評估並迭代至符合。harness 自動配置獨立 grader sub-agent（分離 context window），逐項評估 artifact 對 rubric 符合度，並指出差距。

Rubric 撰寫提示：使用明確可評分準則，如 "The CSV contains a price column with numeric values"，避免模糊描述。範例 DCF Model rubric 涵蓋 Revenue Projections、Cost Structure、Discount Rate、Terminal Value、Output Quality 等 12 項。

上傳 rubric（需額外 `files-api-2025-04-14` beta header）：

```bash
rubric=$(curl -fsSL https://api.anthropic.com/v1/files \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01,files-api-2025-04-14" \
  -F file=@/tmp/rubric.md)
rubric_id=$(jq -r '.id' <<<"$rubric")
```

建立 session 後發送 `user.define_outcome`（Agent 立即啟動，`max_iterations` 預設 3、最大 20）：

```bash
session=$(curl -fsSL https://api.anthropic.com/v1/sessions \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01" \
  --json @- <<EOF
{
  "agent": "$agent_id",
  "environment_id": "$environment_id",
  "title": "Financial analysis on Costco"
}
EOF
)
session_id=$(jq -r '.id' <<<"$session")

curl -fsSL "https://api.anthropic.com/v1/sessions/$session_id/events" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01" \
  --json @- >/dev/null <<EOF
{
  "events": [
    {
      "type": "user.define_outcome",
      "description": "Build a DCF model for Costco in .xlsx",
      "rubric": {"type": "text", "content": "# DCF Model Rubric\n..."},
      "max_iterations": 5
    }
  ]
}
EOF
```

事件包括 `span.outcome_evaluation_start`（iteration 從 0 開始）、`span.outcome_evaluation_ongoing`（heartbeat）、`span.outcome_evaluation_end`（result: `satisfied` 轉 `idle`、`needs_revision` 迭代、`max_iterations_reached`、`failed`、`interrupted`）。檢查 outcome status 透過串流或 poll session。

檢索 outcomes（Python）：

```python
session = client.beta.sessions.retrieve(session.id)
for outcome in session.outcome_evaluations:
    print(f"{outcome.outcome_id}: {outcome.result}")
```

Agent 輸出檔案置於 `/mnt/session/outputs/`，idle 後透過 Files API 下載（scope 到 session）：

```python
files = client.beta.files.list(scope_id=session.id)
if files.data:
    content = client.beta.files.download(files.data[0].id)
    content.write_to_file("/tmp/output.txt")
```

**Webhooks 通知**

Webhooks 避免輪詢，通知 session、thread、outcome、vault 狀態變化。於 [Console](https://platform.claude.com/settings/workspaces/default/webhooks) 註冊 HTTPS 443 endpoint，訂閱事件類型，使用 signing secret 驗證 `X-Webhook-Signature`。

Session webhook events 示例：
- `session.status_run_started`：轉 `running`
- `session.status_idled`：等待輸入
- `session.status_rescheduled`：自動重試
- `session.status_terminated`：終止錯誤
- `session.thread_created`：新 multiagent thread
- `session.outcome_evaluation_ended`：迭代完成

Python webhook 驗證：

```python
from flask import Flask, request
import anthropic

client = anthropic.Anthropic()  # 讀取 ANTHROPIC_WEBHOOK_SIGNING_KEY
app = Flask(__name__)

@app.route("/webhook", methods=["POST"])
def webhook():
    try:
        event = client.beta.webhooks.unwrap(
            request.get_data(as_text=True),
            headers=dict(request.headers),
        )
    except Exception:
        return "invalid signature", 400
    if event.data.type == "session.status_idled":
        print("session idled:", event.data.id)
    return "", 200
```

處理重試（相同 `event.id` 捨棄）、排序用 `created_at`，非 2xx 觸發重試，~20 次失敗自動停用。

**夢境自學習（Dreaming）**

Dreaming 是研究預覽功能（[申請存取](https://claude.com/form/claude-managed-agents)），背景處理多 session 記憶，精煉重組（合併重複、替換過時、提煉洞見）。輸入既有 memory store + 最多 100 sessions，輸出新 memory store，不修改輸入。需額外 `dreaming-2026-04-21` beta header，支援 `claude-opus-4-7`、`claude-sonnet-4-6`。

建立 dream：

```bash
dream=$(curl -s https://api.anthropic.com/v1/dreams \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01,dreaming-2026-04-21" \
  -H "content-type: application/json" \
  --data @- <<EOF
{
  "inputs": [
    { "type": "memory_store", "memory_store_id": "$store_id" },
    { "type": "sessions", "session_ids": ["$session_a", "$session_b"] }
  ],
  "model": "claude-opus-4-7",
  "instructions": "Focus on coding-style preferences; ignore one-off debugging notes."
}
EOF
)
dream_id=$(jq -r '.id' <<< "$dream")
```

輪詢狀態至 `completed`，提取 output memory store ID 並附加至新 session。生命週期：`pending`、`running`、`completed`、`failed`、`canceled`。取消 dream（僅 `pending`/`running`）：

```bash
curl -s -X POST "https://api.anthropic.com/v1/dreams/$dream_id/cancel" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: managed-agents-2026-04-01,dreaming-2026-04-21"
```

歸檔（僅 terminal 狀態）與 list dreams 支援多語言 SDK。錯誤如 `input_memory_store_unavailable` 若輸入中途被刪除。計費按 model token 速率，線性依 sessions 數量；限制：每 dream 100 sessions、`instructions` 4,096 字元。詳細見 [dreams 文件](https://platform.claude.com/docs/en/managed-agents/dreams)、[webhooks 文件](https://platform.claude.com/docs/en/managed-agents/webhooks#supported-event-types)。入門使用 [claude-api skill](https://github.com/anthropics/skills/tree/main/skills/claude-api)。

## 標籤

Agent, 功能更新, 框架更新, 記憶系統, Anthropic, Claude
