Repository Public
1---2title: Build an orchestration mode3url: https://platform.claude.com/docs/en/build-with-claude/mid-conversation-effort-example4description: Build a session-level mode that grants standing consent for multiagent fan-out, switched on and off with mid-conversation system messages.5---67An orchestration mode is a session-level switch: when it is on, the model puts maximum thoroughness behind every substantive request, scouting the task itself and then fanning work out to parallel subagents by default. When it is off, the same orchestration tool goes back to per-request opt-in.89The mode is not an API parameter. It is built entirely from documented pieces:10111. **An effort level:** requests run at a documented [Effort](https://platform.claude.com/docs/en/build-with-claude/effort) value such as `xhigh`. There is no hidden level above the ones on that page. This example sets effort at the top level of each request, which needs no beta header.122. **A mode reminder:** a [mid-conversation system message](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages) tells the model the mode is active, with a one-line refresher every several turns and an exit notice when the mode is turned off. The top-level `system` field never changes, so the cached prefix stays intact.133. **Standing consent in the tool description:** the orchestration tool's description states that while the mode is on, the model should author and run a workflow for every substantive task without asking first.1415<Note>16 This example uses mid-conversation system messages; for the models and platforms that support them, see [Mid-conversation system messages](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages). The fan-out itself multiplies token usage: a single request can spawn many subagent conversations, so reserve the mode for work that justifies the cost.17</Note>1819## Set up the loop2021The example is a single file. The constants control the effort level, the fan-out shape, and how often the mode refresher is re-sent. `MAX_CONCURRENT` caps how many subagents run at the same time (the PHP port is sequential and ignores it); `MAX_TOTAL_SUBTASKS` caps how many the model may queue in a single Workflow call. Splitting the two lets the model plan a large backlog without launching it all at once. The `DOC_TEST_MODE` check caps the loops to a single turn when that environment variable is set, so the automated docs harness can validate that the file compiles and finishes quickly without running the full orchestration; leave it unset when running the example yourself.2223<CodeGroup>24 ```python Python25 import atexit26 import concurrent.futures27 import hashlib28 import json29 import os30 import shutil31 import subprocess32 import sys33 import tempfile34 import threading3536 import anthropic3738 client = anthropic.Anthropic()3940 MODEL = "claude-opus-5"41 EFFORT = "xhigh"4243 SYSTEM_PROMPT = "You are a helpful general-purpose agent. Answer the user's request directly."4445 REQUEST_TIMEOUT_SECONDS = 60046 BASH_TIMEOUT_SECONDS = 6047 TOOL_RESULT_MAX_CHARS = 800048 MAX_CONCURRENT = 1049 DOC_TEST_MODE = bool(os.environ.get("DOC_TEST_MODE"))50 MAX_TOTAL_SUBTASKS = 2 if DOC_TEST_MODE else 20051 MAX_SUBAGENT_TURNS = 1 if DOC_TEST_MODE else 1552 MAX_MAIN_TURNS = 1 if DOC_TEST_MODE else 3053 TURNS_BETWEEN_REFRESHERS = 1054 JOURNAL_PATH = os.environ.get("ORCH_JOURNAL") or "orchestration_journal.json"55 ```5657 ```typescript TypeScript58 import { exec } from "node:child_process";59 import { createHash } from "node:crypto";60 import { rmSync } from "node:fs";61 import { mkdtemp, readFile, rename, writeFile } from "node:fs/promises";62 import { tmpdir } from "node:os";63 import { join } from "node:path";64 import { promisify } from "node:util";6566 import Anthropic from "@anthropic-ai/sdk";6768 const client = new Anthropic();6970 const MODEL = "claude-opus-5";71 const EFFORT = "xhigh";7273 const SYSTEM_PROMPT =74 "You are a helpful general-purpose agent. Answer the user's request directly.";7576 const REQUEST_TIMEOUT_SECONDS = 600;77 const BASH_TIMEOUT_SECONDS = 60;78 const TOOL_RESULT_MAX_CHARS = 8000;79 const MAX_CONCURRENT = 10;80 const DOC_TEST_MODE = Boolean(process.env.DOC_TEST_MODE);81 const MAX_TOTAL_SUBTASKS = DOC_TEST_MODE ? 2 : 200;82 const MAX_SUBAGENT_TURNS = DOC_TEST_MODE ? 1 : 15;83 const MAX_MAIN_TURNS = DOC_TEST_MODE ? 1 : 30;84 const TURNS_BETWEEN_REFRESHERS = 10;85 const JOURNAL_PATH = process.env.ORCH_JOURNAL || "orchestration_journal.json";86 ```8788 ```csharp C#89 using System.Diagnostics;90 using System.Security.Cryptography;91 using System.Text;92 using System.Text.Json;93 using Anthropic;94 using Anthropic.Models.Messages;9596 AnthropicClient client = new();9798 const Model model = Model.ClaudeOpus5;99 var effort = Effort.Xhigh;100101 const string systemPrompt = "You are a helpful general-purpose agent. Answer the user's request directly.";102103 const int requestTimeoutSeconds = 600;104 // The other ports stream with max_tokens 64000. This port uses non-streaming105 // Messages.Create, and the API rejects non-streaming requests at that size.106 // 8192 is the non-streaming ceiling for Opus 4.0 and 4.1 and a conservative107 // choice for newer Opus models.108 const int requestMaxTokens = 8192;109 const int bashTimeoutSeconds = 60;110 const int toolResultMaxChars = 8000;111 const int maxConcurrent = 10;112 var docTestMode = Environment.GetEnvironmentVariable("DOC_TEST_MODE") is { Length: > 0 };113 int maxTotalSubtasks = docTestMode ? 2 : 200;114 int maxSubagentTurns = docTestMode ? 1 : 15;115 int maxMainTurns = docTestMode ? 1 : 30;116 const int turnsBetweenRefreshers = 10;117 var journalPath = Environment.GetEnvironmentVariable("ORCH_JOURNAL") is { Length: > 0 } p ? p : "orchestration_journal.json";118 ```119120 ```go Go121 import (122 "bytes"123 "cmp"124 "context"125 "crypto/sha256"126 "encoding/hex"127 "encoding/json"128 "errors"129 "fmt"130 "log"131 "os"132 "os/exec"133 "path/filepath"134 "strings"135 "sync"136 "time"137138 "github.com/anthropics/anthropic-sdk-go"139 )140141 var client = anthropic.NewClient()142143 const (144 modelID = anthropic.ModelClaudeOpus5145 effort = anthropic.OutputConfigEffortXhigh146147 systemPrompt = "You are a helpful general-purpose agent. Answer the user's request directly."148149 requestTimeoutSeconds = 600150 bashTimeoutSeconds = 60151 toolResultMaxChars = 8000152 maxConcurrent = 10153 turnsBetweenRefreshers = 10154 )155156 var (157 docTestMode = os.Getenv("DOC_TEST_MODE") != ""158 maxTotalSubtasks = ifTest(2, 200)159 maxSubagentTurns = ifTest(1, 15)160 maxMainTurns = ifTest(1, 30)161 journalPath = cmp.Or(os.Getenv("ORCH_JOURNAL"), "orchestration_journal.json")162 )163164 func ifTest(test, normal int) int {165 if docTestMode {166 return test167 }168 return normal169 }170171 ```172173 ```java Java174 import com.anthropic.client.AnthropicClient;175 import com.anthropic.client.okhttp.AnthropicOkHttpClient;176 import com.anthropic.core.JsonValue;177 import com.anthropic.core.RequestOptions;178 import com.anthropic.helpers.MessageAccumulator;179 import com.anthropic.models.messages.ContentBlock;180 import com.anthropic.models.messages.ContentBlockParam;181 import com.anthropic.models.messages.Message;182 import com.anthropic.models.messages.MessageCreateParams;183 import com.anthropic.models.messages.MessageParam;184 import com.anthropic.models.messages.Model;185 import com.anthropic.models.messages.OutputConfig;186 import com.anthropic.models.messages.StopReason;187 import com.anthropic.models.messages.TextBlock;188 import com.anthropic.models.messages.Tool;189 import com.anthropic.models.messages.ToolBash20250124;190 import com.anthropic.models.messages.ToolResultBlockParam;191 import com.anthropic.models.messages.ToolUseBlock;192 import com.fasterxml.jackson.core.JsonProcessingException;193 import com.fasterxml.jackson.core.type.TypeReference;194 import com.fasterxml.jackson.databind.JsonNode;195 import com.fasterxml.jackson.databind.ObjectMapper;196 import java.io.IOException;197 import java.io.UncheckedIOException;198 import java.nio.charset.StandardCharsets;199 import java.nio.file.Files;200 import java.nio.file.Path;201 import java.nio.file.StandardCopyOption;202 import java.security.MessageDigest;203 import java.time.Duration;204 import java.util.ArrayList;205 import java.util.Comparator;206 import java.util.HashMap;207 import java.util.HexFormat;208 import java.util.List;209 import java.util.Map;210 import java.util.Objects;211 import java.util.Optional;212 import java.util.concurrent.Callable;213 import java.util.concurrent.CancellationException;214 import java.util.concurrent.CompletableFuture;215 import java.util.concurrent.ExecutionException;216 import java.util.concurrent.ExecutorService;217 import java.util.concurrent.Executors;218 import java.util.concurrent.Future;219 import java.util.concurrent.TimeUnit;220 import java.util.concurrent.locks.ReentrantLock;221 import java.util.stream.Collectors;222 import java.util.stream.IntStream;223224 AnthropicClient client = AnthropicOkHttpClient.fromEnv();225226 static final Model MODEL = Model.CLAUDE_OPUS_5;227 static final boolean DOC_TEST_MODE =228 !Objects.requireNonNullElse(System.getenv("DOC_TEST_MODE"), "").isEmpty();229 static final OutputConfig.Effort EFFORT = OutputConfig.Effort.XHIGH;230231 static final String SYSTEM_PROMPT =232 "You are a helpful general-purpose agent. Answer the user's request directly.";233234 static final int REQUEST_TIMEOUT_SECONDS = 600;235 static final RequestOptions REQUEST_OPTIONS =236 RequestOptions.builder().timeout(Duration.ofSeconds(REQUEST_TIMEOUT_SECONDS)).build();237 static final int BASH_TIMEOUT_SECONDS = 60;238 static final int TOOL_RESULT_MAX_CHARS = 8000;239 static final int MAX_CONCURRENT = 10;240 static final int MAX_TOTAL_SUBTASKS = DOC_TEST_MODE ? 2 : 200;241 static final int MAX_SUBAGENT_TURNS = DOC_TEST_MODE ? 1 : 15;242 static final int MAX_MAIN_TURNS = DOC_TEST_MODE ? 1 : 30;243 static final int TURNS_BETWEEN_REFRESHERS = 10;244 static final Path JOURNAL_PATH = Path.of(Optional.ofNullable(System.getenv("ORCH_JOURNAL"))245 .filter(s -> !s.isEmpty()).orElse("orchestration_journal.json"));246 ```247248 ```php PHP249 use Anthropic\Client;250 use Anthropic\Messages\ToolUseBlock;251252 $client = new Client();253254 const MODEL = 'claude-opus-5';255 define('DOC_TEST_MODE', (string) getenv('DOC_TEST_MODE') !== '');256 const EFFORT = 'xhigh';257258 const SYSTEM_PROMPT = 'You are a helpful general-purpose agent. Answer the user\'s request directly.';259260 const REQUEST_TIMEOUT_SECONDS = 600;261 const BASH_TIMEOUT_SECONDS = 60;262 const TOOL_RESULT_MAX_CHARS = 8000;263 const MAX_CONCURRENT = 10;264 define('MAX_TOTAL_SUBTASKS', DOC_TEST_MODE ? 2 : 200);265 define('MAX_SUBAGENT_TURNS', DOC_TEST_MODE ? 1 : 15);266 define('MAX_MAIN_TURNS', DOC_TEST_MODE ? 1 : 30);267 const TURNS_BETWEEN_REFRESHERS = 10;268 define('JOURNAL_PATH', getenv('ORCH_JOURNAL') ?: 'orchestration_journal.json');269 ```270271 ```ruby Ruby272 require "anthropic"273 require "digest"274 require "fileutils"275 require "json"276 require "open3"277 require "tmpdir"278279 CLIENT = Anthropic::Client.new280281 MODEL = "claude-opus-5"282 EFFORT = :xhigh283284 SYSTEM_PROMPT = "You are a helpful general-purpose agent. Answer the user's request directly."285286 REQUEST_TIMEOUT_SECONDS = 600287 BASH_TIMEOUT_SECONDS = 60288 TOOL_RESULT_MAX_CHARS = 8000289 MAX_CONCURRENT = 10290 DOC_TEST_MODE = !ENV["DOC_TEST_MODE"].to_s.empty?291 MAX_TOTAL_SUBTASKS = DOC_TEST_MODE ? 2 : 200292 MAX_SUBAGENT_TURNS = DOC_TEST_MODE ? 1 : 15293 MAX_MAIN_TURNS = DOC_TEST_MODE ? 1 : 30294 TURNS_BETWEEN_REFRESHERS = 10295 JOURNAL_PATH = ENV["ORCH_JOURNAL"].to_s.empty? ? "orchestration_journal.json" : ENV["ORCH_JOURNAL"]296 ```297</CodeGroup>298299## Define the mode reminders300301The reminders are short on purpose. They flip the mode and point at the tool description, where the heavyweight instructions live. The full text is sent once when the mode turns on, the refresher is re-sent only after several user turns, and the exit notice is sent once when the mode turns off.302303<CodeGroup>304 ```python Python305 MODE_ENTER = (306 "Orchestration mode is on: optimize for the most exhaustive, correct answer rather than "307 "the fastest one. Use the Workflow tool on every substantive task, sized to the problem's "308 "natural decomposition rather than the maximum the tool allows. See the Workflow tool's "309 "description for standing consent, granularity guidance, and quality patterns. Work solo "310 "only on conversational or trivial turns."311 )312 MODE_REFRESH = (313 "Orchestration mode is still on. Use the Workflow tool; see its standing consent section."314 )315 MODE_EXIT = (316 "Orchestration mode is off. The Workflow tool's standard opt-in rule applies again."317 )318 ```319320 ```typescript TypeScript321 const MODE_ENTER =322 "Orchestration mode is on: optimize for the most exhaustive, correct answer rather than " +323 "the fastest one. Use the Workflow tool on every substantive task, sized to the problem's " +324 "natural decomposition rather than the maximum the tool allows. See the Workflow tool's " +325 "description for standing consent, granularity guidance, and quality patterns. Work solo " +326 "only on conversational or trivial turns.";327 const MODE_REFRESH =328 "Orchestration mode is still on. Use the Workflow tool; see its standing consent section.";329 const MODE_EXIT =330 "Orchestration mode is off. The Workflow tool's standard opt-in rule applies again.";331 ```332333 ```csharp C#334 const string modeEnter =335 "Orchestration mode is on: optimize for the most exhaustive, correct answer rather than "336 + "the fastest one. Use the Workflow tool on every substantive task, sized to the problem's "337 + "natural decomposition rather than the maximum the tool allows. See the Workflow tool's "338 + "description for standing consent, granularity guidance, and quality patterns. Work solo "339 + "only on conversational or trivial turns.";340 const string modeRefresh =341 "Orchestration mode is still on. Use the Workflow tool; see its standing consent section.";342 const string modeExit =343 "Orchestration mode is off. The Workflow tool's standard opt-in rule applies again.";344 ```345346 ```go Go347 const (348 modeEnter = "Orchestration mode is on: optimize for the most exhaustive, correct answer rather than " +349 "the fastest one. Use the Workflow tool on every substantive task, sized to the problem's " +350 "natural decomposition rather than the maximum the tool allows. See the Workflow tool's " +351 "description for standing consent, granularity guidance, and quality patterns. Work solo " +352 "only on conversational or trivial turns."353 modeRefresh = "Orchestration mode is still on. Use the Workflow tool; see its standing consent section."354 modeExit = "Orchestration mode is off. The Workflow tool's standard opt-in rule applies again."355 )356357 ```358359 ```java Java360 static final String MODE_ENTER =361 "Orchestration mode is on: optimize for the most exhaustive, correct answer rather than "362 + "the fastest one. Use the Workflow tool on every substantive task, sized to the problem's "363 + "natural decomposition rather than the maximum the tool allows. See the Workflow tool's "364 + "description for standing consent, granularity guidance, and quality patterns. Work solo "365 + "only on conversational or trivial turns.";366 static final String MODE_REFRESH =367 "Orchestration mode is still on. Use the Workflow tool; see its standing consent section.";368 static final String MODE_EXIT =369 "Orchestration mode is off. The Workflow tool's standard opt-in rule applies again.";370 ```371372 ```php PHP373 const MODE_ENTER =374 'Orchestration mode is on: optimize for the most exhaustive, correct answer rather than '375 . 'the fastest one. Use the Workflow tool on every substantive task, sized to the problem\'s '376 . 'natural decomposition rather than the maximum the tool allows. See the Workflow tool\'s '377 . 'description for standing consent, granularity guidance, and quality patterns. Work solo '378 . 'only on conversational or trivial turns.';379 const MODE_REFRESH =380 'Orchestration mode is still on. Use the Workflow tool; see its standing consent section.';381 const MODE_EXIT =382 'Orchestration mode is off. The Workflow tool\'s standard opt-in rule applies again.';383 ```384385 ```ruby Ruby386 MODE_ENTER =387 "Orchestration mode is on: optimize for the most exhaustive, correct answer rather than " \388 "the fastest one. Use the Workflow tool on every substantive task, sized to the problem's " \389 "natural decomposition rather than the maximum the tool allows. See the Workflow tool's " \390 "description for standing consent, granularity guidance, and quality patterns. Work solo " \391 "only on conversational or trivial turns."392 MODE_REFRESH =393 "Orchestration mode is still on. Use the Workflow tool; see its standing consent section."394 MODE_EXIT =395 "Orchestration mode is off. The Workflow tool's standard opt-in rule applies again."396 ```397</CodeGroup>398399## Grant standing consent in the tool description400401The Workflow tool carries the real behavioral contract: the opt-in rule, the standing consent that applies while the mode is on, granularity guidance for sizing the fan-out, and the quality patterns the model can reach for (a verification wave, a completeness critic, multiphase sequencing). Subagents also get a `report_findings` tool so their results come back as structured JSON instead of prose, and the bash tool is the Anthropic-defined `bash_20250124` tool run locally.402403<CodeGroup>404 ```python Python405 WORKFLOW_TOOL = {406 "name": "Workflow",407 "description": (408 "Orchestrate a multiagent workflow: split a large task into independent subtasks "409 "and run them as parallel agents, then collect their results.\n\n"410 "Opt-in: only use this tool when the user explicitly asks for a workflow, or when a "411 "system message confirms that orchestration mode is on.\n\n"412 "Quality patterns: adversarial verification (a second wave of agents checks the first "413 "wave's findings against the source), a completeness critic (one agent hunts for what "414 "the others missed), and multiphase sequencing (understand, design, implement, and "415 "review as separate workflow calls, reading results between phases). A useful default "416 "is hybrid: scout inline first to discover the work-list, then fan out over it.\n\n"417 "Granularity: scope each subtask to a distinct concern, component, or question rather "418 "than per line or per file section. Scale the count to what the user asked for: a "419 "focused review of a module of a few hundred lines rarely needs more than about ten "420 "subtasks; a broad audit of a large codebase can justify more.\n\n"421 "Standing consent: while a system message confirms orchestration mode is on, that "422 "opt-in is standing. Author and run a workflow for every substantive task by default, "423 "and lean toward verifying findings adversarially. Work solo only on conversational "424 "turns or trivial mechanical edits. When a system message says the mode is off, "425 "revert to the opt-in rule above."426 ),427 "input_schema": {428 "type": "object",429 "properties": {430 "subtasks": {431 "type": "array",432 "items": {"type": "string"},433 "description": "Independent subtask prompts to run as parallel agents",434 }435 },436 "required": ["subtasks"],437 },438 }439440 BASH_TOOL = {"type": "bash_20250124", "name": "bash"}441442 REPORT_TOOL = {443 "name": "report_findings",444 "description": (445 "Report the final findings for your subtask. Call this exactly once, when you are "446 "done investigating; it ends your task."447 ),448 "input_schema": {449 "type": "object",450 "properties": {451 "summary": {"type": "string", "description": "Two or three sentences of synthesis"},452 "findings": {453 "type": "array",454 "items": {455 "type": "object",456 "properties": {457 "claim": {"type": "string", "description": "The finding, one sentence"},458 "evidence": {459 "type": "string",460 "description": "How it was verified (file, line, or command output)",461 },462 "severity": {"type": "string", "enum": ["high", "medium", "low", "info"]},463 },464 "required": ["claim", "evidence", "severity"],465 },466 },467 },468 "required": ["summary", "findings"],469 },470 }471 ```472473 ```typescript TypeScript474 const WORKFLOW_TOOL: Anthropic.Tool = {475 name: "Workflow",476 description:477 "Orchestrate a multiagent workflow: split a large task into independent subtasks " +478 "and run them as parallel agents, then collect their results.\n\n" +479 "Opt-in: only use this tool when the user explicitly asks for a workflow, or when a " +480 "system message confirms that orchestration mode is on.\n\n" +481 "Quality patterns: adversarial verification (a second wave of agents checks the first " +482 "wave's findings against the source), a completeness critic (one agent hunts for what " +483 "the others missed), and multiphase sequencing (understand, design, implement, and " +484 "review as separate workflow calls, reading results between phases). A useful default " +485 "is hybrid: scout inline first to discover the work-list, then fan out over it.\n\n" +486 "Granularity: scope each subtask to a distinct concern, component, or question rather " +487 "than per line or per file section. Scale the count to what the user asked for: a " +488 "focused review of a module of a few hundred lines rarely needs more than about ten " +489 "subtasks; a broad audit of a large codebase can justify more.\n\n" +490 "Standing consent: while a system message confirms orchestration mode is on, that " +491 "opt-in is standing. Author and run a workflow for every substantive task by default, " +492 "and lean toward verifying findings adversarially. Work solo only on conversational " +493 "turns or trivial mechanical edits. When a system message says the mode is off, " +494 "revert to the opt-in rule above.",495 input_schema: {496 type: "object",497 properties: {498 subtasks: {499 type: "array",500 items: { type: "string" },501 description: "Independent subtask prompts to run as parallel agents",502 },503 },504 required: ["subtasks"],505 },506 };507508 const BASH_TOOL: Anthropic.ToolBash20250124 = { type: "bash_20250124", name: "bash" };509510 const REPORT_TOOL: Anthropic.Tool = {511 name: "report_findings",512 description:513 "Report the final findings for your subtask. Call this exactly once, when you are " +514 "done investigating; it ends your task.",515 input_schema: {516 type: "object",517 properties: {518 summary: { type: "string", description: "Two or three sentences of synthesis" },519 findings: {520 type: "array",521 items: {522 type: "object",523 properties: {524 claim: { type: "string", description: "The finding, one sentence" },525 evidence: {526 type: "string",527 description: "How it was verified (file, line, or command output)",528 },529 severity: { type: "string", enum: ["high", "medium", "low", "info"] },530 },531 required: ["claim", "evidence", "severity"],532 },533 },534 },535 required: ["summary", "findings"],536 },537 };538 ```539540 ```csharp C#541 Tool workflowTool = new()542 {543 Name = "Workflow",544 Description =545 "Orchestrate a multiagent workflow: split a large task into independent subtasks "546 + "and run them as parallel agents, then collect their results.\n\n"547 + "Opt-in: only use this tool when the user explicitly asks for a workflow, or when a "548 + "system message confirms that orchestration mode is on.\n\n"549 + "Quality patterns: adversarial verification (a second wave of agents checks the first "550 + "wave's findings against the source), a completeness critic (one agent hunts for what "551 + "the others missed), and multiphase sequencing (understand, design, implement, and "552 + "review as separate workflow calls, reading results between phases). A useful default "553 + "is hybrid: scout inline first to discover the work-list, then fan out over it.\n\n"554 + "Granularity: scope each subtask to a distinct concern, component, or question rather "555 + "than per line or per file section. Scale the count to what the user asked for: a "556 + "focused review of a module of a few hundred lines rarely needs more than about ten "557 + "subtasks; a broad audit of a large codebase can justify more.\n\n"558 + "Standing consent: while a system message confirms orchestration mode is on, that "559 + "opt-in is standing. Author and run a workflow for every substantive task by default, "560 + "and lean toward verifying findings adversarially. Work solo only on conversational "561 + "turns or trivial mechanical edits. When a system message says the mode is off, "562 + "revert to the opt-in rule above.",563 InputSchema = new InputSchema564 {565 Properties = new Dictionary<string, JsonElement>566 {567 ["subtasks"] = JsonSerializer.SerializeToElement(new568 {569 type = "array",570 items = new { type = "string" },571 description = "Independent subtask prompts to run as parallel agents",572 }),573 },574 Required = ["subtasks"],575 },576 };577578 ToolBash20250124 bashTool = new();579580 Tool reportTool = new()581 {582 Name = "report_findings",583 Description =584 "Report the final findings for your subtask. Call this exactly once, when you are "585 + "done investigating; it ends your task.",586 InputSchema = new InputSchema587 {588 Properties = new Dictionary<string, JsonElement>589 {590 ["summary"] = JsonSerializer.SerializeToElement(new591 {592 type = "string",593 description = "Two or three sentences of synthesis",594 }),595 ["findings"] = JsonSerializer.SerializeToElement(new596 {597 type = "array",598 items = new599 {600 type = "object",601 properties = new602 {603 claim = new { type = "string", description = "The finding, one sentence" },604 evidence = new605 {606 type = "string",607 description = "How it was verified (file, line, or command output)",608 },609 severity = new { type = "string", @enum = new[] { "high", "medium", "low", "info" } },610 },611 required = new[] { "claim", "evidence", "severity" },612 },613 }),614 },615 Required = ["summary", "findings"],616 },617 };618 ```619620 ```go Go621 var workflowTool = anthropic.ToolUnionParam{622 OfTool: &anthropic.ToolParam{623 Name: "Workflow",624 Description: anthropic.String("Orchestrate a multiagent workflow: split a large task into independent subtasks " +625 "and run them as parallel agents, then collect their results.\n\n" +626 "Opt-in: only use this tool when the user explicitly asks for a workflow, or when a " +627 "system message confirms that orchestration mode is on.\n\n" +628 "Quality patterns: adversarial verification (a second wave of agents checks the first " +629 "wave's findings against the source), a completeness critic (one agent hunts for what " +630 "the others missed), and multiphase sequencing (understand, design, implement, and " +631 "review as separate workflow calls, reading results between phases). A useful default " +632 "is hybrid: scout inline first to discover the work-list, then fan out over it.\n\n" +633 "Granularity: scope each subtask to a distinct concern, component, or question rather " +634 "than per line or per file section. Scale the count to what the user asked for: a " +635 "focused review of a module of a few hundred lines rarely needs more than about ten " +636 "subtasks; a broad audit of a large codebase can justify more.\n\n" +637 "Standing consent: while a system message confirms orchestration mode is on, that " +638 "opt-in is standing. Author and run a workflow for every substantive task by default, " +639 "and lean toward verifying findings adversarially. Work solo only on conversational " +640 "turns or trivial mechanical edits. When a system message says the mode is off, " +641 "revert to the opt-in rule above."),642 InputSchema: anthropic.ToolInputSchemaParam{643 Properties: map[string]any{644 "subtasks": map[string]any{645 "type": "array",646 "items": map[string]any{"type": "string"},647 "description": "Independent subtask prompts to run as parallel agents",648 },649 },650 Required: []string{"subtasks"},651 },652 },653 }654655 var bashTool = anthropic.ToolUnionParam{656 OfBashTool20250124: &anthropic.ToolBash20250124Param{},657 }658659 var reportTool = anthropic.ToolUnionParam{660 OfTool: &anthropic.ToolParam{661 Name: "report_findings",662 Description: anthropic.String("Report the final findings for your subtask. Call this exactly once, when you are " +663 "done investigating; it ends your task."),664 InputSchema: anthropic.ToolInputSchemaParam{665 Properties: map[string]any{666 "summary": map[string]any{"type": "string", "description": "Two or three sentences of synthesis"},667 "findings": map[string]any{668 "type": "array",669 "items": map[string]any{670 "type": "object",671 "properties": map[string]any{672 "claim": map[string]any{"type": "string", "description": "The finding, one sentence"},673 "evidence": map[string]any{674 "type": "string",675 "description": "How it was verified (file, line, or command output)",676 },677 "severity": map[string]any{"type": "string", "enum": []string{"high", "medium", "low", "info"}},678 },679 "required": []string{"claim", "evidence", "severity"},680 },681 },682 },683 Required: []string{"summary", "findings"},684 },685 },686 }687688 ```689690 ```java Java691 static final Tool WORKFLOW_TOOL = Tool.builder()692 .name("Workflow")693 .description("Orchestrate a multiagent workflow: split a large task into independent subtasks "694 + "and run them as parallel agents, then collect their results.\n\n"695 + "Opt-in: only use this tool when the user explicitly asks for a workflow, or when a "696 + "system message confirms that orchestration mode is on.\n\n"697 + "Quality patterns: adversarial verification (a second wave of agents checks the first "698 + "wave's findings against the source), a completeness critic (one agent hunts for what "699 + "the others missed), and multiphase sequencing (understand, design, implement, and "700 + "review as separate workflow calls, reading results between phases). A useful default "701 + "is hybrid: scout inline first to discover the work-list, then fan out over it.\n\n"702 + "Granularity: scope each subtask to a distinct concern, component, or question rather "703 + "than per line or per file section. Scale the count to what the user asked for: a "704 + "focused review of a module of a few hundred lines rarely needs more than about ten "705 + "subtasks; a broad audit of a large codebase can justify more.\n\n"706 + "Standing consent: while a system message confirms orchestration mode is on, that "707 + "opt-in is standing. Author and run a workflow for every substantive task by default, "708 + "and lean toward verifying findings adversarially. Work solo only on conversational "709 + "turns or trivial mechanical edits. When a system message says the mode is off, "710 + "revert to the opt-in rule above.")711 .inputSchema(Tool.InputSchema.builder()712 .properties(JsonValue.from(Map.of(713 "subtasks", Map.of(714 "type", "array",715 "items", Map.of("type", "string"),716 "description", "Independent subtask prompts to run as parallel agents"))))717 .putAdditionalProperty("required", JsonValue.from(List.of("subtasks")))718 .build())719 .build();720721 static final ToolBash20250124 BASH_TOOL = ToolBash20250124.builder().build();722723 static final Tool REPORT_TOOL = Tool.builder()724 .name("report_findings")725 .description("Report the final findings for your subtask. Call this exactly once, when you are "726 + "done investigating; it ends your task.")727 .inputSchema(Tool.InputSchema.builder()728 .properties(JsonValue.from(Map.of(729 "summary", Map.of("type", "string", "description", "Two or three sentences of synthesis"),730 "findings", Map.of(731 "type", "array",732 "items", Map.of(733 "type", "object",734 "properties", Map.of(735 "claim", Map.of(736 "type", "string",737 "description", "The finding, one sentence"),738 "evidence", Map.of(739 "type", "string",740 "description", "How it was verified (file, line, or command output)"),741 "severity", Map.of(742 "type", "string",743 "enum", List.of("high", "medium", "low", "info"))),744 "required", List.of("claim", "evidence", "severity"))))))745 .putAdditionalProperty("required", JsonValue.from(List.of("summary", "findings")))746 .build())747 .build();748 ```749750 ```php PHP751 const WORKFLOW_TOOL = [752 'name' => 'Workflow',753 'description' =>754 'Orchestrate a multiagent workflow: split a large task into independent subtasks '755 . "and run them as parallel agents, then collect their results.\n\n"756 . 'Opt-in: only use this tool when the user explicitly asks for a workflow, or when a '757 . "system message confirms that orchestration mode is on.\n\n"758 . 'Quality patterns: adversarial verification (a second wave of agents checks the first '759 . 'wave\'s findings against the source), a completeness critic (one agent hunts for what '760 . 'the others missed), and multiphase sequencing (understand, design, implement, and '761 . 'review as separate workflow calls, reading results between phases). A useful default '762 . "is hybrid: scout inline first to discover the work-list, then fan out over it.\n\n"763 . 'Granularity: scope each subtask to a distinct concern, component, or question rather '764 . 'than per line or per file section. Scale the count to what the user asked for: a '765 . 'focused review of a module of a few hundred lines rarely needs more than about ten '766 . "subtasks; a broad audit of a large codebase can justify more.\n\n"767 . 'Standing consent: while a system message confirms orchestration mode is on, that '768 . 'opt-in is standing. Author and run a workflow for every substantive task by default, '769 . 'and lean toward verifying findings adversarially. Work solo only on conversational '770 . 'turns or trivial mechanical edits. When a system message says the mode is off, '771 . 'revert to the opt-in rule above.',772 'input_schema' => [773 'type' => 'object',774 'properties' => [775 'subtasks' => [776 'type' => 'array',777 'items' => ['type' => 'string'],778 'description' => 'Independent subtask prompts to run as parallel agents',779 ],780 ],781 'required' => ['subtasks'],782 ],783 ];784785 const BASH_TOOL = ['type' => 'bash_20250124', 'name' => 'bash'];786787 const REPORT_TOOL = [788 'name' => 'report_findings',789 'description' =>790 'Report the final findings for your subtask. Call this exactly once, when you are '791 . 'done investigating; it ends your task.',792 'input_schema' => [793 'type' => 'object',794 'properties' => [795 'summary' => ['type' => 'string', 'description' => 'Two or three sentences of synthesis'],796 'findings' => [797 'type' => 'array',798 'items' => [799 'type' => 'object',800 'properties' => [801 'claim' => ['type' => 'string', 'description' => 'The finding, one sentence'],802 'evidence' => [803 'type' => 'string',804 'description' => 'How it was verified (file, line, or command output)',805 ],806 'severity' => ['type' => 'string', 'enum' => ['high', 'medium', 'low', 'info']],807 ],808 'required' => ['claim', 'evidence', 'severity'],809 ],810 ],811 ],812 'required' => ['summary', 'findings'],813 ],814 ];815 ```816817 ```ruby Ruby818 WORKFLOW_TOOL = {819 name: "Workflow",820 description:821 "Orchestrate a multiagent workflow: split a large task into independent subtasks " \822 "and run them as parallel agents, then collect their results.\n\n" \823 "Opt-in: only use this tool when the user explicitly asks for a workflow, or when a " \824 "system message confirms that orchestration mode is on.\n\n" \825 "Quality patterns: adversarial verification (a second wave of agents checks the first " \826 "wave's findings against the source), a completeness critic (one agent hunts for what " \827 "the others missed), and multiphase sequencing (understand, design, implement, and " \828 "review as separate workflow calls, reading results between phases). A useful default " \829 "is hybrid: scout inline first to discover the work-list, then fan out over it.\n\n" \830 "Granularity: scope each subtask to a distinct concern, component, or question rather " \831 "than per line or per file section. Scale the count to what the user asked for: a " \832 "focused review of a module of a few hundred lines rarely needs more than about ten " \833 "subtasks; a broad audit of a large codebase can justify more.\n\n" \834 "Standing consent: while a system message confirms orchestration mode is on, that " \835 "opt-in is standing. Author and run a workflow for every substantive task by default, " \836 "and lean toward verifying findings adversarially. Work solo only on conversational " \837 "turns or trivial mechanical edits. When a system message says the mode is off, " \838 "revert to the opt-in rule above.",839 input_schema: {840 type: "object",841 properties: {842 subtasks: {843 type: "array",844 items: {type: "string"},845 description: "Independent subtask prompts to run as parallel agents"846 }847 },848 required: ["subtasks"]849 }850 }.freeze851852 BASH_TOOL = {type: "bash_20250124", name: "bash"}.freeze853854 REPORT_TOOL = {855 name: "report_findings",856 description:857 "Report the final findings for your subtask. Call this exactly once, when you are " \858 "done investigating; it ends your task.",859 input_schema: {860 type: "object",861 properties: {862 summary: {type: "string", description: "Two or three sentences of synthesis"},863 findings: {864 type: "array",865 items: {866 type: "object",867 properties: {868 claim: {type: "string", description: "The finding, one sentence"},869 evidence: {870 type: "string",871 description: "How it was verified (file, line, or command output)"872 },873 severity: {type: "string", enum: ["high", "medium", "low", "info"]}874 },875 required: ["claim", "evidence", "severity"]876 }877 }878 },879 required: ["summary", "findings"]880 }881 }.freeze882 ```883</CodeGroup>884885## Run the bash tool locally886887The bash handler runs the requested command with a timeout, captures combined stdout and stderr, and truncates the result so a runaway command can't flood the context window. Commands run in the directory you launch the example from, so pointing it at a project means starting it there; when `DOC_TEST_MODE` is set, the harness instead gives bash a small throwaway fixture directory that is removed on exit. There is no sandbox here: the command runs with the permissions of the process that launched the example. For clarity this example runs each call in a fresh subshell rather than maintaining the persistent session the `bash_20250124` contract describes; a production agent should back the tool with a long-lived shell so that working directory, environment, and the `restart` action behave as documented.888889<CodeGroup>890 ```python Python891 # Run bash where the example was launched. In DOC_TEST_MODE the docs harness892 # points it at a throwaway fixture directory instead, removed on exit.893 if DOC_TEST_MODE:894 WORK_DIR = tempfile.mkdtemp(prefix="orchestration-")895 atexit.register(shutil.rmtree, WORK_DIR, ignore_errors=True)896 with open(os.path.join(WORK_DIR, "sample.py"), "w") as fixture:897 fixture.write(898 "def fib(n):\n"899 " return n if n < 2 else fib(n - 1) + fib(n - 2)\n\n"900 "print(fib(10))\n"901 )902 else:903 WORK_DIR = os.getcwd()904905906 def run_bash(command: str) -> tuple[str, bool]:907 """Run a shell command and return (output, is_error). No sandbox: example code only."""908 print(f"[bash] {command}", file=sys.stderr)909 try:910 proc = subprocess.run(911 ["bash", "-c", command],912 cwd=WORK_DIR,913 capture_output=True,914 text=True,915 errors="replace",916 timeout=BASH_TIMEOUT_SECONDS,917 )918 except subprocess.TimeoutExpired:919 return f"command timed out after {BASH_TIMEOUT_SECONDS}s", True920 output = (proc.stdout + proc.stderr).strip() or "(no output)"921 if len(output) > TOOL_RESULT_MAX_CHARS:922 output = output[:TOOL_RESULT_MAX_CHARS] + f"\n(truncated at {TOOL_RESULT_MAX_CHARS} chars)"923 if proc.returncode != 0:924 output = f"(exit code {proc.returncode})\n{output}"925 return output, proc.returncode != 0926927928 def handle_bash_block(block) -> tuple[str, bool]:929 if block.input.get("restart") is True:930 return "Shell restarted.", False931 command = block.input.get("command")932 if not isinstance(command, str) or not command:933 return "bash error: no command was provided.", True934 return run_bash(command)935 ```936937 ```typescript TypeScript938 const execShell = promisify(exec);939940 // Run bash where the example was launched. In DOC_TEST_MODE the docs harness941 // points it at a throwaway fixture directory instead, removed on exit.942 const WORK_DIR = DOC_TEST_MODE943 ? await mkdtemp(join(tmpdir(), "orchestration-"))944 : process.cwd();945 if (DOC_TEST_MODE) {946 await writeFile(947 join(WORK_DIR, "sample.py"),948 "def fib(n):\n" +949 " return n if n < 2 else fib(n - 1) + fib(n - 2)\n\n" +950 "print(fib(10))\n",951 );952 process.on("exit", () => rmSync(WORK_DIR, { recursive: true, force: true }));953 }954955 // Run a shell command and return its output. No sandbox: example code only.956 async function runBash(command: string): Promise<{ output: string; isError: boolean }> {957 console.error(`[bash] ${command}`);958 let stdout = "";959 let stderr = "";960 let exitCode = 0;961 try {962 ({ stdout, stderr } = await execShell(command, {963 shell: "/bin/bash",964 cwd: WORK_DIR,965 timeout: BASH_TIMEOUT_SECONDS * 1000,966 maxBuffer: 16 * 1024 * 1024,967 }));968 } catch (error) {969 const failure = error as {970 stdout?: string;971 stderr?: string;972 code?: number | string;973 killed?: boolean;974 };975 if (failure.killed && failure.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {976 return { output: `command timed out after ${BASH_TIMEOUT_SECONDS}s`, isError: true };977 }978 stdout = failure.stdout ?? "";979 stderr = failure.stderr ?? "";980 exitCode = typeof failure.code === "number" ? failure.code : 1;981 }982 let output = (stdout + stderr).trim() || "(no output)";983 const codePoints = [...output];984 if (codePoints.length > TOOL_RESULT_MAX_CHARS) {985 output =986 codePoints.slice(0, TOOL_RESULT_MAX_CHARS).join("") +987 `\n(truncated at ${TOOL_RESULT_MAX_CHARS} chars)`;988 }989 if (exitCode !== 0) {990 output = `(exit code ${exitCode})\n${output}`;991 }992 return { output, isError: exitCode !== 0 };993 }994995 async function handleBashBlock(996 block: Anthropic.ToolUseBlock,997 ): Promise<{ output: string; isError: boolean }> {998 const input = block.input as { command?: string; restart?: boolean };999 if (input.restart === true) {1000 return { output: "Shell restarted.", isError: false };1001 }1002 if (!input.command) {1003 return { output: "bash error: no command was provided.", isError: true };1004 }1005 return runBash(input.command);1006 }1007 ```10081009 ```csharp C#1010 // Run bash where the example was launched. In DOC_TEST_MODE the docs harness1011 // points it at a throwaway fixture directory instead, removed on exit.1012 var workDir = Environment.CurrentDirectory;1013 if (docTestMode)1014 {1015 workDir = Directory.CreateTempSubdirectory("orchestration-").FullName;1016 File.WriteAllText(Path.Combine(workDir, "sample.py"),1017 "def fib(n):\n" +1018 " return n if n < 2 else fib(n - 1) + fib(n - 2)\n\n" +1019 "print(fib(10))\n");1020 var fixtureDir = workDir;1021 AppDomain.CurrentDomain.ProcessExit += (_, _) =>1022 {1023 try { Directory.Delete(fixtureDir, recursive: true); }1024 catch { /* Best-effort cleanup; the OS tmp sweeper handles leftovers. */ }1025 };1026 }10271028 // Run a shell command and return its output plus an error flag. No sandbox: example code only.1029 async Task<(string Output, bool IsError)> RunBash(string command)1030 {1031 Console.Error.WriteLine($"[bash] {command}");1032 using var process = Process.Start(new ProcessStartInfo("bash")1033 {1034 ArgumentList = { "-c", command },1035 WorkingDirectory = workDir,1036 RedirectStandardOutput = true,1037 RedirectStandardError = true,1038 });1039 if (process is null)1040 {1041 return ("bash error: the shell process failed to start.", true);1042 }1043 var stdoutTask = process.StandardOutput.ReadToEndAsync();1044 var stderrTask = process.StandardError.ReadToEndAsync();1045 using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(bashTimeoutSeconds));1046 try1047 {1048 await process.WaitForExitAsync(timeout.Token);1049 }1050 catch (OperationCanceledException)1051 {1052 process.Kill(entireProcessTree: true);1053 // Let the reader tasks finish before the process is disposed.1054 try1055 {1056 await Task.WhenAll(stdoutTask, stderrTask);1057 }1058 catch1059 {1060 // The output is discarded on timeout, so reader failures are ignored too.1061 }1062 return ($"command timed out after {bashTimeoutSeconds}s", true);1063 }1064 var output = (await stdoutTask + await stderrTask).Trim();1065 if (output.Length == 0)1066 {1067 output = "(no output)";1068 }1069 if (output.Length > toolResultMaxChars)1070 {1071 output = output[..toolResultMaxChars] + $"\n(truncated at {toolResultMaxChars} chars)";1072 }1073 if (process.ExitCode != 0)1074 {1075 output = $"(exit code {process.ExitCode})\n{output}";1076 }1077 return (output, process.ExitCode != 0);1078 }10791080 // Execute one bash tool call requested by the model.1081 async Task<(string Output, bool IsError)> HandleBashBlock(ToolUseBlock block)1082 {1083 if (block.Input.TryGetValue("restart", out var restart) && restart.ValueKind == JsonValueKind.True)1084 {1085 return ("Shell restarted.", false);1086 }1087 var command = block.Input.TryGetValue("command", out var rawCommand) && rawCommand.ValueKind == JsonValueKind.String1088 ? rawCommand.GetString()!1089 : "";1090 if (command.Length == 0)1091 {1092 return ("bash error: no command was provided.", true);1093 }1094 return await RunBash(command);1095 }1096 ```10971098 ```go Go1099 // Run bash where the example was launched. In DOC_TEST_MODE the docs harness1100 // points it at a throwaway fixture directory instead, removed on exit.1101 var workDir = func() string {1102 if !docTestMode {1103 dir, err := os.Getwd()1104 if err != nil {1105 log.Fatal(err)1106 }1107 return dir1108 }1109 dir, err := os.MkdirTemp("", "orchestration-")1110 if err != nil {1111 log.Fatal(err)1112 }1113 fixture := "def fib(n):\n" +1114 " return n if n < 2 else fib(n - 1) + fib(n - 2)\n\n" +1115 "print(fib(10))\n"1116 if err := os.WriteFile(filepath.Join(dir, "sample.py"), []byte(fixture), 0o644); err != nil {1117 log.Fatal(err)1118 }1119 return dir1120 }()11211122 // runBash runs a shell command and returns its output plus an error flag.1123 // No sandbox: example code only.1124 func runBash(ctx context.Context, command string) (string, bool) {1125 fmt.Fprintf(os.Stderr, "[bash] %s\n", command)1126 ctx, cancel := context.WithTimeout(ctx, bashTimeoutSeconds*time.Second)1127 defer cancel()1128 cmd := exec.CommandContext(ctx, "bash", "-c", command)1129 cmd.Dir = workDir1130 combined, err := cmd.CombinedOutput()1131 if errors.Is(ctx.Err(), context.DeadlineExceeded) {1132 return fmt.Sprintf("command timed out after %ds", bashTimeoutSeconds), true1133 }1134 output := strings.TrimSpace(string(combined))1135 if output == "" {1136 output = "(no output)"1137 }1138 if runes := []rune(output); len(runes) > toolResultMaxChars {1139 output = string(runes[:toolResultMaxChars]) + fmt.Sprintf("\n(truncated at %d chars)", toolResultMaxChars)1140 }1141 if err == nil {1142 return output, false1143 }1144 var exitErr *exec.ExitError1145 if errors.As(err, &exitErr) {1146 return fmt.Sprintf("(exit code %d)\n%s", exitErr.ExitCode(), output), true1147 }1148 return fmt.Sprintf("(%s)\n%s", err, output), true1149 }11501151 // handleBashBlock executes one bash tool call requested by the model.1152 func handleBashBlock(ctx context.Context, block anthropic.ToolUseBlock) (string, bool) {1153 var input struct {1154 Command string `json:"command"`1155 Restart bool `json:"restart"`1156 }1157 if err := json.Unmarshal(block.Input, &input); err != nil {1158 return fmt.Sprintf("bash error: could not parse input: %s", err), true1159 }1160 if input.Restart {1161 return "Shell restarted.", false1162 }1163 if input.Command == "" {1164 return "bash error: no command was provided.", true1165 }1166 return runBash(ctx, input.Command)1167 }11681169 ```11701171 ```java Java1172 record ToolOutput(String output, boolean isError) {}11731174 // Run bash where the example was launched. In DOC_TEST_MODE the docs harness1175 // points it at a throwaway fixture directory instead, removed on exit.1176 static final Path WORK_DIR = createWorkDir();11771178 static Path createWorkDir() {1179 if (!DOC_TEST_MODE) {1180 return Path.of(System.getProperty("user.dir"));1181 }1182 try {1183 var dir = Files.createTempDirectory("orchestration-");1184 Files.writeString(dir.resolve("sample.py"), """1185 def fib(n):1186 return n if n < 2 else fib(n - 1) + fib(n - 2)11871188 print(fib(10))1189 """);1190 Runtime.getRuntime().addShutdownHook(new Thread(() -> {1191 try (var paths = Files.walk(dir)) {1192 paths.sorted(Comparator.reverseOrder()).forEach(p -> {1193 try { Files.deleteIfExists(p); } catch (IOException ignored) {}1194 });1195 } catch (IOException ignored) {1196 // Best-effort cleanup; the OS tmp sweeper handles leftovers.1197 }1198 }));1199 return dir;1200 } catch (IOException error) {1201 throw new UncheckedIOException(error);1202 }1203 }12041205 // Run a shell command and return its output plus an error flag. No sandbox: example code only.1206 ToolOutput runBash(String command) throws InterruptedException {1207 System.err.println("[bash] " + command);1208 Process process;1209 try {1210 process = new ProcessBuilder("bash", "-c", command)1211 .directory(WORK_DIR.toFile())1212 .redirectErrorStream(true)1213 .start();1214 } catch (IOException error) {1215 return new ToolOutput("(" + error + ")", true);1216 }1217 // Drain stdout on another thread so a filled pipe cannot stall the timeout wait below.1218 CompletableFuture<String> outputReader = CompletableFuture.supplyAsync(() -> {1219 try (var stdout = process.getInputStream()) {1220 return new String(stdout.readAllBytes(), StandardCharsets.UTF_8);1221 } catch (IOException error) {1222 return "";1223 }1224 });1225 if (!process.waitFor(BASH_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {1226 process.destroyForcibly();1227 outputReader.cancel(true);1228 return new ToolOutput("command timed out after " + BASH_TIMEOUT_SECONDS + "s", true);1229 }1230 String output = outputReader.join().trim();1231 if (output.isEmpty()) {1232 output = "(no output)";1233 }1234 if (output.length() > TOOL_RESULT_MAX_CHARS) {1235 output = output.substring(0, TOOL_RESULT_MAX_CHARS)1236 + "\n(truncated at " + TOOL_RESULT_MAX_CHARS + " chars)";1237 }1238 int exitCode = process.exitValue();1239 if (exitCode != 0) {1240 return new ToolOutput("(exit code " + exitCode + ")\n" + output, true);1241 }1242 return new ToolOutput(output, false);1243 }12441245 // Execute one bash tool call requested by the model.1246 ToolOutput handleBashBlock(ToolUseBlock block) throws InterruptedException {1247 Map<String, JsonValue> input = (Map<String, JsonValue>) block._input().asObject().orElse(Map.of());1248 JsonValue restart = input.getOrDefault("restart", JsonValue.from(false));1249 if (Boolean.TRUE.equals(restart.asBoolean().orElse(false))) {1250 return new ToolOutput("Shell restarted.", false);1251 }1252 JsonValue raw = input.get("command");1253 String command = raw != null && raw.asString().isPresent() ? raw.asStringOrThrow() : "";1254 if (command.isEmpty()) {1255 return new ToolOutput("bash error: no command was provided.", true);1256 }1257 return runBash(command);1258 }1259 ```12601261 ```php PHP1262 // Run bash where the example was launched. In DOC_TEST_MODE the docs harness1263 // points it at a throwaway fixture directory instead, removed on exit.1264 if (DOC_TEST_MODE) {1265 $workDir = sys_get_temp_dir() . '/orchestration-' . bin2hex(random_bytes(8));1266 if (!mkdir($workDir, 0700)) {1267 throw new RuntimeException("could not create working directory {$workDir}");1268 }1269 file_put_contents(1270 $workDir . '/sample.py',1271 "def fib(n):\n"1272 . " return n if n < 2 else fib(n - 1) + fib(n - 2)\n\n"1273 . "print(fib(10))\n",1274 );1275 register_shutdown_function(function () use ($workDir): void {1276 foreach (glob($workDir . '/*') ?: [] as $entry) {1277 @unlink($entry);1278 }1279 @rmdir($workDir);1280 });1281 } else {1282 $workDir = getcwd() ?: '.';1283 }1284 define('WORK_DIR', $workDir);12851286 /**1287 * Run a shell command and return [output, isError]. The coreutils timeout command1288 * enforces the time limit. No sandbox: example code only.1289 */1290 function runBash(string $command): array1291 {1292 fwrite(STDERR, "[bash] {$command}\n");1293 // Requires GNU coreutils 'timeout'. On macOS: brew install coreutils, or replace with gtimeout.1294 exec(1295 'cd ' . escapeshellarg(WORK_DIR) . ' && timeout ' . BASH_TIMEOUT_SECONDS1296 . ' bash -c ' . escapeshellarg($command) . ' 2>&1',1297 $outputLines,1298 $exitCode,1299 );1300 if ($exitCode === 124) {1301 return ['command timed out after ' . BASH_TIMEOUT_SECONDS . 's', true];1302 }1303 $output = trim(implode("\n", $outputLines));1304 if ($output === '') {1305 $output = '(no output)';1306 }1307 if (mb_strlen($output) > TOOL_RESULT_MAX_CHARS) {1308 $output = mb_substr($output, 0, TOOL_RESULT_MAX_CHARS)1309 . "\n(truncated at " . TOOL_RESULT_MAX_CHARS . ' chars)';1310 }1311 if ($exitCode !== 0) {1312 $output = "(exit code {$exitCode})\n{$output}";1313 }1314 return [$output, $exitCode !== 0];1315 }13161317 /** Execute one bash tool call requested by the model. */1318 function handleBashBlock(ToolUseBlock $block): array1319 {1320 if (($block->input['restart'] ?? null) === true) {1321 return ['Shell restarted.', false];1322 }1323 $command = $block->input['command'] ?? '';1324 if (!is_string($command) || $command === '') {1325 return ['bash error: no command was provided.', true];1326 }1327 return runBash($command);1328 }1329 ```13301331 ```ruby Ruby1332 # Run bash where the example was launched. In DOC_TEST_MODE the docs harness1333 # points it at a throwaway fixture directory instead, removed on exit.1334 WORK_DIR =1335 if DOC_TEST_MODE1336 Dir.mktmpdir("orchestration-").tap do |dir|1337 File.write(File.join(dir, "sample.py"), <<~PYTHON)1338 def fib(n):1339 return n if n < 2 else fib(n - 1) + fib(n - 2)13401341 print(fib(10))1342 PYTHON1343 at_exit { FileUtils.remove_entry(dir, true) }1344 end1345 else1346 Dir.pwd1347 end13481349 # Tool input arrives as a Hash or as a raw JSON string from the streaming1350 # accumulator; normalize either shape to a string-keyed Hash.1351 def parse_tool_input(raw)1352 return raw.transform_keys(&:to_s) if raw.is_a?(Hash)1353 parsed = JSON.parse(raw.to_s) rescue nil1354 parsed.is_a?(Hash) ? parsed : {}1355 end13561357 # Run a shell command and return [output, is_error]. No sandbox: example code only.1358 def run_bash(command)1359 warn "[bash] #{command}"1360 begin1361 stdin, stdout_and_stderr, wait_thr = Open3.popen2e("bash", "-c", command, pgroup: true, chdir: WORK_DIR)1362 stdin.close1363 reader = Thread.new { stdout_and_stderr.read.scrub }1364 # Enforce the time limit with a monotonic-clock deadline so a timed-out command is1365 # terminated rather than left running in the background.1366 deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + BASH_TIMEOUT_SECONDS1367 until wait_thr.join(0.1)1368 next if Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline13691370 begin1371 Process.kill("-TERM", wait_thr.pid)1372 rescue Errno::ESRCH1373 end1374 unless wait_thr.join(2)1375 begin1376 Process.kill("-KILL", wait_thr.pid)1377 rescue Errno::ESRCH1378 end1379 end1380 wait_thr.join(5)1381 reader.join(1) || reader.kill1382 stdout_and_stderr.close rescue nil1383 return ["command timed out after #{BASH_TIMEOUT_SECONDS}s", true]1384 end1385 status = wait_thr.value1386 output = reader.value.strip1387 stdout_and_stderr.close1388 output = "(no output)" if output.empty?1389 if output.length > TOOL_RESULT_MAX_CHARS1390 output = "#{output[0, TOOL_RESULT_MAX_CHARS]}\n(truncated at #{TOOL_RESULT_MAX_CHARS} chars)"1391 end1392 output = "(exit code #{status.exitstatus})\n#{output}" unless status.success?1393 [output, !status.success?]1394 rescue Errno::ENOENT => e1395 return ["bash error: #{e.message}", true]1396 end1397 end13981399 # Execute one bash tool call requested by the model.1400 def handle_bash_block(block)1401 input = parse_tool_input(block.input)1402 return ["Shell restarted.", false] if input["restart"] == true14031404 command = input["command"]1405 return ["bash error: no command was provided.", true] unless command.is_a?(String) && !command.empty?14061407 run_bash(command)1408 end14091410 # Convert response content to request-shaped params. The streaming accumulator1411 # returns tool_use input as a raw JSON string and includes response-only fields,1412 # so reshape each block to the request schema before echoing it back.1413 def assistant_content_param(content)1414 content.map do |block|1415 case block1416 when Anthropic::Models::ToolUseBlock1417 input = parse_tool_input(block.input)1418 {type: "tool_use", id: block.id, name: block.name, input: input}1419 when Anthropic::Models::TextBlock1420 {type: "text", text: block.text}1421 when Anthropic::Models::ThinkingBlock1422 {type: "thinking", thinking: block.thinking, signature: block.signature}1423 when Anthropic::Models::RedactedThinkingBlock then {type: "redacted_thinking", data: block.data}1424 else1425 block.to_h1426 end1427 end1428 end1429 ```1430</CodeGroup>14311432## Run one subagent14331434Each workflow subtask becomes its own small agent loop with the bash tool, running at the same effort as the main loop. A per-request timeout bounds each API call so a dropped connection degrades one subagent instead of stalling the whole run.14351436<CodeGroup>1437 ```python Python1438 def run_subagent(model: str, prompt: str) -> str:1439 """One subagent: a small nested agent loop with the bash tool plus report_findings.1440 Subagents inherit the main loop's effort level."""1441 subagent_system = (1442 "You are one agent in a larger parallel fan-out, assigned a single subtask. "1443 "Investigate it directly, using bash to check facts rather than guessing, and finish "1444 "by calling report_findings exactly once. Return findings, not narration."1445 )1446 messages = [{"role": "user", "content": prompt}]1447 for _ in range(MAX_SUBAGENT_TURNS):1448 with client.messages.stream(1449 model=model,1450 max_tokens=64000,1451 system=subagent_system,1452 output_config={"effort": EFFORT},1453 tools=[BASH_TOOL, REPORT_TOOL],1454 messages=messages,1455 timeout=REQUEST_TIMEOUT_SECONDS,1456 ) as stream:1457 response = stream.get_final_message()1458 messages.append({"role": "assistant", "content": response.content})1459 if response.stop_reason == "pause_turn":1460 continue1461 if response.stop_reason != "tool_use":1462 text = "".join(block.text for block in response.content if block.type == "text")1463 if response.stop_reason == "max_tokens":1464 text += "\n\n(warning: subagent response was truncated at max_tokens)"1465 return text1466 tool_results = []1467 report = None1468 for block in response.content:1469 if block.type != "tool_use":1470 continue1471 match block.name:1472 case "report_findings":1473 report = json.dumps(block.input, indent=2)1474 output, is_error = "Findings recorded.", False1475 case "bash":1476 output, is_error = handle_bash_block(block)1477 case _:1478 output, is_error = f"unknown tool: {block.name}", True1479 tool_results.append(1480 {1481 "type": "tool_result",1482 "tool_use_id": block.id,1483 "content": output,1484 "is_error": is_error,1485 }1486 )1487 if report is not None:1488 return report1489 messages.append({"role": "user", "content": tool_results})1490 return "(subagent hit the turn limit before finishing)"1491 ```14921493 ```typescript TypeScript1494 // One subagent: a small nested agent loop with the bash tool plus report_findings.1495 // Subagents inherit the main loop's effort level.1496 async function runSubagent(model: string, prompt: string): Promise<string> {1497 const subagentSystem =1498 "You are one agent in a larger parallel fan-out, assigned a single subtask. " +1499 "Investigate it directly, using bash to check facts rather than guessing, and finish " +1500 "by calling report_findings exactly once. Return findings, not narration.";1501 const messages: Anthropic.MessageParam[] = [{ role: "user", content: prompt }];1502 for (let turn = 0; turn < MAX_SUBAGENT_TURNS; turn++) {1503 const response = await client.messages1504 .stream(1505 {1506 model,1507 max_tokens: 64000,1508 system: subagentSystem,1509 output_config: { effort: EFFORT },1510 tools: [BASH_TOOL, REPORT_TOOL],1511 messages,1512 },1513 { signal: AbortSignal.timeout(REQUEST_TIMEOUT_SECONDS * 1000) },1514 )1515 .finalMessage();1516 messages.push({ role: "assistant", content: response.content });1517 if (response.stop_reason === "pause_turn") {1518 continue;1519 }1520 if (response.stop_reason !== "tool_use") {1521 let text = response.content1522 .filter((block): block is Anthropic.TextBlock => block.type === "text")1523 .map((block) => block.text)1524 .join("");1525 if (response.stop_reason === "max_tokens") {1526 text += "\n\n(warning: subagent response was truncated at max_tokens)";1527 }1528 return text;1529 }1530 const toolResults: Anthropic.ToolResultBlockParam[] = [];1531 let report: string | null = null;1532 for (const block of response.content) {1533 if (block.type !== "tool_use") {1534 continue;1535 }1536 let output: string;1537 let isError: boolean;1538 switch (block.name) {1539 case "report_findings":1540 report = JSON.stringify(block.input, null, 2);1541 output = "Findings recorded.";1542 isError = false;1543 break;1544 case "bash":1545 ({ output, isError } = await handleBashBlock(block));1546 break;1547 default:1548 output = `unknown tool: ${block.name}`;1549 isError = true;1550 }1551 toolResults.push({1552 type: "tool_result",1553 tool_use_id: block.id,1554 content: output,1555 is_error: isError,1556 });1557 }1558 if (report !== null) {1559 return report;1560 }1561 messages.push({ role: "user", content: toolResults });1562 }1563 return "(subagent hit the turn limit before finishing)";1564 }1565 ```15661567 ```csharp C#1568 // One subagent: a small nested agent loop with the bash tool plus report_findings.1569 // Subagents inherit the main loop's effort level.1570 async Task<string> RunSubagent(string prompt)1571 {1572 const string subagentSystem =1573 "You are one agent in a larger parallel fan-out, assigned a single subtask. "1574 + "Investigate it directly, using bash to check facts rather than guessing, and finish "1575 + "by calling report_findings exactly once. Return findings, not narration.";1576 List<MessageParam> messages = [new() { Role = Role.User, Content = prompt }];1577 for (var turn = 0; turn < maxSubagentTurns; turn++)1578 {1579 using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(requestTimeoutSeconds));1580 var response = await client.Messages.Create(new MessageCreateParams1581 {1582 Model = model,1583 MaxTokens = requestMaxTokens,1584 System = subagentSystem,1585 OutputConfig = new OutputConfig { Effort = effort },1586 Tools = [bashTool, reportTool],1587 Messages = messages,1588 }, cancellationToken: deadline.Token);1589 messages.Add(new()1590 {1591 Role = Role.Assistant,1592 Content = response.Content.Select(block => new ContentBlockParam(block.Json)).ToList(),1593 });1594 if (response.StopReason == StopReason.PauseTurn)1595 {1596 continue;1597 }1598 if (response.StopReason != StopReason.ToolUse)1599 {1600 var text = string.Concat(1601 response.Content.Select(block => block.TryPickText(out var textBlock) ? textBlock.Text : ""));1602 if (response.StopReason == StopReason.MaxTokens)1603 {1604 text += "\n\n(warning: subagent response was truncated at max_tokens)";1605 }1606 return text;1607 }1608 List<ContentBlockParam> toolResults = [];1609 string? report = null;1610 foreach (var block in response.Content)1611 {1612 if (!block.TryPickToolUse(out var toolUse))1613 {1614 continue;1615 }1616 string output;1617 bool isError;1618 if (toolUse.Name == "report_findings")1619 {1620 report = JsonSerializer.Serialize(1621 toolUse.Input, new JsonSerializerOptions { WriteIndented = true });1622 output = "Findings recorded.";1623 isError = false;1624 }1625 else if (toolUse.Name == "bash")1626 {1627 (output, isError) = await HandleBashBlock(toolUse);1628 }1629 else1630 {1631 output = $"unknown tool: {toolUse.Name}";1632 isError = true;1633 }1634 toolResults.Add(new ToolResultBlockParam(toolUse.ID) { Content = output, IsError = isError });1635 }1636 if (report is not null)1637 {1638 return report;1639 }1640 messages.Add(new() { Role = Role.User, Content = toolResults });1641 }1642 return "(subagent hit the turn limit before finishing)";1643 }1644 ```16451646 ```go Go1647 // runSubagent runs one subagent: a small nested agent loop with the bash tool plus1648 // report_findings. Subagents inherit the main loop's effort level.1649 func runSubagent(ctx context.Context, model string, prompt string) (string, error) {1650 subagentSystem := "You are one agent in a larger parallel fan-out, assigned a single subtask. " +1651 "Investigate it directly, using bash to check facts rather than guessing, and finish " +1652 "by calling report_findings exactly once. Return findings, not narration."1653 messages := []anthropic.MessageParam{anthropic.NewUserMessage(anthropic.NewTextBlock(prompt))}1654 for range maxSubagentTurns {1655 var response anthropic.Message1656 err := func() error {1657 ctx, cancel := context.WithTimeout(ctx, requestTimeoutSeconds*time.Second)1658 defer cancel()1659 stream := client.Messages.NewStreaming(ctx, anthropic.MessageNewParams{1660 Model: model,1661 MaxTokens: 64000,1662 System: []anthropic.TextBlockParam{{Text: subagentSystem}},1663 OutputConfig: anthropic.OutputConfigParam{Effort: effort},1664 Tools: []anthropic.ToolUnionParam{bashTool, reportTool},1665 Messages: messages,1666 })1667 defer stream.Close()1668 for stream.Next() {1669 if err := response.Accumulate(stream.Current()); err != nil {1670 return err1671 }1672 }1673 return stream.Err()1674 }()1675 if err != nil {1676 return "", err1677 }1678 messages = append(messages, response.ToParam())1679 if response.StopReason == anthropic.StopReasonPauseTurn {1680 continue1681 }1682 if response.StopReason != anthropic.StopReasonToolUse {1683 var text strings.Builder1684 for _, block := range response.Content {1685 if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {1686 text.WriteString(textBlock.Text)1687 }1688 }1689 if response.StopReason == anthropic.StopReasonMaxTokens {1690 text.WriteString("\n\n(warning: subagent response was truncated at max_tokens)")1691 }1692 return text.String(), nil1693 }1694 var toolResults []anthropic.ContentBlockParamUnion1695 var report string1696 var reportRecorded bool1697 for _, block := range response.Content {1698 toolUse, ok := block.AsAny().(anthropic.ToolUseBlock)1699 if !ok {1700 continue1701 }1702 var output string1703 var isError bool1704 switch toolUse.Name {1705 case "report_findings":1706 report = string(toolUse.Input)1707 var pretty bytes.Buffer1708 if err := json.Indent(&pretty, toolUse.Input, "", " "); err == nil {1709 report = pretty.String()1710 }1711 reportRecorded = true1712 output = "Findings recorded."1713 case "bash":1714 output, isError = handleBashBlock(ctx, toolUse)1715 default:1716 output, isError = fmt.Sprintf("unknown tool: %s", toolUse.Name), true1717 }1718 toolResults = append(toolResults, anthropic.NewToolResultBlock(toolUse.ID, output, isError))1719 }1720 if reportRecorded {1721 return report, nil1722 }1723 messages = append(messages, anthropic.NewUserMessage(toolResults...))1724 }1725 return "(subagent hit the turn limit before finishing)", nil1726 }17271728 ```17291730 ```java Java1731 // One subagent: a small nested agent loop with the bash tool plus report_findings.1732 // Subagents inherit the main loop's effort level.1733 String runSubagent(Model model, String prompt) throws InterruptedException {1734 String subagentSystem = "You are one agent in a larger parallel fan-out, assigned a single subtask. "1735 + "Investigate it directly, using bash to check facts rather than guessing, and finish "1736 + "by calling report_findings exactly once. Return findings, not narration.";1737 List<MessageParam> messages = new ArrayList<>();1738 messages.add(MessageParam.builder().role(MessageParam.Role.USER).content(prompt).build());1739 for (int turn = 0; turn < MAX_SUBAGENT_TURNS; turn++) {1740 MessageCreateParams params = MessageCreateParams.builder()1741 .model(model)1742 .maxTokens(64000L)1743 .system(subagentSystem)1744 .outputConfig(OutputConfig.builder().effort(EFFORT).build())1745 .addTool(BASH_TOOL)1746 .addTool(REPORT_TOOL)1747 .messages(messages)1748 .build();1749 MessageAccumulator accumulator = MessageAccumulator.create();1750 try (var stream = client.messages().createStreaming(params, REQUEST_OPTIONS)) {1751 stream.stream().forEach(accumulator::accumulate);1752 }1753 Message response = accumulator.message();1754 messages.add(response.toParam());1755 StopReason stopReason = response.stopReason().orElse(null);1756 if (StopReason.PAUSE_TURN.equals(stopReason)) {1757 continue;1758 }1759 if (!StopReason.TOOL_USE.equals(stopReason)) {1760 String text = response.content().stream()1761 .flatMap(block -> block.text().stream())1762 .map(TextBlock::text)1763 .collect(Collectors.joining());1764 if (StopReason.MAX_TOKENS.equals(stopReason)) {1765 text += "\n\n(warning: subagent response was truncated at max_tokens)";1766 }1767 return text;1768 }1769 List<ContentBlockParam> toolResults = new ArrayList<>();1770 String report = null;1771 for (ContentBlock block : response.content()) {1772 if (block.toolUse().isEmpty()) {1773 continue;1774 }1775 ToolUseBlock toolUse = block.toolUse().get();1776 ToolOutput result;1777 if (toolUse.name().equals("report_findings")) {1778 report = toolUse._input().convert(JsonNode.class).toPrettyString();1779 result = new ToolOutput("Findings recorded.", false);1780 } else if (toolUse.name().equals("bash")) {1781 result = handleBashBlock(toolUse);1782 } else {1783 result = new ToolOutput("unknown tool: " + toolUse.name(), true);1784 }1785 toolResults.add(ContentBlockParam.ofToolResult(ToolResultBlockParam.builder()1786 .toolUseId(toolUse.id())1787 .content(result.output())1788 .isError(result.isError())1789 .build()));1790 }1791 if (report != null) {1792 return report;1793 }1794 messages.add(MessageParam.builder()1795 .role(MessageParam.Role.USER)1796 .contentOfBlockParams(toolResults)1797 .build());1798 }1799 return "(subagent hit the turn limit before finishing)";1800 }1801 ```18021803 ```php PHP1804 /**1805 * Consume a message stream and assemble the final assistant turn from its events:1806 * the full content-block list plus the stop reason, equivalent to what a1807 * non-streaming create call returns.1808 */1809 function drainMessageStream(iterable $events): array1810 {1811 $stringValue = fn ($value) => $value instanceof BackedEnum ? $value->value : $value;1812 $blocks = [];1813 $jsonBuffers = [];1814 $stopReason = null;1815 foreach ($events as $event) {1816 $type = $stringValue($event->type);1817 if ($type === 'content_block_start') {1818 $blocks[$event->index] = $event->contentBlock;1819 $jsonBuffers[$event->index] = '';1820 } elseif ($type === 'content_block_delta') {1821 $block = $blocks[$event->index];1822 $delta = $event->delta;1823 $deltaType = $stringValue($delta->type);1824 if ($deltaType === 'text_delta') {1825 $blocks[$event->index] = $block->withText($block->text . $delta->text);1826 } elseif ($deltaType === 'input_json_delta') {1827 $jsonBuffers[$event->index] .= $delta->partialJSON;1828 } elseif ($deltaType === 'thinking_delta') {1829 $blocks[$event->index] = $block->withThinking($block->thinking . $delta->thinking);1830 } elseif ($deltaType === 'signature_delta') {1831 $blocks[$event->index] = $block->withSignature($delta->signature);1832 }1833 } elseif ($type === 'message_delta') {1834 $stopReason = $stringValue($event->delta->stopReason);1835 }1836 }1837 foreach ($jsonBuffers as $index => $buffer) {1838 if ($buffer !== '' && $blocks[$index] instanceof \Anthropic\Messages\ToolUseBlock) {1839 $decoded = json_decode($buffer, true);1840 $blocks[$index] = $blocks[$index]->withInput(is_array($decoded) ? $decoded : []);1841 }1842 }1843 return [array_values($blocks), $stopReason];1844 }18451846 /**1847 * One subagent: a small nested agent loop with the bash tool plus report_findings.1848 * Subagents inherit the main loop's effort level.1849 */1850 function runSubagent(Client $client, string $model, string $prompt): string1851 {1852 $subagentSystem =1853 'You are one agent in a larger parallel fan-out, assigned a single subtask. '1854 . 'Investigate it directly, using bash to check facts rather than guessing, and finish '1855 . 'by calling report_findings exactly once. Return findings, not narration.';1856 $messages = [['role' => 'user', 'content' => $prompt]];1857 for ($turn = 0; $turn < MAX_SUBAGENT_TURNS; $turn++) {1858 $stream = $client->messages->createStream(1859 model: $model,1860 maxTokens: 64000,1861 system: $subagentSystem,1862 outputConfig: ['effort' => EFFORT],1863 tools: [BASH_TOOL, REPORT_TOOL],1864 messages: $messages,1865 requestOptions: ['timeout' => REQUEST_TIMEOUT_SECONDS],1866 );1867 [$content, $stopReason] = drainMessageStream($stream);1868 $messages[] = ['role' => 'assistant', 'content' => $content];1869 if ($stopReason === 'pause_turn') {1870 continue;1871 }1872 if ($stopReason !== 'tool_use') {1873 $text = '';1874 foreach ($content as $block) {1875 if ($block instanceof \Anthropic\Messages\TextBlock) {1876 $text .= $block->text;1877 }1878 }1879 if ($stopReason === 'max_tokens') {1880 $text .= "\n\n(warning: subagent response was truncated at max_tokens)";1881 }1882 return $text;1883 }1884 $report = null;1885 $toolResults = [];1886 foreach ($content as $block) {1887 if (!$block instanceof \Anthropic\Messages\ToolUseBlock) {1888 continue;1889 }1890 if ($block->name === 'report_findings') {1891 $report = json_encode($block->input, JSON_PRETTY_PRINT);1892 $output = 'Findings recorded.';1893 $isError = false;1894 } elseif ($block->name === 'bash') {1895 [$output, $isError] = handleBashBlock($block);1896 } else {1897 $output = "unknown tool: {$block->name}";1898 $isError = true;1899 }1900 $toolResults[] = [1901 'type' => 'tool_result',1902 'tool_use_id' => $block->id,1903 'content' => $output,1904 'is_error' => $isError,1905 ];1906 }1907 if ($report !== null) {1908 return $report;1909 }1910 $messages[] = ['role' => 'user', 'content' => $toolResults];1911 }1912 return '(subagent hit the turn limit before finishing)';1913 }1914 ```19151916 ```ruby Ruby1917 # One subagent: a small nested agent loop with the bash tool plus report_findings.1918 # Subagents inherit the main loop's effort level.1919 def run_subagent(model, prompt)1920 subagent_system =1921 "You are one agent in a larger parallel fan-out, assigned a single subtask. " \1922 "Investigate it directly, using bash to check facts rather than guessing, and finish " \1923 "by calling report_findings exactly once. Return findings, not narration."1924 messages = [{role: "user", content: prompt}]1925 MAX_SUBAGENT_TURNS.times do1926 stream = CLIENT.messages.stream(1927 model: model,1928 max_tokens: 64_000,1929 system_: subagent_system,1930 output_config: {effort: EFFORT},1931 tools: [BASH_TOOL, REPORT_TOOL],1932 messages: messages,1933 request_options: {timeout: REQUEST_TIMEOUT_SECONDS}1934 )1935 response = stream.accumulated_message1936 messages << {role: "assistant", content: assistant_content_param(response.content)}1937 next if response.stop_reason == :pause_turn19381939 unless response.stop_reason == :tool_use1940 text = response.content.select { |block| block.type == :text }.map(&:text).join1941 text += "\n\n(warning: subagent response was truncated at max_tokens)" if response.stop_reason == :max_tokens1942 return text1943 end19441945 report = nil1946 tool_results = []1947 response.content.each do |block|1948 next unless block.type == :tool_use19491950 input = parse_tool_input(block.input)1951 case block.name1952 when "report_findings"1953 report = JSON.pretty_generate(input)1954 output, is_error = "Findings recorded.", false1955 when "bash"1956 output, is_error = handle_bash_block(block)1957 else1958 output, is_error = "unknown tool: #{block.name}", true1959 end1960 tool_results << {1961 type: "tool_result",1962 tool_use_id: block.id,1963 content: output,1964 is_error: is_error1965 }1966 end1967 return report unless report.nil?19681969 messages << {role: "user", content: tool_results}1970 end1971 "(subagent hit the turn limit before finishing)"1972 end1973 ```1974</CodeGroup>19751976## Journal results so reruns resume19771978A fan-out that spawns dozens of subagents is expensive to restart from scratch. A small content-addressed journal makes it idempotent: before dispatching a subagent, look up the SHA-256 of its prompt in a local JSON file, and return the recorded result if one exists. Interrupt the run, rerun it, and only the subtasks that never finished are recomputed. The journal deduplicates across runs, not within a single fan-out wave; delete the journal file to start fresh.19791980<CodeGroup>1981 ```python Python1982 _journal_lock = threading.Lock()198319841985 def _load_journal() -> dict:1986 try:1987 with open(JOURNAL_PATH) as file:1988 return json.load(file) or {}1989 except (OSError, json.JSONDecodeError):1990 return {}199119921993 def journaled(prompt: str, compute) -> str:1994 """Return a cached result for this exact prompt, or compute and persist it. This1995 makes the fan-out resumable: interrupt the run, rerun it, and only the subtasks1996 that never finished are recomputed. Delete the journal file to start fresh."""1997 key = hashlib.sha256(prompt.encode()).hexdigest()1998 cached = _load_journal().get(key)1999 if cached is not None:2000 print(f"[journal] cache hit for {key[:12]}", file=sys.stderr)2001 return cached2002 result = compute()2003 try:2004 with _journal_lock: # fan-out writes from many threads2005 journal = _load_journal()2006 journal[key] = result2007 temp = f"{JOURNAL_PATH}.tmp"2008 with open(temp, "w") as file:2009 json.dump(journal, file)2010 os.replace(temp, JOURNAL_PATH) # atomic on POSIX and Windows2011 except OSError as error: # the journal is best-effort; never discard a computed result2012 print(f"[journal] write failed: {error}", file=sys.stderr)2013 return result2014 ```20152016 ```typescript TypeScript2017 let journalWriteChain = Promise.resolve();20182019 async function loadJournal(): Promise<Record<string, string>> {2020 try {2021 return JSON.parse(await readFile(JOURNAL_PATH, "utf8")) ?? {};2022 } catch (error) {2023 if ((error as NodeJS.ErrnoException).code !== "ENOENT") {2024 console.error(`[journal] discarding unreadable journal: ${error}`);2025 }2026 return {};2027 }2028 }20292030 // Return a cached result for this exact prompt, or compute and persist it. This2031 // makes the fan-out resumable: interrupt the run, rerun it, and only the subtasks2032 // that never finished are recomputed. Delete the journal file to start fresh.2033 async function journaled(prompt: string, compute: () => Promise<string>): Promise<string> {2034 const key = createHash("sha256").update(prompt).digest("hex");2035 const cached = (await loadJournal())[key];2036 if (cached !== undefined) {2037 console.error(`[journal] cache hit for ${key.slice(0, 12)}`);2038 return cached;2039 }2040 const result = await compute();2041 // Chain writes so concurrent subagents do not clobber each other's entries.2042 // The chain is kept settled so one failed write does not poison later ones.2043 await (journalWriteChain = journalWriteChain2044 .then(async () => {2045 const journal = await loadJournal();2046 journal[key] = result;2047 const temp = `${JOURNAL_PATH}.tmp`;2048 await writeFile(temp, JSON.stringify(journal));2049 await rename(temp, JOURNAL_PATH);2050 })2051 .catch((error) => console.error(`[journal] write failed: ${error}`)));2052 return result;2053 }2054 ```20552056 ```csharp C#2057 SemaphoreSlim journalLock = new(1, 1);20582059 async Task<Dictionary<string, string>> LoadJournal()2060 {2061 try2062 {2063 return JsonSerializer.Deserialize<Dictionary<string, string>>(await File.ReadAllTextAsync(journalPath)) ?? [];2064 }2065 catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException)2066 {2067 return [];2068 }2069 }20702071 // Return a cached result for this exact prompt, or compute and persist it. This2072 // makes the fan-out resumable: interrupt the run, rerun it, and only the subtasks2073 // that never finished are recomputed. Delete the journal file to start fresh.2074 async Task<string> Journaled(string prompt, Func<Task<string>> compute)2075 {2076 var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(prompt))).ToLowerInvariant();2077 if ((await LoadJournal()).TryGetValue(key, out var cached))2078 {2079 Console.Error.WriteLine($"[journal] cache hit for {key[..12]}");2080 return cached;2081 }2082 var result = await compute();2083 await journalLock.WaitAsync(); // fan-out writes from many tasks2084 try2085 {2086 var journal = await LoadJournal();2087 journal[key] = result;2088 var temp = journalPath + ".tmp";2089 await File.WriteAllTextAsync(temp, JsonSerializer.Serialize(journal));2090 File.Move(temp, journalPath, overwrite: true);2091 }2092 catch (Exception error) when (error is IOException or UnauthorizedAccessException or NotSupportedException)2093 {2094 // The journal is best-effort; never discard a computed result.2095 Console.Error.WriteLine($"[journal] write failed: {error.Message}");2096 }2097 finally2098 {2099 journalLock.Release();2100 }2101 return result;2102 }2103 ```21042105 ```go Go2106 var journalMutex sync.Mutex21072108 func loadJournal() map[string]string {2109 data, err := os.ReadFile(journalPath)2110 if err != nil {2111 return map[string]string{}2112 }2113 var journal map[string]string2114 if err := json.Unmarshal(data, &journal); err != nil || journal == nil {2115 return map[string]string{}2116 }2117 return journal2118 }21192120 // journaled returns a cached result for this exact prompt, or computes and persists2121 // it. This makes the fan-out resumable: interrupt the run, rerun it, and only the2122 // subtasks that never finished are recomputed. Delete the journal file to start fresh.2123 func journaled(prompt string, compute func() (string, error)) (string, error) {2124 sum := sha256.Sum256([]byte(prompt))2125 key := hex.EncodeToString(sum[:])2126 if cached, ok := loadJournal()[key]; ok {2127 fmt.Fprintf(os.Stderr, "[journal] cache hit for %s\n", key[:12])2128 return cached, nil2129 }2130 result, err := compute()2131 if err != nil {2132 return "", err2133 }2134 journalMutex.Lock() // fan-out writes from many goroutines2135 defer journalMutex.Unlock()2136 journal := loadJournal()2137 journal[key] = result2138 data, _ := json.Marshal(journal)2139 temp := journalPath + ".tmp"2140 if err := os.WriteFile(temp, data, 0o644); err != nil {2141 fmt.Fprintf(os.Stderr, "[journal] write failed: %s\n", err)2142 } else if err := os.Rename(temp, journalPath); err != nil {2143 fmt.Fprintf(os.Stderr, "[journal] write failed: %s\n", err)2144 _ = os.Remove(temp)2145 }2146 return result, nil2147 }21482149 ```21502151 ```java Java2152 static final ObjectMapper JOURNAL_MAPPER = new ObjectMapper();2153 static final ReentrantLock JOURNAL_LOCK = new ReentrantLock();21542155 Map<String, String> loadJournal() {2156 try {2157 return Objects.requireNonNullElseGet(2158 JOURNAL_MAPPER.readValue(Files.readString(JOURNAL_PATH), new TypeReference<HashMap<String, String>>() {}),2159 HashMap::new);2160 } catch (IOException error) {2161 return new HashMap<>();2162 }2163 }21642165 // Return a cached result for this exact prompt, or compute and persist it. This2166 // makes the fan-out resumable: interrupt the run, rerun it, and only the subtasks2167 // that never finished are recomputed. Delete the journal file to start fresh.2168 String journaled(String prompt, Callable<String> compute) throws Exception {2169 var digest = MessageDigest.getInstance("SHA-256").digest(prompt.getBytes(StandardCharsets.UTF_8));2170 String key = HexFormat.of().formatHex(digest);2171 String cached = loadJournal().get(key);2172 if (cached != null) {2173 System.err.println("[journal] cache hit for " + key.substring(0, 12));2174 return cached;2175 }2176 String result = compute.call();2177 JOURNAL_LOCK.lock(); // fan-out writes from many threads2178 try {2179 Map<String, String> journal = loadJournal();2180 journal.put(key, result);2181 Path temp = JOURNAL_PATH.resolveSibling(JOURNAL_PATH.getFileName() + ".tmp");2182 Files.writeString(temp, JOURNAL_MAPPER.writeValueAsString(journal));2183 Files.move(temp, JOURNAL_PATH, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);2184 } catch (IOException error) {2185 // The journal is best-effort; never discard a computed result.2186 System.err.println("[journal] write failed: " + error);2187 } finally {2188 JOURNAL_LOCK.unlock();2189 }2190 return result;2191 }2192 ```21932194 ```php PHP2195 function loadJournal(): array2196 {2197 $raw = @file_get_contents(JOURNAL_PATH);2198 if ($raw === false) {2199 return [];2200 }2201 $decoded = json_decode($raw, true);2202 return is_array($decoded) ? $decoded : [];2203 }22042205 /**2206 * Return a cached result for this exact prompt, or compute and persist it. This2207 * makes the fan-out resumable: interrupt the run, rerun it, and only the subtasks2208 * that never finished are recomputed. Delete the journal file to start fresh.2209 */2210 function journaled(string $prompt, callable $compute): string2211 {2212 $key = hash('sha256', $prompt);2213 $journal = loadJournal();2214 if (array_key_exists($key, $journal)) {2215 fwrite(STDERR, '[journal] cache hit for ' . substr($key, 0, 12) . "\n");2216 return $journal[$key];2217 }2218 $result = $compute();2219 $journal = loadJournal();2220 $journal[$key] = $result;2221 $temp = JOURNAL_PATH . '.tmp';2222 $encoded = json_encode($journal, JSON_INVALID_UTF8_SUBSTITUTE);2223 if ($encoded === false || @file_put_contents($temp, $encoded) === false || !@rename($temp, JOURNAL_PATH)) {2224 fwrite(STDERR, '[journal] write failed: ' . (error_get_last()['message'] ?? json_last_error_msg()) . "\n");2225 @unlink($temp);2226 }2227 return $result;2228 }2229 ```22302231 ```ruby Ruby2232 JOURNAL_LOCK = Mutex.new22332234 def load_journal2235 JSON.parse(File.read(JOURNAL_PATH)) || {}2236 rescue SystemCallError, JSON::ParserError2237 {}2238 end22392240 # Return a cached result for this exact prompt, or compute and persist it. This2241 # makes the fan-out resumable: interrupt the run, rerun it, and only the subtasks2242 # that never finished are recomputed. Delete the journal file to start fresh.2243 def journaled(prompt)2244 key = Digest::SHA256.hexdigest(prompt)2245 cached = load_journal[key]2246 unless cached.nil?2247 warn "[journal] cache hit for #{key[0, 12]}"2248 return cached2249 end2250 result = yield2251 begin2252 JOURNAL_LOCK.synchronize do # fan-out writes from many threads2253 journal = load_journal2254 journal[key] = result2255 temp = "#{JOURNAL_PATH}.tmp"2256 File.write(temp, JSON.generate(journal))2257 File.rename(temp, JOURNAL_PATH)2258 end2259 rescue SystemCallError => error # the journal is best-effort; never discard a computed result2260 warn "[journal] write failed: #{error}"2261 end2262 result2263 end2264 ```2265</CodeGroup>22662267## Fan out, then verify22682269The fan-out accepts up to `MAX_TOTAL_SUBTASKS` prompts, runs them through the journal with at most `MAX_CONCURRENT` in flight (sequential in the PHP port), and isolates failures so one broken subagent degrades to an error string instead of ending the run. Once the first wave finishes, a second wave reuses the same subagent path to try to refute each result: every verifier re-derives the claims from the source, defaulting to refuted when uncertain. Both the original result and its verdict are returned to the orchestrator so it can weigh them together.22702271<CodeGroup>2272 ```python Python2273 def normalize_subtasks(raw) -> list[str]:2274 """Accept the subtasks input in whatever shape the model emits: an array, the array2275 JSON-encoded as a single string, or a newline-separated list."""2276 if isinstance(raw, str):2277 try:2278 raw = json.loads(raw)2279 except json.JSONDecodeError:2280 raw = raw.splitlines() if "\n" in raw else [raw]2281 if not isinstance(raw, list):2282 return []2283 return [task.strip() for task in raw if isinstance(task, str) and task.strip()]228422852286 def verify_prompt_for(subtask: str, result: str) -> str:2287 return (2288 "Adversarially verify the subagent result below: try to REFUTE it. Re-derive the "2289 "claims yourself with bash rather than trusting the result, and look for evidence "2290 "that contradicts them. Default to refuted if uncertain. Call report_findings with "2291 "summary 'refuted: <why>' or 'confirmed: <why>', citing the file:line or command "2292 "output that decided it.\n\n"2293 f"Subtask: {subtask}\n\nResult to verify:\n{result}"2294 )229522962297 def run_workflow(model: str, raw_subtasks) -> tuple[str, bool]:2298 """Run subtasks as parallel subagents, then run a second verification wave over2299 the results, and return both. MAX_TOTAL_SUBTASKS bounds how many the model can2300 queue; MAX_CONCURRENT bounds how many run at once."""2301 all_subtasks = normalize_subtasks(raw_subtasks)2302 subtasks = all_subtasks[:MAX_TOTAL_SUBTASKS]2303 dropped = len(all_subtasks) - len(subtasks)2304 if not subtasks:2305 return "Workflow error: no usable subtasks were provided.", True2306 print(f"[workflow] fanning out {len(subtasks)} agents", file=sys.stderr)23072308 def run_one(prompt: str) -> str:2309 try:2310 return journaled(prompt, lambda: run_subagent(model, prompt))2311 except Exception as error: # isolation boundary: one bad subagent should not end the run2312 return f"(subagent failed: {type(error).__name__}: {error})"23132314 with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_CONCURRENT) as pool:2315 results = list(pool.map(run_one, subtasks))2316 print(f"[workflow] verifying {len(results)} results", file=sys.stderr)2317 verify_prompts = [verify_prompt_for(task, result) for task, result in zip(subtasks, results)]2318 verdicts = list(pool.map(run_one, verify_prompts))23192320 joined = "\n\n".join(2321 f"[agent {index + 1}: {task}]\n{result}\n\n[verify {index + 1}]\n{verdict}"2322 for index, (task, result, verdict) in enumerate(zip(subtasks, results, verdicts))2323 )2324 if dropped > 0:2325 joined = (2326 f"(note: {dropped} subtasks beyond MAX_TOTAL_SUBTASKS={MAX_TOTAL_SUBTASKS} were not "2327 "run; rerun them in a follow-up Workflow call)\n\n" + joined2328 )2329 return joined, False2330 ```23312332 ```typescript TypeScript2333 // Accept the subtasks input in whatever shape the model emits: an array, the array2334 // JSON-encoded as a single string, or a newline-separated list.2335 function normalizeSubtasks(raw: unknown): string[] {2336 let value = raw;2337 if (typeof raw === "string") {2338 try {2339 value = JSON.parse(raw);2340 } catch {2341 value = raw.includes("\n") ? raw.split("\n") : [raw];2342 }2343 }2344 if (!Array.isArray(value)) {2345 return [];2346 }2347 return value2348 .filter((task): task is string => typeof task === "string")2349 .map((task) => task.trim())2350 .filter((task) => task.length > 0);2351 }23522353 function verifyPromptFor(subtask: string, result: string): string {2354 return (2355 "Adversarially verify the subagent result below: try to REFUTE it. Re-derive the " +2356 "claims yourself with bash rather than trusting the result, and look for evidence " +2357 "that contradicts them. Default to refuted if uncertain. Call report_findings with " +2358 "summary 'refuted: <why>' or 'confirmed: <why>', citing the file:line or command " +2359 "output that decided it.\n\n" +2360 `Subtask: ${subtask}\n\nResult to verify:\n${result}`2361 );2362 }23632364 // Map with a concurrency limit: at most `limit` tasks are in flight at once.2365 async function mapWithLimit<In, Out>(2366 items: readonly In[],2367 limit: number,2368 task: (item: In) => Promise<Out>,2369 ): Promise<Out[]> {2370 const results = new Array<Out>(items.length);2371 let cursor = 0;2372 const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {2373 while (cursor < items.length) {2374 const index = cursor++;2375 results[index] = await task(items[index]);2376 }2377 });2378 await Promise.all(workers);2379 return results;2380 }23812382 // Run subtasks as parallel subagents, then run a second verification wave over2383 // the results, and return both. MAX_TOTAL_SUBTASKS bounds how many the model can2384 // queue; MAX_CONCURRENT bounds how many run at once.2385 async function runWorkflow(2386 model: string,2387 rawSubtasks: unknown,2388 ): Promise<{ output: string; isError: boolean }> {2389 const allSubtasks = normalizeSubtasks(rawSubtasks);2390 const subtasks = allSubtasks.slice(0, MAX_TOTAL_SUBTASKS);2391 const dropped = allSubtasks.length - subtasks.length;2392 if (subtasks.length === 0) {2393 return { output: "Workflow error: no usable subtasks were provided.", isError: true };2394 }2395 console.error(`[workflow] fanning out ${subtasks.length} agents`);23962397 const runOne = async (prompt: string): Promise<string> => {2398 try {2399 return await journaled(prompt, () => runSubagent(model, prompt));2400 } catch (error) {2401 // Isolation boundary: one bad subagent should not end the run.2402 const reason = error instanceof Error ? `${error.name}: ${error.message}` : String(error);2403 return `(subagent failed: ${reason})`;2404 }2405 };24062407 const results = await mapWithLimit(subtasks, MAX_CONCURRENT, runOne);2408 console.error(`[workflow] verifying ${results.length} results`);2409 const verifyPrompts = subtasks.map((task, index) => verifyPromptFor(task, results[index]));2410 const verdicts = await mapWithLimit(verifyPrompts, MAX_CONCURRENT, runOne);24112412 let joined = subtasks2413 .map(2414 (task, index) =>2415 `[agent ${index + 1}: ${task}]\n${results[index]}\n\n[verify ${index + 1}]\n${verdicts[index]}`,2416 )2417 .join("\n\n");2418 if (dropped > 0) {2419 joined =2420 `(note: ${dropped} subtasks beyond MAX_TOTAL_SUBTASKS=${MAX_TOTAL_SUBTASKS} were not ` +2421 "run; rerun them in a follow-up Workflow call)\n\n" +2422 joined;2423 }2424 return { output: joined, isError: false };2425 }2426 ```24272428 ```csharp C#2429 // Accept the subtasks input in whatever shape the model emits: an array, the array2430 // JSON-encoded as a single string, or a newline-separated list.2431 List<string> NormalizeSubtasks(JsonElement raw)2432 {2433 List<string> tasks = [];2434 if (raw.ValueKind == JsonValueKind.Array)2435 {2436 tasks = raw.EnumerateArray()2437 .Where(item => item.ValueKind == JsonValueKind.String)2438 .Select(item => item.GetString()!)2439 .ToList();2440 }2441 else if (raw.ValueKind == JsonValueKind.String)2442 {2443 var single = raw.GetString()!;2444 try2445 {2446 tasks = JsonSerializer.Deserialize<List<string>>(single) ?? [];2447 }2448 catch (JsonException)2449 {2450 tasks = [.. single.Split('\n')];2451 }2452 }2453 return tasks.Where(task => task != null).Select(task => task.Trim()).Where(task => task.Length > 0).ToList();2454 }24552456 string VerifyPromptFor(string subtask, string result) =>2457 "Adversarially verify the subagent result below: try to REFUTE it. Re-derive the "2458 + "claims yourself with bash rather than trusting the result, and look for evidence "2459 + "that contradicts them. Default to refuted if uncertain. Call report_findings with "2460 + "summary 'refuted: <why>' or 'confirmed: <why>', citing the file:line or command "2461 + "output that decided it.\n\n"2462 + $"Subtask: {subtask}\n\nResult to verify:\n{result}";24632464 // Run subtasks as parallel subagents, then run a second verification wave over2465 // the results, and return both. maxTotalSubtasks bounds how many the model can2466 // queue; maxConcurrent bounds how many run at once.2467 async Task<(string Output, bool IsError)> RunWorkflow(JsonElement rawSubtasks)2468 {2469 var allSubtasks = NormalizeSubtasks(rawSubtasks);2470 var subtasks = allSubtasks.Take(maxTotalSubtasks).ToList();2471 var dropped = allSubtasks.Count - subtasks.Count;2472 if (subtasks.Count == 0)2473 {2474 return ("Workflow error: no usable subtasks were provided.", true);2475 }2476 Console.Error.WriteLine($"[workflow] fanning out {subtasks.Count} agents");24772478 using SemaphoreSlim gate = new(maxConcurrent);2479 async Task<string> RunOne(string prompt)2480 {2481 await gate.WaitAsync();2482 try2483 {2484 return await Journaled(prompt, () => RunSubagent(prompt));2485 }2486 catch (Exception error)2487 {2488 // Isolation boundary: one bad subagent should not end the run.2489 return $"(subagent failed: {error.GetType().Name}: {error.Message})";2490 }2491 finally2492 {2493 gate.Release();2494 }2495 }24962497 var results = await Task.WhenAll(subtasks.Select(RunOne));2498 Console.Error.WriteLine($"[workflow] verifying {results.Length} results");2499 var verifyPrompts = subtasks.Select((task, index) => VerifyPromptFor(task, results[index])).ToList();2500 var verdicts = await Task.WhenAll(verifyPrompts.Select(RunOne));25012502 var joined = string.Join(2503 "\n\n",2504 subtasks.Select((task, index) =>2505 $"[agent {index + 1}: {task}]\n{results[index]}\n\n[verify {index + 1}]\n{verdicts[index]}"));2506 if (dropped > 0)2507 {2508 joined = $"(note: {dropped} subtasks beyond maxTotalSubtasks={maxTotalSubtasks} were not run; "2509 + "rerun them in a follow-up Workflow call)\n\n" + joined;2510 }2511 return (joined, false);2512 }2513 ```25142515 ```go Go2516 // normalizeSubtasks accepts the subtasks input in whatever shape the model emits: an2517 // array, the array JSON-encoded as a single string, or a newline-separated list.2518 func normalizeSubtasks(raw json.RawMessage) []string {2519 var tasks []string2520 if err := json.Unmarshal(raw, &tasks); err != nil {2521 var single string2522 if err := json.Unmarshal(raw, &single); err != nil {2523 return nil2524 }2525 if err := json.Unmarshal([]byte(single), &tasks); err != nil {2526 tasks = strings.Split(single, "\n")2527 }2528 }2529 cleaned := make([]string, 0, len(tasks))2530 for _, task := range tasks {2531 if trimmed := strings.TrimSpace(task); trimmed != "" {2532 cleaned = append(cleaned, trimmed)2533 }2534 }2535 return cleaned2536 }25372538 func verifyPromptFor(subtask, result string) string {2539 return "Adversarially verify the subagent result below: try to REFUTE it. Re-derive the " +2540 "claims yourself with bash rather than trusting the result, and look for evidence " +2541 "that contradicts them. Default to refuted if uncertain. Call report_findings with " +2542 "summary 'refuted: <why>' or 'confirmed: <why>', citing the file:line or command " +2543 "output that decided it.\n\n" +2544 "Subtask: " + subtask + "\n\nResult to verify:\n" + result2545 }25462547 // mapWithLimit runs task over items with at most limit goroutines in flight.2548 func mapWithLimit(items []string, limit int, task func(string) string) []string {2549 results := make([]string, len(items))2550 semaphore := make(chan struct{}, limit)2551 var waitGroup sync.WaitGroup2552 for index, item := range items {2553 waitGroup.Add(1)2554 semaphore <- struct{}{}2555 go func() {2556 defer waitGroup.Done()2557 defer func() { <-semaphore }()2558 results[index] = task(item)2559 }()2560 }2561 waitGroup.Wait()2562 return results2563 }25642565 // runWorkflow runs subtasks as parallel subagents, then runs a second verification wave2566 // over the results, and returns both. maxTotalSubtasks bounds how many the model can2567 // queue; maxConcurrent bounds how many run at once.2568 func runWorkflow(ctx context.Context, model string, rawSubtasks json.RawMessage) (string, bool) {2569 allSubtasks := normalizeSubtasks(rawSubtasks)2570 subtasks := allSubtasks2571 if len(subtasks) > maxTotalSubtasks {2572 subtasks = subtasks[:maxTotalSubtasks]2573 }2574 dropped := len(allSubtasks) - len(subtasks)2575 if len(subtasks) == 0 {2576 return "Workflow error: no usable subtasks were provided.", true2577 }2578 fmt.Fprintf(os.Stderr, "[workflow] fanning out %d agents\n", len(subtasks))25792580 runOne := func(prompt string) string {2581 report, err := journaled(prompt, func() (string, error) { return runSubagent(ctx, model, prompt) })2582 if err != nil {2583 // Isolation boundary: one bad subagent should not end the run.2584 return fmt.Sprintf("(subagent failed: %s)", err)2585 }2586 return report2587 }25882589 results := mapWithLimit(subtasks, maxConcurrent, runOne)2590 fmt.Fprintf(os.Stderr, "[workflow] verifying %d results\n", len(results))2591 verifyPrompts := make([]string, len(subtasks))2592 for index, task := range subtasks {2593 verifyPrompts[index] = verifyPromptFor(task, results[index])2594 }2595 verdicts := mapWithLimit(verifyPrompts, maxConcurrent, runOne)25962597 sections := make([]string, len(subtasks))2598 for index, task := range subtasks {2599 sections[index] = fmt.Sprintf("[agent %d: %s]\n%s\n\n[verify %d]\n%s",2600 index+1, task, results[index], index+1, verdicts[index])2601 }2602 joined := strings.Join(sections, "\n\n")2603 if dropped > 0 {2604 joined = fmt.Sprintf("(note: %d subtasks beyond maxTotalSubtasks=%d were not run; "+2605 "rerun them in a follow-up Workflow call)\n\n", dropped, maxTotalSubtasks) + joined2606 }2607 return joined, false2608 }26092610 ```26112612 ```java Java2613 // Accept the subtasks input in whatever shape the model emits: an array, the array2614 // JSON-encoded as a single string, or a newline-separated list.2615 List<String> normalizeSubtasks(JsonValue raw) {2616 List<String> tasks = new ArrayList<>();2617 if (raw.asArray().isPresent()) {2618 for (JsonValue item : (List<JsonValue>) raw.asArray().get()) {2619 tasks.add(item.asString().isPresent() ? item.asStringOrThrow() : item.toString());2620 }2621 } else if (raw.asString().isPresent()) {2622 String single = raw.asStringOrThrow();2623 try {2624 String[] parsed = new ObjectMapper().readValue(single, String[].class);2625 if (parsed != null) {2626 for (String task : parsed) {2627 tasks.add(task);2628 }2629 }2630 } catch (JsonProcessingException error) {2631 for (String task : single.split("\n")) {2632 tasks.add(task);2633 }2634 }2635 }2636 return tasks.stream()2637 .filter(task -> task != null)2638 .map(String::trim)2639 .filter(task -> !task.isEmpty())2640 .toList();2641 }26422643 String verifyPromptFor(String subtask, String result) {2644 return "Adversarially verify the subagent result below: try to REFUTE it. Re-derive the "2645 + "claims yourself with bash rather than trusting the result, and look for evidence "2646 + "that contradicts them. Default to refuted if uncertain. Call report_findings with "2647 + "summary 'refuted: <why>' or 'confirmed: <why>', citing the file:line or command "2648 + "output that decided it.\n\n"2649 + "Subtask: " + subtask + "\n\nResult to verify:\n" + result;2650 }26512652 List<String> runAll(ExecutorService pool, List<String> prompts, Model model) throws InterruptedException {2653 List<Callable<String>> jobs = prompts.stream()2654 .<Callable<String>>map(prompt -> () -> journaled(prompt, () -> runSubagent(model, prompt)))2655 .toList();2656 List<String> results = new ArrayList<>();2657 for (Future<String> future : pool.invokeAll(jobs)) {2658 try {2659 results.add(future.get());2660 } catch (ExecutionException | CancellationException error) {2661 // Isolation boundary: one bad subagent should not end the run.2662 Throwable cause = error.getCause() != null ? error.getCause() : error;2663 results.add("(subagent failed: " + cause + ")");2664 }2665 }2666 return results;2667 }26682669 // Run subtasks as parallel subagents, then run a second verification wave over2670 // the results, and return both. MAX_TOTAL_SUBTASKS bounds how many the model can2671 // queue; MAX_CONCURRENT bounds how many run at once.2672 ToolOutput runWorkflow(Model model, JsonValue rawSubtasks) throws InterruptedException {2673 List<String> allSubtasks = normalizeSubtasks(rawSubtasks);2674 List<String> subtasks = allSubtasks.stream().limit(MAX_TOTAL_SUBTASKS).toList();2675 int dropped = allSubtasks.size() - subtasks.size();2676 if (subtasks.isEmpty()) {2677 return new ToolOutput("Workflow error: no usable subtasks were provided.", true);2678 }2679 System.err.println("[workflow] fanning out " + subtasks.size() + " agents");26802681 List<String> results;2682 List<String> verdicts;2683 try (ExecutorService pool = Executors.newFixedThreadPool(MAX_CONCURRENT, Thread.ofVirtual().factory())) {2684 results = runAll(pool, subtasks, model);2685 System.err.println("[workflow] verifying " + results.size() + " results");2686 List<String> verifyPrompts = IntStream.range(0, subtasks.size())2687 .mapToObj(index -> verifyPromptFor(subtasks.get(index), results.get(index)))2688 .toList();2689 verdicts = runAll(pool, verifyPrompts, model);2690 }2691 String joined = IntStream.range(0, subtasks.size())2692 .mapToObj(index -> "[agent " + (index + 1) + ": " + subtasks.get(index) + "]\n" + results.get(index)2693 + "\n\n[verify " + (index + 1) + "]\n" + verdicts.get(index))2694 .collect(Collectors.joining("\n\n"));2695 if (dropped > 0) {2696 joined = "(note: " + dropped + " subtasks beyond MAX_TOTAL_SUBTASKS=" + MAX_TOTAL_SUBTASKS2697 + " were not run; rerun them in a follow-up Workflow call)\n\n" + joined;2698 }2699 return new ToolOutput(joined, false);2700 }2701 ```27022703 ```php PHP2704 /**2705 * Accept the subtasks input in whatever shape the model emits: an array, the array2706 * JSON-encoded as a single string, or a newline-separated list.2707 */2708 function normalizeSubtasks(mixed $raw): array2709 {2710 if (is_string($raw)) {2711 try {2712 $raw = json_decode($raw, true, flags: JSON_THROW_ON_ERROR);2713 } catch (JsonException) {2714 $raw = str_contains($raw, "\n") ? explode("\n", $raw) : [$raw];2715 }2716 }2717 if (!is_array($raw)) {2718 return [];2719 }2720 $tasks = array_map('trim', array_filter($raw, 'is_string'));2721 return array_values(array_filter($tasks, fn ($task) => $task !== ''));2722 }27232724 function verifyPromptFor(string $subtask, string $result): string2725 {2726 return 'Adversarially verify the subagent result below: try to REFUTE it. Re-derive the '2727 . 'claims yourself with bash rather than trusting the result, and look for evidence '2728 . 'that contradicts them. Default to refuted if uncertain. Call report_findings with '2729 . "summary 'refuted: <why>' or 'confirmed: <why>', citing the file:line or command "2730 . "output that decided it.\n\n"2731 . "Subtask: {$subtask}\n\nResult to verify:\n{$result}";2732 }27332734 /**2735 * Run subtasks through the journal, then run a second verification wave over the2736 * results, and return both. PHP's standard runtime has no lightweight thread pool,2737 * so both waves run sequentially here (MAX_CONCURRENT is unused); the SDK examples2738 * in other languages fan them out in parallel.2739 */2740 function runWorkflow(Client $client, string $model, mixed $rawSubtasks): array2741 {2742 $allSubtasks = normalizeSubtasks($rawSubtasks);2743 $subtasks = array_slice($allSubtasks, 0, MAX_TOTAL_SUBTASKS);2744 $dropped = count($allSubtasks) - count($subtasks);2745 if ($subtasks === []) {2746 return ['Workflow error: no usable subtasks were provided.', true];2747 }2748 fwrite(STDERR, '[workflow] running ' . count($subtasks) . " agents\n");27492750 $runOne = function (string $prompt) use ($client, $model): string {2751 try {2752 return journaled($prompt, fn () => runSubagent($client, $model, $prompt));2753 } catch (Throwable $error) {2754 // Isolation boundary: one bad subagent should not end the run.2755 return '(subagent failed: ' . $error::class . ': ' . $error->getMessage() . ')';2756 }2757 };27582759 $results = array_map($runOne, $subtasks);2760 fwrite(STDERR, '[workflow] verifying ' . count($results) . " results\n");2761 $verifyPrompts = array_map(verifyPromptFor(...), $subtasks, $results);2762 $verdicts = array_map($runOne, $verifyPrompts);27632764 $sections = [];2765 foreach ($subtasks as $index => $task) {2766 $sections[] = '[agent ' . ($index + 1) . ": {$task}]\n{$results[$index]}"2767 . "\n\n[verify " . ($index + 1) . "]\n{$verdicts[$index]}";2768 }2769 $joined = implode("\n\n", $sections);2770 if ($dropped > 0) {2771 $joined = '(note: ' . $dropped . ' subtasks beyond MAX_TOTAL_SUBTASKS=' . MAX_TOTAL_SUBTASKS2772 . " were not run; rerun them in a follow-up Workflow call)\n\n" . $joined;2773 }2774 return [$joined, false];2775 }2776 ```27772778 ```ruby Ruby2779 # Accept the subtasks input in whatever shape the model emits: an array, the array2780 # JSON-encoded as a single string, or a newline-separated list.2781 def normalize_subtasks(raw)2782 if raw.is_a?(String)2783 begin2784 raw = JSON.parse(raw)2785 rescue JSON::ParserError2786 raw = raw.include?("\n") ? raw.split("\n") : [raw]2787 end2788 end2789 return [] unless raw.is_a?(Array)2790 raw.select { |task| task.is_a?(String) }.map(&:strip).reject(&:empty?)2791 end27922793 def verify_prompt_for(subtask, result)2794 "Adversarially verify the subagent result below: try to REFUTE it. Re-derive the " \2795 "claims yourself with bash rather than trusting the result, and look for evidence " \2796 "that contradicts them. Default to refuted if uncertain. Call report_findings with " \2797 "summary 'refuted: <why>' or 'confirmed: <why>', citing the file:line or command " \2798 "output that decided it.\n\n" \2799 "Subtask: #{subtask}\n\nResult to verify:\n#{result}"2800 end28012802 # Map with a concurrency limit: at most `limit` threads are in flight at once.2803 def map_with_limit(items, limit)2804 results = Array.new(items.length)2805 queue = Queue.new2806 items.each_with_index { |item, index| queue << [index, item] }2807 workers = Array.new([limit, items.length].min) do2808 Thread.new do2809 until queue.empty?2810 index, item = queue.pop(true) rescue break2811 results[index] = yield item2812 end2813 end2814 end2815 workers.each(&:join)2816 results2817 end28182819 # Run subtasks as parallel subagents, then run a second verification wave over2820 # the results, and return both. MAX_TOTAL_SUBTASKS bounds how many the model can2821 # queue; MAX_CONCURRENT bounds how many run at once.2822 def run_workflow(model, raw_subtasks)2823 all_subtasks = normalize_subtasks(raw_subtasks)2824 subtasks = all_subtasks.first(MAX_TOTAL_SUBTASKS)2825 dropped = all_subtasks.length - subtasks.length2826 return ["Workflow error: no usable subtasks were provided.", true] if subtasks.empty?28272828 warn "[workflow] fanning out #{subtasks.length} agents"2829 run_one = lambda do |prompt|2830 journaled(prompt) { run_subagent(model, prompt) }2831 rescue => error # isolation boundary: one bad subagent should not end the run2832 "(subagent failed: #{error.class}: #{error.message})"2833 end28342835 results = map_with_limit(subtasks, MAX_CONCURRENT, &run_one)2836 warn "[workflow] verifying #{results.length} results"2837 verify_prompts = subtasks.zip(results).map { |task, result| verify_prompt_for(task, result) }2838 verdicts = map_with_limit(verify_prompts, MAX_CONCURRENT, &run_one)28392840 joined = subtasks.each_with_index.map do |task, index|2841 "[agent #{index + 1}: #{task}]\n#{results[index]}\n\n[verify #{index + 1}]\n#{verdicts[index]}"2842 end.join("\n\n")2843 if dropped > 02844 joined =2845 "(note: #{dropped} subtasks beyond MAX_TOTAL_SUBTASKS=#{MAX_TOTAL_SUBTASKS} were not " \2846 "run; rerun them in a follow-up Workflow call)\n\n#{joined}"2847 end2848 [joined, false]2849 end2850 ```2851</CodeGroup>28522853## Toggle the mode with mid-conversation system messages28542855The agent appends the user's message first, then any system messages that are due: the exit notice, the full mode text on entry, or the periodic refresher. Placing the system message after the user turn keeps every cached byte ahead of it untouched, and satisfies the placement rule that a system message follows a user turn.28562857<CodeGroup>2858 ```bash cURL2859 # One orchestration-mode turn: the mode reminder rides in the messages array as a2860 # {"role": "system"} entry placed after the user turn it applies to. The response2861 # stops at the first tool call. The agent loop that executes tool calls and fans2862 # out subagents is shown in the SDK tabs; the Workflow description is condensed2863 # here, the SDK examples carry the full standing-consent text.2864 curl --fail-with-body -sS https://api.anthropic.com/v1/messages \2865 -H "x-api-key: $ANTHROPIC_API_KEY" \2866 -H "anthropic-version: 2023-06-01" \2867 -H "content-type: application/json" \2868 -d @- <<'EOF'2869 {2870 "model": "claude-opus-5",2871 "max_tokens": 64000,2872 "system": "You are a helpful general-purpose agent. Answer the user's request directly.",2873 "output_config": {"effort": "xhigh"},2874 "tools": [2875 {2876 "name": "Workflow",2877 "description": "Orchestrate a multiagent workflow: split a large task into independent subtasks and run them as parallel agents, then collect their results. Opt-in: only use this tool when the user explicitly asks for a workflow, or when a system message confirms that orchestration mode is on. Granularity: scope each subtask to a distinct concern rather than per line or file section; a review of a small module rarely needs more than about ten. Standing consent: while a system message confirms orchestration mode is on, author and run a workflow for every substantive task by default; work solo only on conversational turns or trivial mechanical edits.",2878 "input_schema": {2879 "type": "object",2880 "properties": {2881 "subtasks": {2882 "type": "array",2883 "items": {"type": "string"},2884 "description": "Independent subtask prompts to run as parallel agents"2885 }2886 },2887 "required": ["subtasks"]2888 }2889 },2890 {"type": "bash_20250124", "name": "bash"}2891 ],2892 "messages": [2893 {2894 "role": "user",2895 "content": "Explore the current directory, then give a thorough review: what it does, code-quality issues, and concrete improvements."2896 },2897 {2898 "role": "system",2899 "content": "Orchestration mode is on: optimize for the most exhaustive, correct answer rather than the fastest one. Use the Workflow tool on every substantive task, sized to the problem's natural decomposition rather than the maximum the tool allows. See the Workflow tool's description for standing consent, granularity guidance, and quality patterns. Work solo only on conversational or trivial turns."2900 }2901 ]2902 }2903 EOF2904 ```29052906 ```bash CLI2907 # One orchestration-mode turn: the mode reminder rides in the messages array as a2908 # system-role entry placed after the user turn it applies to. The response stops2909 # at the first tool call. The agent loop that executes tool calls and fans out2910 # subagents is shown in the SDK tabs; the Workflow description is condensed here,2911 # the SDK examples carry the full standing-consent text.2912 ant messages create <<'YAML'2913 model: claude-opus-52914 max_tokens: 640002915 system: You are a helpful general-purpose agent. Answer the user's request directly.2916 output_config: {effort: xhigh}2917 tools:2918 - name: Workflow2919 description: >-2920 Orchestrate a multiagent workflow: split a large task into independent2921 subtasks and run them as parallel agents, then collect their results.2922 Opt-in: only use this tool when the user explicitly asks for a workflow,2923 or when a system message confirms that orchestration mode is on.2924 Granularity: scope each subtask to a distinct concern rather than per2925 line or file section; a review of a small module rarely needs more than2926 about ten. Standing consent: while a system message confirms2927 orchestration mode is on, author and run a workflow for every2928 substantive task by default; work solo only on conversational turns or2929 trivial mechanical edits.2930 input_schema:2931 type: object2932 properties:2933 subtasks:2934 type: array2935 items: {type: string}2936 description: Independent subtask prompts to run as parallel agents2937 required: [subtasks]2938 - {type: bash_20250124, name: bash}2939 messages:2940 - role: user2941 content: >-2942 Explore the current directory, then give a thorough review: what it2943 does, code-quality issues, and concrete improvements.2944 - role: system2945 content: >-2946 Orchestration mode is on: optimize for the most exhaustive, correct2947 answer rather than the fastest one. Use the Workflow tool on every2948 substantive task, sized to the problem's natural decomposition rather2949 than the maximum the tool allows. See the Workflow tool's description2950 for standing consent, granularity guidance, and quality patterns. Work2951 solo only on conversational or trivial turns.2952 YAML2953 ```29542955 ```python Python2956 class ModeAgent:2957 """An agent loop whose orchestration mode is toggled with mid-conversation system messages."""29582959 def __init__(self, model: str, mode_on: bool = True):2960 self.model = model2961 self.mode_on = mode_on2962 self.messages: list[dict] = []2963 self._mode_announced = False2964 self._exit_pending = False2965 self._turns_since_reminder = 029662967 def set_mode(self, mode_on: bool) -> None:2968 """Turn the mode on or off. The notice is delivered with the next user turn."""2969 if mode_on == self.mode_on:2970 return2971 if not mode_on:2972 if self._mode_announced:2973 self._exit_pending = True2974 else:2975 self._exit_pending = False2976 self.mode_on = mode_on29772978 def _due_system_messages(self) -> list[dict]:2979 """System messages owed on this turn: an exit notice, the full mode text on entry,2980 or a one-line refresher every TURNS_BETWEEN_REFRESHERS user turns."""2981 due = []2982 if self._exit_pending:2983 self._exit_pending = False2984 self._mode_announced = False2985 due.append({"role": "system", "content": MODE_EXIT})2986 if self.mode_on:2987 if not self._mode_announced:2988 self._mode_announced = True2989 self._turns_since_reminder = 02990 due.append({"role": "system", "content": MODE_ENTER})2991 elif self._turns_since_reminder >= TURNS_BETWEEN_REFRESHERS:2992 self._turns_since_reminder = 02993 due.append({"role": "system", "content": MODE_REFRESH})2994 return due29952996 def turn(self, user_input: str) -> str:2997 # Mid-conversation system messages follow the user turn they apply to, which keeps2998 # the cached prefix ahead of them untouched.2999 self.messages.append({"role": "user", "content": user_input})3000 self.messages.extend(self._due_system_messages())3001 self._turns_since_reminder += 130023003 for _ in range(MAX_MAIN_TURNS):3004 with client.messages.stream(3005 model=self.model,3006 max_tokens=64000,3007 system=SYSTEM_PROMPT, # static for the whole session3008 output_config={"effort": EFFORT},3009 tools=[WORKFLOW_TOOL, BASH_TOOL],3010 messages=self.messages,3011 timeout=REQUEST_TIMEOUT_SECONDS,3012 ) as stream:3013 response = stream.get_final_message()3014 self.messages.append({"role": "assistant", "content": response.content})30153016 if response.stop_reason == "pause_turn":3017 continue3018 if response.stop_reason != "tool_use":3019 text = "".join(block.text for block in response.content if block.type == "text")3020 if response.stop_reason == "max_tokens":3021 # Drop the truncated assistant message so later turns don't build on it.3022 self.messages.pop()3023 text += "\n\n(warning: response was truncated at max_tokens)"3024 return text30253026 tool_results = []3027 for block in response.content:3028 if block.type != "tool_use":3029 continue3030 match block.name:3031 case "Workflow":3032 output, is_error = run_workflow(self.model, block.input.get("subtasks", []))3033 case "bash":3034 output, is_error = handle_bash_block(block)3035 case _:3036 output, is_error = f"unknown tool: {block.name}", True3037 tool_results.append(3038 {3039 "type": "tool_result",3040 "tool_use_id": block.id,3041 "content": output,3042 "is_error": is_error,3043 }3044 )3045 self.messages.append({"role": "user", "content": tool_results})3046 return "(hit the main loop turn limit before finishing)"3047 ```30483049 ```typescript TypeScript3050 // An agent loop whose orchestration mode is toggled with mid-conversation system messages.3051 class ModeAgent {3052 private readonly model: string;3053 private modeOn: boolean;3054 private readonly messages: Anthropic.MessageParam[] = [];3055 private modeAnnounced = false;3056 private exitPending = false;3057 private turnsSinceReminder = 0;30583059 constructor(model: string, modeOn = true) {3060 this.model = model;3061 this.modeOn = modeOn;3062 }30633064 // Turn the mode on or off. The notice is delivered with the next user turn.3065 setMode(modeOn: boolean): void {3066 if (modeOn === this.modeOn) {3067 return;3068 }3069 if (!modeOn) {3070 if (this.modeAnnounced) {3071 this.exitPending = true;3072 }3073 } else {3074 this.exitPending = false;3075 }3076 this.modeOn = modeOn;3077 }30783079 // System messages owed on this turn: an exit notice, the full mode text on entry,3080 // or a one-line refresher every TURNS_BETWEEN_REFRESHERS user turns.3081 private dueSystemMessages(): Anthropic.MessageParam[] {3082 const due: Array<{ role: "system"; content: string }> = [];3083 if (this.exitPending) {3084 this.exitPending = false;3085 this.modeAnnounced = false;3086 due.push({ role: "system", content: MODE_EXIT });3087 }3088 if (this.modeOn) {3089 if (!this.modeAnnounced) {3090 this.modeAnnounced = true;3091 this.turnsSinceReminder = 0;3092 due.push({ role: "system", content: MODE_ENTER });3093 } else if (this.turnsSinceReminder >= TURNS_BETWEEN_REFRESHERS) {3094 this.turnsSinceReminder = 0;3095 due.push({ role: "system", content: MODE_REFRESH });3096 }3097 }3098 // The published SDK types message roles as "user" | "assistant"; typed support for3099 // mid-conversation system messages ships with the SDK release that includes them.3100 return due as unknown as Anthropic.MessageParam[];3101 }31023103 async turn(userInput: string): Promise<string> {3104 // Mid-conversation system messages follow the user turn they apply to, which keeps3105 // the cached prefix ahead of them untouched.3106 this.messages.push({ role: "user", content: userInput });3107 this.messages.push(...this.dueSystemMessages());3108 this.turnsSinceReminder += 1;31093110 for (let turn = 0; turn < MAX_MAIN_TURNS; turn++) {3111 const response = await client.messages3112 .stream(3113 {3114 model: this.model,3115 max_tokens: 64000,3116 system: SYSTEM_PROMPT, // static for the whole session3117 output_config: { effort: EFFORT },3118 tools: [WORKFLOW_TOOL, BASH_TOOL],3119 messages: this.messages,3120 },3121 { signal: AbortSignal.timeout(REQUEST_TIMEOUT_SECONDS * 1000) },3122 )3123 .finalMessage();3124 this.messages.push({ role: "assistant", content: response.content });31253126 if (response.stop_reason === "pause_turn") {3127 continue;3128 }3129 if (response.stop_reason !== "tool_use") {3130 let text = response.content3131 .filter((block): block is Anthropic.TextBlock => block.type === "text")3132 .map((block) => block.text)3133 .join("");3134 if (response.stop_reason === "max_tokens") {3135 // Drop the truncated assistant message so later turns do not build on it.3136 this.messages.pop();3137 text += "\n\n(warning: response was truncated at max_tokens)";3138 }3139 return text;3140 }31413142 const toolResults: Anthropic.ToolResultBlockParam[] = [];3143 for (const block of response.content) {3144 if (block.type !== "tool_use") {3145 continue;3146 }3147 let output: string;3148 let isError: boolean;3149 switch (block.name) {3150 case "Workflow": {3151 const input = block.input as { subtasks?: unknown };3152 ({ output, isError } = await runWorkflow(this.model, input.subtasks ?? []));3153 break;3154 }3155 case "bash":3156 ({ output, isError } = await handleBashBlock(block));3157 break;3158 default:3159 output = `unknown tool: ${block.name}`;3160 isError = true;3161 }3162 toolResults.push({3163 type: "tool_result",3164 tool_use_id: block.id,3165 content: output,3166 is_error: isError,3167 });3168 }3169 this.messages.push({ role: "user", content: toolResults });3170 }3171 return "(hit the main loop turn limit before finishing)";3172 }3173 }3174 ```31753176 ```csharp C#3177 // An agent loop whose orchestration mode is toggled with mid-conversation system messages.3178 List<MessageParam> messages = [];3179 var modeOn = true;3180 var modeAnnounced = false;3181 var exitPending = false;3182 var turnsSinceReminder = 0;31833184 // Turn the mode on or off. The notice is delivered with the next user turn.3185 void SetMode(bool nextModeOn)3186 {3187 if (nextModeOn == modeOn)3188 {3189 return;3190 }3191 if (!nextModeOn)3192 {3193 if (modeAnnounced)3194 {3195 exitPending = true;3196 }3197 }3198 else3199 {3200 exitPending = false;3201 }3202 modeOn = nextModeOn;3203 }32043205 // The Role property is an open enum, so the mid-conversation "system" role can be assigned3206 // as a raw string; a dedicated constant ships with the SDK release.3207 MessageParam SystemMessage(string content) => new() { Role = "system", Content = content };32083209 // System messages owed on this turn: an exit notice, the full mode text on entry,3210 // or a one-line refresher every turnsBetweenRefreshers user turns.3211 List<MessageParam> DueSystemMessages()3212 {3213 List<MessageParam> due = [];3214 if (exitPending)3215 {3216 exitPending = false;3217 modeAnnounced = false;3218 due.Add(SystemMessage(modeExit));3219 }3220 if (modeOn)3221 {3222 if (!modeAnnounced)3223 {3224 modeAnnounced = true;3225 turnsSinceReminder = 0;3226 due.Add(SystemMessage(modeEnter));3227 }3228 else if (turnsSinceReminder >= turnsBetweenRefreshers)3229 {3230 turnsSinceReminder = 0;3231 due.Add(SystemMessage(modeRefresh));3232 }3233 }3234 return due;3235 }32363237 // Send one user turn through the loop, executing tool calls until the model stops.3238 async Task<string> Turn(string userInput)3239 {3240 // Mid-conversation system messages follow the user turn they apply to, which keeps3241 // the cached prefix ahead of them untouched.3242 messages.Add(new() { Role = Role.User, Content = userInput });3243 messages.AddRange(DueSystemMessages());3244 turnsSinceReminder++;32453246 for (var turn = 0; turn < maxMainTurns; turn++)3247 {3248 using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(requestTimeoutSeconds));3249 var response = await client.Messages.Create(new MessageCreateParams3250 {3251 Model = model,3252 MaxTokens = requestMaxTokens,3253 System = systemPrompt, // static for the whole session3254 OutputConfig = new OutputConfig { Effort = effort },3255 Tools = [workflowTool, bashTool],3256 Messages = messages,3257 }, cancellationToken: deadline.Token);3258 messages.Add(new()3259 {3260 Role = Role.Assistant,3261 Content = response.Content.Select(block => new ContentBlockParam(block.Json)).ToList(),3262 });32633264 if (response.StopReason == StopReason.PauseTurn)3265 {3266 continue;3267 }3268 if (response.StopReason != StopReason.ToolUse)3269 {3270 var text = string.Concat(3271 response.Content.Select(block => block.TryPickText(out var textBlock) ? textBlock.Text : ""));3272 if (response.StopReason == StopReason.MaxTokens)3273 {3274 // Drop the truncated assistant message so the next turn does not build on it.3275 messages.RemoveAt(messages.Count - 1);3276 text += "\n\n(warning: response was truncated at max_tokens)";3277 }3278 return text;3279 }32803281 List<ContentBlockParam> toolResults = [];3282 foreach (var block in response.Content)3283 {3284 if (!block.TryPickToolUse(out var toolUse))3285 {3286 continue;3287 }3288 string output;3289 bool isError;3290 if (toolUse.Name == "Workflow")3291 {3292 toolUse.Input.TryGetValue("subtasks", out var rawSubtasks);3293 (output, isError) = await RunWorkflow(rawSubtasks);3294 }3295 else if (toolUse.Name == "bash")3296 {3297 (output, isError) = await HandleBashBlock(toolUse);3298 }3299 else3300 {3301 output = $"unknown tool: {toolUse.Name}";3302 isError = true;3303 }3304 toolResults.Add(new ToolResultBlockParam(toolUse.ID) { Content = output, IsError = isError });3305 }3306 messages.Add(new() { Role = Role.User, Content = toolResults });3307 }3308 return "(hit the main loop turn limit before finishing)";3309 }3310 ```33113312 ```go Go3313 // modeAgent is an agent loop whose orchestration mode is toggled with mid-conversation3314 // system messages.3315 type modeAgent struct {3316 model string3317 modeOn bool3318 messages []anthropic.MessageParam3319 modeAnnounced bool3320 exitPending bool3321 turnsSinceReminder int3322 }33233324 func newModeAgent(model string) *modeAgent {3325 return &modeAgent{model: model, modeOn: true}3326 }33273328 // setMode turns the mode on or off. The notice is delivered with the next user turn.3329 func (agent *modeAgent) setMode(modeOn bool) {3330 if modeOn == agent.modeOn {3331 return3332 }3333 if !modeOn {3334 if agent.modeAnnounced {3335 agent.exitPending = true3336 }3337 } else {3338 agent.exitPending = false3339 }3340 agent.modeOn = modeOn3341 }33423343 // dueSystemMessages returns the system messages owed on this turn: an exit notice, the3344 // full mode text on entry, or a one-line refresher every turnsBetweenRefreshers user turns.3345 func (agent *modeAgent) dueSystemMessages() []anthropic.MessageParam {3346 // MessageParamRole is an open string type, so the mid-conversation "system" role can3347 // be expressed directly; a dedicated constant ships with the SDK release.3348 systemMessage := func(content string) anthropic.MessageParam {3349 return anthropic.MessageParam{3350 Role: anthropic.MessageParamRole("system"),3351 Content: []anthropic.ContentBlockParamUnion{anthropic.NewTextBlock(content)},3352 }3353 }3354 var due []anthropic.MessageParam3355 if agent.exitPending {3356 agent.exitPending = false3357 agent.modeAnnounced = false3358 due = append(due, systemMessage(modeExit))3359 }3360 if agent.modeOn {3361 if !agent.modeAnnounced {3362 agent.modeAnnounced = true3363 agent.turnsSinceReminder = 03364 due = append(due, systemMessage(modeEnter))3365 } else if agent.turnsSinceReminder >= turnsBetweenRefreshers {3366 agent.turnsSinceReminder = 03367 due = append(due, systemMessage(modeRefresh))3368 }3369 }3370 return due3371 }33723373 // turn sends one user turn through the loop, executing tool calls until the model stops.3374 func (agent *modeAgent) turn(ctx context.Context, userInput string) (string, error) {3375 // Mid-conversation system messages follow the user turn they apply to, which keeps3376 // the cached prefix ahead of them untouched.3377 agent.messages = append(agent.messages, anthropic.NewUserMessage(anthropic.NewTextBlock(userInput)))3378 agent.messages = append(agent.messages, agent.dueSystemMessages()...)3379 agent.turnsSinceReminder++33803381 for range maxMainTurns {3382 var response anthropic.Message3383 err := func() error {3384 ctx, cancel := context.WithTimeout(ctx, requestTimeoutSeconds*time.Second)3385 defer cancel()3386 stream := client.Messages.NewStreaming(ctx, anthropic.MessageNewParams{3387 Model: agent.model,3388 MaxTokens: 64000,3389 System: []anthropic.TextBlockParam{{Text: systemPrompt}}, // static for the whole session3390 OutputConfig: anthropic.OutputConfigParam{Effort: effort},3391 Tools: []anthropic.ToolUnionParam{workflowTool, bashTool},3392 Messages: agent.messages,3393 })3394 defer stream.Close()3395 for stream.Next() {3396 if err := response.Accumulate(stream.Current()); err != nil {3397 return err3398 }3399 }3400 return stream.Err()3401 }()3402 if err != nil {3403 return "", err3404 }3405 agent.messages = append(agent.messages, response.ToParam())34063407 if response.StopReason == anthropic.StopReasonPauseTurn {3408 continue3409 }3410 if response.StopReason != anthropic.StopReasonToolUse {3411 var text strings.Builder3412 for _, block := range response.Content {3413 if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {3414 text.WriteString(textBlock.Text)3415 }3416 }3417 if response.StopReason == anthropic.StopReasonMaxTokens {3418 // Drop the truncated assistant message rather than leave a clipped turn in history.3419 agent.messages = agent.messages[:len(agent.messages)-1]3420 text.WriteString("\n\n(warning: response was truncated at max_tokens)")3421 }3422 return text.String(), nil3423 }34243425 var toolResults []anthropic.ContentBlockParamUnion3426 for _, block := range response.Content {3427 toolUse, ok := block.AsAny().(anthropic.ToolUseBlock)3428 if !ok {3429 continue3430 }3431 var output string3432 var isError bool3433 switch toolUse.Name {3434 case "Workflow":3435 var input struct {3436 Subtasks json.RawMessage `json:"subtasks"`3437 }3438 if err := json.Unmarshal(toolUse.Input, &input); err != nil {3439 output, isError = fmt.Sprintf("Workflow error: could not parse input: %s", err), true3440 } else {3441 output, isError = runWorkflow(ctx, agent.model, input.Subtasks)3442 }3443 case "bash":3444 output, isError = handleBashBlock(ctx, toolUse)3445 default:3446 output, isError = fmt.Sprintf("unknown tool: %s", toolUse.Name), true3447 }3448 toolResults = append(toolResults, anthropic.NewToolResultBlock(toolUse.ID, output, isError))3449 }3450 agent.messages = append(agent.messages, anthropic.NewUserMessage(toolResults...))3451 }3452 return "(hit the main loop turn limit before finishing)", nil3453 }34543455 ```34563457 ```java Java3458 // An agent loop whose orchestration mode is toggled with mid-conversation system messages.3459 class ModeAgent {3460 private final Model model;3461 private boolean modeOn;3462 private final List<MessageParam> messages = new ArrayList<>();3463 private boolean modeAnnounced = false;3464 private boolean exitPending = false;3465 private int turnsSinceReminder = 0;34663467 ModeAgent(Model model) {3468 this(model, true);3469 }34703471 ModeAgent(Model model, boolean modeOn) {3472 this.model = model;3473 this.modeOn = modeOn;3474 }34753476 // Turn the mode on or off. The notice is delivered with the next user turn.3477 void setMode(boolean modeOn) {3478 if (modeOn == this.modeOn) {3479 return;3480 }3481 if (!modeOn) {3482 if (modeAnnounced) {3483 exitPending = true;3484 }3485 } else {3486 exitPending = false;3487 }3488 this.modeOn = modeOn;3489 }34903491 // System messages owed on this turn: an exit notice, the full mode text on entry,3492 // or a one-line refresher every TURNS_BETWEEN_REFRESHERS user turns.3493 private List<MessageParam> dueSystemMessages() {3494 List<MessageParam> due = new ArrayList<>();3495 if (exitPending) {3496 exitPending = false;3497 modeAnnounced = false;3498 due.add(systemMessage(MODE_EXIT));3499 }3500 if (modeOn) {3501 if (!modeAnnounced) {3502 modeAnnounced = true;3503 turnsSinceReminder = 0;3504 due.add(systemMessage(MODE_ENTER));3505 } else if (turnsSinceReminder >= TURNS_BETWEEN_REFRESHERS) {3506 turnsSinceReminder = 0;3507 due.add(systemMessage(MODE_REFRESH));3508 }3509 }3510 return due;3511 }35123513 // MessageParam.Role is an open enum, so the mid-conversation "system" role can be3514 // expressed with Role.of; a dedicated constant ships with the SDK release.3515 private MessageParam systemMessage(String content) {3516 return MessageParam.builder()3517 .role(MessageParam.Role.of("system"))3518 .content(content)3519 .build();3520 }35213522 // Send one user turn through the loop, executing tool calls until the model stops.3523 String turn(String userInput) throws InterruptedException {3524 // Mid-conversation system messages follow the user turn they apply to, which keeps3525 // the cached prefix ahead of them untouched.3526 messages.add(MessageParam.builder().role(MessageParam.Role.USER).content(userInput).build());3527 messages.addAll(dueSystemMessages());3528 turnsSinceReminder++;35293530 for (int turn = 0; turn < MAX_MAIN_TURNS; turn++) {3531 MessageCreateParams params = MessageCreateParams.builder()3532 .model(model)3533 .maxTokens(64000L)3534 .system(SYSTEM_PROMPT) // static for the whole session3535 .outputConfig(OutputConfig.builder().effort(EFFORT).build())3536 .addTool(WORKFLOW_TOOL)3537 .addTool(BASH_TOOL)3538 .messages(messages)3539 .build();3540 MessageAccumulator accumulator = MessageAccumulator.create();3541 try (var stream = client.messages().createStreaming(params, REQUEST_OPTIONS)) {3542 stream.stream().forEach(accumulator::accumulate);3543 }3544 Message response = accumulator.message();3545 messages.add(response.toParam());35463547 StopReason stopReason = response.stopReason().orElse(null);3548 if (StopReason.PAUSE_TURN.equals(stopReason)) {3549 continue;3550 }3551 if (!StopReason.TOOL_USE.equals(stopReason)) {3552 String text = response.content().stream()3553 .flatMap(block -> block.text().stream())3554 .map(TextBlock::text)3555 .collect(Collectors.joining());3556 if (StopReason.MAX_TOKENS.equals(stopReason)) {3557 // Drop the truncated assistant message so it does not poison later turns.3558 messages.removeLast();3559 text += "\n\n(warning: response was truncated at max_tokens)";3560 }3561 return text;3562 }35633564 List<ContentBlockParam> toolResults = new ArrayList<>();3565 for (ContentBlock block : response.content()) {3566 if (block.toolUse().isEmpty()) {3567 continue;3568 }3569 ToolUseBlock toolUse = block.toolUse().get();3570 ToolOutput result = switch (toolUse.name()) {3571 case "Workflow" -> {3572 Map<String, JsonValue> input =3573 (Map<String, JsonValue>) toolUse._input().asObject().orElse(Map.of());3574 JsonValue rawSubtasks = input.getOrDefault("subtasks", JsonValue.from(List.of()));3575 yield runWorkflow(model, rawSubtasks);3576 }3577 case "bash" -> handleBashBlock(toolUse);3578 default -> new ToolOutput("unknown tool: " + toolUse.name(), true);3579 };3580 toolResults.add(ContentBlockParam.ofToolResult(ToolResultBlockParam.builder()3581 .toolUseId(toolUse.id())3582 .content(result.output())3583 .isError(result.isError())3584 .build()));3585 }3586 messages.add(MessageParam.builder()3587 .role(MessageParam.Role.USER)3588 .contentOfBlockParams(toolResults)3589 .build());3590 }3591 return "(hit the main loop turn limit before finishing)";3592 }3593 }3594 ```35953596 ```php PHP3597 /** An agent loop whose orchestration mode is toggled with mid-conversation system messages. */3598 class ModeAgent3599 {3600 private array $messages = [];3601 private bool $modeAnnounced = false;3602 private bool $exitPending = false;3603 private int $turnsSinceReminder = 0;36043605 public function __construct(3606 private readonly Client $client,3607 private readonly string $model,3608 private bool $modeOn = true,3609 ) {3610 }36113612 /** Turn the mode on or off. The notice is delivered with the next user turn. */3613 public function setMode(bool $modeOn): void3614 {3615 if ($modeOn === $this->modeOn) {3616 return;3617 }3618 if ($modeOn) {3619 $this->exitPending = false;3620 } elseif ($this->modeAnnounced) {3621 $this->exitPending = true;3622 }3623 $this->modeOn = $modeOn;3624 }36253626 public function turn(string $userInput): string3627 {3628 // Mid-conversation system messages follow the user turn they apply to, which keeps3629 // the cached prefix ahead of them untouched.3630 $this->messages[] = ['role' => 'user', 'content' => $userInput];3631 array_push($this->messages, ...$this->dueSystemMessages());3632 $this->turnsSinceReminder++;36333634 for ($turn = 0; $turn < MAX_MAIN_TURNS; $turn++) {3635 $stream = $this->client->messages->createStream(3636 model: $this->model,3637 maxTokens: 64000,3638 system: SYSTEM_PROMPT, // static for the whole session3639 outputConfig: ['effort' => EFFORT],3640 tools: [WORKFLOW_TOOL, BASH_TOOL],3641 messages: $this->messages,3642 requestOptions: ['timeout' => REQUEST_TIMEOUT_SECONDS],3643 );3644 [$content, $stopReason] = drainMessageStream($stream);3645 $this->messages[] = ['role' => 'assistant', 'content' => $content];36463647 if ($stopReason === 'pause_turn') {3648 continue;3649 }3650 if ($stopReason !== 'tool_use') {3651 $text = '';3652 foreach ($content as $block) {3653 if ($block instanceof \Anthropic\Messages\TextBlock) {3654 $text .= $block->text;3655 }3656 }3657 if ($stopReason === 'max_tokens') {3658 // Drop the truncated assistant message so the next turn does not build on it.3659 array_pop($this->messages);3660 $text .= "\n\n(warning: response was truncated at max_tokens)";3661 }3662 return $text;3663 }36643665 $toolResults = [];3666 foreach ($content as $block) {3667 if (!$block instanceof \Anthropic\Messages\ToolUseBlock) {3668 continue;3669 }3670 if ($block->name === 'Workflow') {3671 [$output, $isError] =3672 runWorkflow($this->client, $this->model, $block->input['subtasks'] ?? []);3673 } elseif ($block->name === 'bash') {3674 [$output, $isError] = handleBashBlock($block);3675 } else {3676 $output = "unknown tool: {$block->name}";3677 $isError = true;3678 }3679 $toolResults[] = [3680 'type' => 'tool_result',3681 'tool_use_id' => $block->id,3682 'content' => $output,3683 'is_error' => $isError,3684 ];3685 }3686 $this->messages[] = ['role' => 'user', 'content' => $toolResults];3687 }3688 return '(hit the main loop turn limit before finishing)';3689 }36903691 /**3692 * System messages owed on this turn: an exit notice, the full mode text on entry,3693 * or a one-line refresher every TURNS_BETWEEN_REFRESHERS user turns.3694 */3695 private function dueSystemMessages(): array3696 {3697 $due = [];3698 if ($this->exitPending) {3699 $this->exitPending = false;3700 $this->modeAnnounced = false;3701 $due[] = ['role' => 'system', 'content' => MODE_EXIT];3702 }3703 if ($this->modeOn) {3704 if (!$this->modeAnnounced) {3705 $this->modeAnnounced = true;3706 $this->turnsSinceReminder = 0;3707 $due[] = ['role' => 'system', 'content' => MODE_ENTER];3708 } elseif ($this->turnsSinceReminder >= TURNS_BETWEEN_REFRESHERS) {3709 $this->turnsSinceReminder = 0;3710 $due[] = ['role' => 'system', 'content' => MODE_REFRESH];3711 }3712 }3713 return $due;3714 }3715 }3716 ```37173718 ```ruby Ruby3719 # An agent loop whose orchestration mode is toggled with mid-conversation system messages.3720 class ModeAgent3721 def initialize(model, mode_on: true)3722 @model = model3723 @mode_on = mode_on3724 @messages = []3725 @mode_announced = false3726 @exit_pending = false3727 @turns_since_reminder = 03728 end37293730 # Turn the mode on or off. The notice is delivered with the next user turn.3731 def set_mode(mode_on)3732 return if mode_on == @mode_on37333734 if mode_on3735 @exit_pending = false3736 else3737 @exit_pending = true if @mode_announced3738 end3739 @mode_on = mode_on3740 end37413742 def turn(user_input)3743 # Mid-conversation system messages follow the user turn they apply to, which keeps3744 # the cached prefix ahead of them untouched.3745 @messages << {role: "user", content: user_input}3746 @messages.concat(due_system_messages)3747 @turns_since_reminder += 137483749 MAX_MAIN_TURNS.times do3750 stream = CLIENT.messages.stream(3751 model: @model,3752 max_tokens: 64_000,3753 system_: SYSTEM_PROMPT, # static for the whole session3754 output_config: {effort: EFFORT},3755 tools: [WORKFLOW_TOOL, BASH_TOOL],3756 messages: @messages,3757 request_options: {timeout: REQUEST_TIMEOUT_SECONDS}3758 )3759 response = stream.accumulated_message3760 @messages << {role: "assistant", content: assistant_content_param(response.content)}37613762 next if response.stop_reason == :pause_turn37633764 unless response.stop_reason == :tool_use3765 text = response.content.select { |block| block.type == :text }.map(&:text).join3766 if response.stop_reason == :max_tokens3767 @messages.pop # drop the truncated assistant message from the history3768 text += "\n\n(warning: response was truncated at max_tokens)"3769 end3770 return text3771 end37723773 tool_results = []3774 response.content.each do |block|3775 next unless block.type == :tool_use37763777 input = parse_tool_input(block.input)3778 case block.name3779 when "Workflow"3780 output, is_error = run_workflow(@model, input["subtasks"] || [])3781 when "bash"3782 output, is_error = handle_bash_block(block)3783 else3784 output, is_error = "unknown tool: #{block.name}", true3785 end3786 tool_results << {3787 type: "tool_result",3788 tool_use_id: block.id,3789 content: output,3790 is_error: is_error3791 }3792 end3793 @messages << {role: "user", content: tool_results}3794 end3795 "(hit the main loop turn limit before finishing)"3796 end37973798 private37993800 # System messages owed on this turn: an exit notice, the full mode text on entry,3801 # or a one-line refresher every TURNS_BETWEEN_REFRESHERS user turns.3802 def due_system_messages3803 due = []3804 if @exit_pending3805 @exit_pending = false3806 @mode_announced = false3807 due << {role: "system", content: MODE_EXIT}3808 end3809 if @mode_on3810 if !@mode_announced3811 @mode_announced = true3812 @turns_since_reminder = 03813 due << {role: "system", content: MODE_ENTER}3814 elsif @turns_since_reminder >= TURNS_BETWEEN_REFRESHERS3815 @turns_since_reminder = 03816 due << {role: "system", content: MODE_REFRESH}3817 end3818 end3819 due3820 end3821 end3822 ```3823</CodeGroup>38243825## Run it38263827<Warning>3828 The bash tool in this example runs model-written commands directly on your machine with no sandbox, and the fan-out runs several of those agents in parallel. Run it in a directory and environment you are comfortable exposing, and add sandboxing before adapting it for anything beyond local experimentation.3829</Warning>38303831<CodeGroup>3832 ```python Python3833 if __name__ == "__main__":3834 task = (3835 sys.argv[1]3836 if len(sys.argv) > 13837 else "Explore the current directory, then give a thorough review: what it does, "3838 "code-quality issues, and concrete improvements."3839 )3840 agent = ModeAgent(MODEL)3841 print(agent.turn(task))3842 agent.set_mode(False)3843 print(agent.turn("Briefly summarize what you found above, no fan-out needed."))3844 ```38453846 ```typescript TypeScript3847 const task =3848 process.argv[2] ??3849 "Explore the current directory, then give a thorough review: what it does, " +3850 "code-quality issues, and concrete improvements.";3851 const agent = new ModeAgent(MODEL);3852 console.log(await agent.turn(task));3853 agent.setMode(false);3854 console.log(await agent.turn("Briefly summarize what you found above, no fan-out needed."));3855 ```38563857 ```csharp C#3858 var task = args.Length > 03859 ? args[0]3860 : "Explore the current directory, then give a thorough review: what it does, "3861 + "code-quality issues, and concrete improvements.";3862 Console.WriteLine(await Turn(task));3863 SetMode(false);3864 Console.WriteLine(await Turn("Briefly summarize what you found above, no fan-out needed."));3865 ```38663867 ```go Go3868 func main() {3869 if err := run(context.Background()); err != nil {3870 log.Fatal(err)3871 }3872 }38733874 func run(ctx context.Context) error {3875 if docTestMode {3876 defer os.RemoveAll(workDir)3877 }3878 task := "Explore the current directory, then give a thorough review: what it does, " +3879 "code-quality issues, and concrete improvements."3880 if len(os.Args) > 1 {3881 task = os.Args[1]3882 }3883 agent := newModeAgent(modelID)3884 answer, err := agent.turn(ctx, task)3885 if err != nil {3886 return err3887 }3888 fmt.Println(answer)38893890 agent.setMode(false)3891 summary, err := agent.turn(ctx, "Briefly summarize what you found above, no fan-out needed.")3892 if err != nil {3893 return err3894 }3895 fmt.Println(summary)3896 return nil3897 }38983899 ```39003901 ```java Java3902 void main(String[] args) throws InterruptedException {3903 String task = args.length > 03904 ? args[0]3905 : "Explore the current directory, then give a thorough review: what it does, "3906 + "code-quality issues, and concrete improvements.";3907 ModeAgent agent = new ModeAgent(MODEL);3908 IO.println(agent.turn(task));3909 agent.setMode(false);3910 IO.println(agent.turn("Briefly summarize what you found above, no fan-out needed."));3911 }3912 ```39133914 ```php PHP3915 $task = $argv[1] ??3916 'Explore the current directory, then give a thorough review: what it does, '3917 . 'code-quality issues, and concrete improvements.';3918 $agent = new ModeAgent($client, MODEL);3919 echo $agent->turn($task), PHP_EOL;3920 $agent->setMode(false);3921 echo $agent->turn('Briefly summarize what you found above, no fan-out needed.'), PHP_EOL;3922 ```39233924 ```ruby Ruby3925 task = ARGV[0] ||3926 "Explore the current directory, then give a thorough review: what it does, " \3927 "code-quality issues, and concrete improvements."3928 agent = ModeAgent.new(MODEL)3929 puts agent.turn(task)3930 agent.set_mode(false)3931 puts agent.turn("Briefly summarize what you found above, no fan-out needed.")3932 ```3933</CodeGroup>39343935Start the example from the directory you want the agents to work in, for example the root of a repository to review:39363937```bash3938python orchestration_mode.py "Review this repository for flaky tests and propose fixes."3939```39403941With the mode on, expect the model to scout with a few bash commands, dispatch the Workflow tool unprompted, and synthesize the subagent reports into a final answer. Trivial or conversational requests stay solo, as the reminder instructs.39423943## Toward a production harness39443945This example is deliberately small. A harness meant for real workloads would typically add:39463947* **Sandboxed orchestration scripts:** let the model emit a short orchestration program (branching, loops, and reduce steps) and run it inside an isolated interpreter, rather than accepting only a flat list of subtask strings.3948* **Durable journaling:** replace the local JSON file with a store that survives process restarts and is safe under concurrent writers across machines.3949* **Budget enforcement:** track total subagents launched across the whole session, not just per Workflow call, and refuse to exceed a hard cap so a runaway plan cannot exhaust your quota.39503951The patterns in this example (the mode reminders, standing consent in the tool description, journaling, and a verification wave) carry over unchanged; only the execution substrate around them gets more robust.39523953## Related39543955<CardGroup cols={2}>3956 <Card title="Mid-conversation system messages" icon="message" href="https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages">3957 The mechanism the mode reminders use, and how it interacts with prompt caching.3958 </Card>39593960 <Card title="Effort" icon="gauge" href="https://platform.claude.com/docs/en/build-with-claude/effort">3961 The effort levels the API accepts and how to choose one.3962 </Card>39633964 <Card title="Tool use with Claude" icon="wrench" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview">3965 Defining tools, handling tool calls, and tool results.3966 </Card>39673968 <Card title="Bash tool" icon="terminal" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool">3969 The Anthropic-defined bash tool this example executes locally.3970 </Card>3971</CardGroup>3972