mid-conversation-effort-example changedbuild-with-claude/mid-conversation-effort-example
Nearest release: v2.1.309, published 3 hours before this site recorded the change. Shown because the two are within 24 hours of each other. Nothing here says the release caused the edit.
Recorded here
Lines+180added
Lines−174removed
From line
199
where the diff opens
First seen
14 Aug 2026
this site's first read of the page
Recorded edits13to this page, all time
The whole hunk
from line 199, old and new numbered
/
from line 199
199199
200200 static final Model MODEL = Model.CLAUDE_OPUS_5_5;
201201 static final boolean DOC_TEST_MODE =
202 !Objects.requireNonNullElse(System.getenv("DOC_TEST_MODE"), "").isEmpty();
202 !Objects.requireNonNullElse(System.getenv("DOC_TEST_MODE"), "").isEmpty();
203203 static final OutputConfig.Effort EFFORT = OutputConfig.Effort.XHIGH;
204204
205205 static final String SYSTEM_PROMPT =
206 "You are a helpful general-purpose agent. Answer the user's request directly.";
206 "You are a helpful general-purpose agent. Answer the user's request directly.";
207207
208208 static final int REQUEST_TIMEOUT_SECONDS = 600;
209209 static final RequestOptions REQUEST_OPTIONS =
210 RequestOptions.builder().timeout(Duration.ofSeconds(REQUEST_TIMEOUT_SECONDS)).build();
210 RequestOptions.builder()
211 .timeout(Duration.ofSeconds(REQUEST_TIMEOUT_SECONDS))
212 .build();
211213 static final int BASH_TIMEOUT_SECONDS = 60;
212214 static final int TOOL_RESULT_MAX_CHARS = 8000;
213215 static final int MAX_CONCURRENT = 10;
from line 218
216218 static final int MAX_MAIN_TURNS = DOC_TEST_MODE ? 1 : 30;
217219 static final int TURNS_BETWEEN_REFRESHERS = 10;
218220 static final Path JOURNAL_PATH = Path.of(Optional.ofNullable(System.getenv("ORCH_JOURNAL"))
219 .filter(path -> !path.isEmpty())
220 .orElse("orchestration_journal.json"));
221 .filter(path -> !path.isEmpty())
222 .orElse("orchestration_journal.json"));
221223 ```
222224
223225 ```php PHP
from line 332
330332
331333 ```java Java
332334 static final String MODE_ENTER = """
333 Orchestration mode is on: optimize for the most exhaustive, correct answer rather than \
334 the fastest one. Use the Workflow tool on every substantive task, sized to the problem's \
335 natural decomposition rather than the maximum the tool allows. See the Workflow tool's \
336 description for standing consent, granularity guidance, and quality patterns. Work solo \
337 only on conversational or trivial turns.""";
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.""";
338340 static final String MODE_REFRESH =
339 "Orchestration mode is still on. Use the Workflow tool; see its standing consent section.";
341 "Orchestration mode is still on. Use the Workflow tool; see its standing consent section.";
340342 static final String MODE_EXIT =
341 "Orchestration mode is off. The Workflow tool's standard opt-in rule applies again.";
343 "Orchestration mode is off. The Workflow tool's standard opt-in rule applies again.";
342344 ```
343345
344346 ```php PHP
from line 664
662664
663665 ```java Java
664666 static final Tool WORKFLOW_TOOL = Tool.builder()
665 .name("Workflow")
666 .description("""
667 Orchestrate a multiagent workflow: split a large task into independent subtasks \
668 and run them as parallel agents, then collect their results.
667 .name("Workflow")
668 .description("""
669 Orchestrate a multiagent workflow: split a large task into independent subtasks \
670 and run them as parallel agents, then collect their results.
669671
670 Opt-in: only use this tool when the user explicitly asks for a workflow, or when a \
671 system message confirms that orchestration mode is on.
672 Opt-in: only use this tool when the user explicitly asks for a workflow, or when a \
673 system message confirms that orchestration mode is on.
672674
673 Quality patterns: adversarial verification (a second wave of agents checks the first \
674 wave's findings against the source), a completeness critic (one agent hunts for what \
675 the others missed), and multiphase sequencing (understand, design, implement, and \
676 review as separate workflow calls, reading results between phases). A useful default \
677 is hybrid: scout inline first to discover the work-list, then fan out over it.
675 Quality patterns: adversarial verification (a second wave of agents checks the first \
676 wave's findings against the source), a completeness critic (one agent hunts for what \
677 the others missed), and multiphase sequencing (understand, design, implement, and \
678 review as separate workflow calls, reading results between phases). A useful default \
679 is hybrid: scout inline first to discover the work-list, then fan out over it.
678680
679 Granularity: scope each subtask to a distinct concern, component, or question rather \
680 than per line or per file section. Scale the count to what the user asked for: a \
681 focused review of a module of a few hundred lines rarely needs more than about ten \
682 subtasks; a broad audit of a large codebase can justify more.
681 Granularity: scope each subtask to a distinct concern, component, or question rather \
682 than per line or per file section. Scale the count to what the user asked for: a \
683 focused review of a module of a few hundred lines rarely needs more than about ten \
684 subtasks; a broad audit of a large codebase can justify more.
683685
684 Standing consent: while a system message confirms orchestration mode is on, that \
685 opt-in is standing. Author and run a workflow for every substantive task by default, \
686 and lean toward verifying findings adversarially. Work solo only on conversational \
687 turns or trivial mechanical edits. When a system message says the mode is off, \
688 revert to the opt-in rule above.""")
689 .inputSchema(Tool.InputSchema.builder()
690 .properties(Tool.InputSchema.Properties.builder()
691 .putAdditionalProperty("subtasks", JsonValue.from(Map.of(
692 "type", "array",
693 "items", Map.of("type", "string"),
694 "description", "Independent subtask prompts to run as parallel agents")))
695 .build())
696 .putAdditionalProperty("required", JsonValue.from(List.of("subtasks")))
697 .build())
698 .build();
686 Standing consent: while a system message confirms orchestration mode is on, that \
687 opt-in is standing. Author and run a workflow for every substantive task by default, \
688 and lean toward verifying findings adversarially. Work solo only on conversational \
689 turns or trivial mechanical edits. When a system message says the mode is off, \
690 revert to the opt-in rule above.""")
691 .inputSchema(Tool.InputSchema.builder()
692 .properties(Tool.InputSchema.Properties.builder()
693 .putAdditionalProperty("subtasks", JsonValue.from(Map.of(
694 "type", "array",
695 "items", Map.of("type", "string"),
696 "description", "Independent subtask prompts to run as parallel agents")))
697 .build())
698 .putAdditionalProperty("required", JsonValue.from(List.of("subtasks")))
699 .build())
700 .build();
699701
700702 static final ToolBash20250124 BASH_TOOL = ToolBash20250124.builder().build();
701703
702704 static final Tool REPORT_TOOL = Tool.builder()
703 .name("report_findings")
704 .description("""
705 Report the final findings for your subtask. Call this exactly once, when you are \
706 done investigating; it ends your task.""")
707 .inputSchema(Tool.InputSchema.builder()
708 .properties(Tool.InputSchema.Properties.builder()
709 .putAdditionalProperty("summary", JsonValue.from(Map.of(
710 "type", "string",
711 "description", "Two or three sentences of synthesis")))
712 .putAdditionalProperty("findings", JsonValue.from(Map.of(
713 "type", "array",
714 "items", Map.of(
715 "type", "object",
716 "properties", Map.of(
717 "claim", Map.of(
718 "type", "string",
719 "description", "The finding, one sentence"),
720 "evidence", Map.of(
721 "type", "string",
722 "description", "How it was verified (file, line, or command output)"),
723 "severity", Map.of(
724 "type", "string",
725 "enum", List.of("high", "medium", "low", "info"))),
726 "required", List.of("claim", "evidence", "severity")))))
727 .build())
728 .putAdditionalProperty("required", JsonValue.from(List.of("summary", "findings")))
729 .build())
730 .build();
705 .name("report_findings")
706 .description("""
707 Report the final findings for your subtask. Call this exactly once, when you are \
708 done investigating; it ends your task.""")
709 .inputSchema(Tool.InputSchema.builder()
710 .properties(Tool.InputSchema.Properties.builder()
711 .putAdditionalProperty("summary", JsonValue.from(Map.of(
712 "type", "string",
713 "description", "Two or three sentences of synthesis")))
714 .putAdditionalProperty("findings", JsonValue.from(Map.of(
715 "type", "array",
716 "items", Map.of(
717 "type", "object",
718 "properties", Map.of(
719 "claim", Map.of(
720 "type", "string",
721 "description", "The finding, one sentence"),
722 "evidence", Map.of(
723 "type", "string",
724 "description", "How it was verified (file, line, or command output)"),
725 "severity", Map.of(
726 "type", "string",
727 "enum", List.of("high", "medium", "low", "info"))),
728 "required", List.of("claim", "evidence", "severity")))))
729 .build())
730 .putAdditionalProperty("required", JsonValue.from(List.of("summary", "findings")))
731 .build())
732 .build();
731733 ```
732734
733735 ```php PHP
from line 1058
10561058 return (output, process.ExitCode != 0);
10571059 }
10581060
1059 // Execute one bash tool call requested by the model.
1061 // Run one bash tool call requested by the model.
10601062 async Task<(string Output, bool IsError)> HandleBashBlock(ToolUseBlock block)
10611063 {
10621064 if (block.Input.GetValueOrDefault("restart").ValueKind is JsonValueKind.True)
from line 1126
11241126 return fmt.Sprintf("(%s)\n%s", err, output), true
11251127 }
11261128
1127 // handleBashBlock executes one bash tool call requested by the model.
1129 // handleBashBlock runs one bash tool call requested by the model.
11281130 func handleBashBlock(ctx context.Context, block anthropic.ToolUseBlock) (string, bool) {
11291131 var input struct {
11301132 Command string `json:"command"`
from line 1159
11571159 try {
11581160 var dir = Files.createTempDirectory("orchestration-");
11591161 Files.writeString(dir.resolve("sample.py"), """
1160 def fib(n):
1161 return n if n < 2 else fib(n - 1) + fib(n - 2)
1162 def fib(n):
1163 return n if n < 2 else fib(n - 1) + fib(n - 2)
11621164
1163 print(fib(10))
1164 """);
1165 print(fib(10))
1166 """);
11651167 Runtime.getRuntime().addShutdownHook(new Thread(() -> {
11661168 // Best-effort cleanup; the OS tmp sweeper handles leftovers.
11671169 try (var paths = Files.walk(dir)) {
from line 1184
11821184 Process process;
11831185 try {
11841186 process = new ProcessBuilder("bash", "-c", command)
1185 .directory(WORK_DIR.toFile())
1186 .redirectErrorStream(true)
1187 .start();
1187 .directory(WORK_DIR.toFile())
1188 .redirectErrorStream(true)
1189 .start();
11881190 } catch (IOException error) {
11891191 return new ToolOutput("(" + error + ")", true);
11901192 }
1191 // Drain stdout on another thread so a filled pipe cannot stall the timeout wait below.
1193 // Drain stdout on another thread so a filled pipe cannot stall the timeout wait that follows.
11921194 CompletableFuture<String> outputReader = CompletableFuture.supplyAsync(() -> {
11931195 try (var stdout = process.getInputStream()) {
11941196 return new String(stdout.readAllBytes(), StandardCharsets.UTF_8);
from line 1208
12061208 output = "(no output)";
12071209 } else if (output.length() > TOOL_RESULT_MAX_CHARS) {
12081210 output = output.substring(0, TOOL_RESULT_MAX_CHARS)
1209 + "\n(truncated at " + TOOL_RESULT_MAX_CHARS + " chars)";
1211 + "\n(truncated at " + TOOL_RESULT_MAX_CHARS + " chars)";
12101212 }
12111213 int exitCode = process.exitValue();
12121214 return exitCode == 0
1213 ? new ToolOutput(output, false)
1214 : new ToolOutput("(exit code " + exitCode + ")\n" + output, true);
1215 ? new ToolOutput(output, false)
1216 : new ToolOutput("(exit code " + exitCode + ")\n" + output, true);
12151217 }
12161218
12171219 // A tool call's input fields, or an empty map if the model sent something other than an object.
from line 1221
12191221 return toolUse._input() instanceof JsonObject object ? object.values() : Map.of();
12201222 }
12211223
1222 // Execute one bash tool call requested by the model.
1224 // Run one bash tool call requested by the model.
12231225 ToolOutput handleBashBlock(ToolUseBlock toolUse) throws InterruptedException {
12241226 Map<String, JsonValue> input = toolInput(toolUse);
12251227 if (input.get("restart") instanceof JsonBoolean restart && restart.value()) {
from line 1291
12891291 return [$output, $exitCode !== 0];
12901292 }
12911293
1292 /** Execute one bash tool call requested by the model. */
1294 /** Run one bash tool call requested by the model. */
12931295 function handleBashBlock(ToolUseBlock $block): array
12941296 {
12951297 if (($block->input['restart'] ?? null) === true) {
from line 1339
13371339 stdin.close
13381340 reader = Thread.new { stdout_and_stderr.read.scrub }
13391341 # Enforce the time limit with a monotonic-clock deadline so a timed-out command is
1340 # stopped rather than left running in the background.
1342 # ended rather than left running in the background.
13411343 deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + BASH_TIMEOUT_SECONDS
13421344 until wait_thr.join(0.1)
13431345 next if Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline
from line 1373
13711373 end
13721374 end
13731375
1374 # Execute one bash tool call requested by the model.
1376 # Run one bash tool call requested by the model.
13751377 def handle_bash_block(block)
13761378 input = parse_tool_input(block.input)
13771379 return ["Shell restarted.", false] if input["restart"] == true
from line 1707
17051707
17061708 ```java Java
17071709 static final String SUBAGENT_SYSTEM = """
1708 You are one agent in a larger parallel fan-out, assigned a single subtask. \
1709 Investigate it directly, using bash to check facts rather than guessing, and finish \
1710 by calling report_findings exactly once. Return findings, not narration.""";
1710 You are one agent in a larger parallel fan-out, assigned a single subtask. \
1711 Investigate it directly, using bash to check facts rather than guessing, and finish \
1712 by calling report_findings exactly once. Return findings, not narration.""";
17111713
17121714 // One subagent: a small nested agent loop with the bash tool plus report_findings.
17131715 // Subagents inherit the main loop's effort level.
from line 1718
17161718 messages.add(MessageParam.ofUser(prompt));
17171719 for (int turn = 0; turn < MAX_SUBAGENT_TURNS; turn++) {
17181720 MessageCreateParams params = MessageCreateParams.builder()
1719 .model(model)
1720 .maxTokens(64000L)
1721 .system(SUBAGENT_SYSTEM)
1722 .outputConfig(OutputConfig.builder().effort(EFFORT).build())
1723 .addTool(BASH_TOOL)
1724 .addTool(REPORT_TOOL)
1725 .messages(messages)
1726 .build();
1721 .model(model)
1722 .maxTokens(64000L)
1723 .system(SUBAGENT_SYSTEM)
1724 .outputConfig(OutputConfig.builder()
1725 .effort(EFFORT)
1726 .build())
1727 .addTool(BASH_TOOL)
1728 .addTool(REPORT_TOOL)
1729 .messages(messages)
1730 .build();
17271731 MessageAccumulator accumulator = MessageAccumulator.create();
17281732 try (var stream = client.messages().createStreaming(params, REQUEST_OPTIONS)) {
17291733 stream.stream().forEach(accumulator::accumulate);
from line 1740
17361740 }
17371741 if (!StopReason.TOOL_USE.equals(stopReason)) {
17381742 String text = response.content().stream()
1739 .flatMap(block -> block.text().stream())
1740 .map(TextBlock::text)
1741 .collect(Collectors.joining());
1743 .flatMap(block -> block.text().stream())
1744 .map(TextBlock::text)
1745 .collect(Collectors.joining());
17421746 if (StopReason.MAX_TOKENS.equals(stopReason)) {
17431747 text += "\n\n(warning: subagent response was truncated at max_tokens)";
17441748 }
from line 1749
17451749 return text;
17461750 }
17471751 List<ToolUseBlock> toolUses = response.content().stream()
1748 .flatMap(block -> block.toolUse().stream())
1749 .toList();
1752 .flatMap(block -> block.toolUse().stream())
1753 .toList();
17501754 List<ContentBlockParam> toolResults = new ArrayList<>();
17511755 String report = null;
17521756 for (ToolUseBlock toolUse : toolUses) {
from line 1763
17591763 default -> new ToolOutput("unknown tool: " + toolUse.name(), true);
17601764 };
17611765 toolResults.add(ContentBlockParam.ofToolResult(ToolResultBlockParam.builder()
1762 .toolUseId(toolUse.id())
1763 .content(result.output())
1764 .isError(result.isError())
1765 .build()));
1766 .toolUseId(toolUse.id())
1767 .content(result.output())
1768 .isError(result.isError())
1769 .build()));
17661770 }
17671771 if (report != null) {
17681772 return report;
from line 2132
21282132 Map<String, String> loadJournal() {
21292133 try {
21302134 return Objects.requireNonNullElseGet(
2131 JOURNAL_MAPPER.readValue(Files.readString(JOURNAL_PATH), new TypeReference<HashMap<String, String>>() {}),
2132 HashMap::new);
2135 JOURNAL_MAPPER.readValue(Files.readString(JOURNAL_PATH), new TypeReference<HashMap<String, String>>() {}),
2136 HashMap::new);
21332137 } catch (IOException _) {
21342138 return new HashMap<>();
21352139 }
from line 2615
26112615 List<String> normalizeSubtasks(JsonValue rawSubtasks) {
26122616 List<String> tasks = switch (rawSubtasks) {
26132617 case JsonArray array -> array.values().stream()
2614 .map(item -> item instanceof JsonString text ? text.value() : item.toString())
2615 .toList();
2618 .map(item -> item instanceof JsonString text ? text.value() : item.toString())
2619 .toList();
26162620 case JsonString string -> parseSubtaskString(string.value());
26172621 default -> List.of();
26182622 };
26192623 return tasks.stream()
2620 .filter(Objects::nonNull)
2621 .map(String::strip)
2622 .filter(task -> !task.isEmpty())
2623 .toList();
2624 .filter(Objects::nonNull)
2625 .map(String::strip)
2626 .filter(task -> !task.isEmpty())
2627 .toList();
26242628 }
26252629
26262630 List<String> parseSubtaskString(String encoded) {
from line 2638
26342638
26352639 String verifyPromptFor(String subtask, String result) {
26362640 return """
2637 Adversarially verify the subagent result below: try to REFUTE it. Re-derive the \
2638 claims yourself with bash rather than trusting the result, and look for evidence \
2639 that contradicts them. Default to refuted if uncertain. Call report_findings with \
2640 summary 'refuted: <why>' or 'confirmed: <why>', citing the file:line or command \
2641 output that decided it.
2641 Adversarially verify the subagent result below: try to REFUTE it. Re-derive the \
2642 claims yourself with bash rather than trusting the result, and look for evidence \
2643 that contradicts them. Default to refuted if uncertain. Call report_findings with \
2644 summary 'refuted: <why>' or 'confirmed: <why>', citing the file:line or command \
2645 output that decided it.
26422646
2643 Subtask: %s
2647 Subtask: %s
26442648
2645 Result to verify:
2646 %s""".formatted(subtask, result);
2649 Result to verify:
2650 %s""".formatted(subtask, result);
26472651 }
26482652
26492653 // invokeAll waits for every job, so each future is finished when it is read here.
26502654 List<String> runAll(ExecutorService pool, List<String> prompts, Model model) throws InterruptedException {
26512655 List<Callable<String>> jobs = prompts.stream()
2652 .<Callable<String>>map(prompt -> () -> journaled(prompt, () -> runSubagent(model, prompt)))
2653 .toList();
2656 .<Callable<String>>map(prompt -> () -> journaled(prompt, () -> runSubagent(model, prompt)))
2657 .toList();
26542658 return pool.invokeAll(jobs).stream()
2655 .map(future -> switch (future.state()) {
2656 case SUCCESS -> future.resultNow();
2657 // Isolation boundary: one bad subagent should not end the run.
2658 case FAILED -> "(subagent failed: " + future.exceptionNow() + ")";
2659 case CANCELLED, RUNNING -> "(subagent failed: cancelled)";
2660 })
2661 .toList();
2659 .map(future -> switch (future.state()) {
2660 case SUCCESS -> future.resultNow();
2661 // Isolation boundary: one bad subagent should not end the run.
2662 case FAILED -> "(subagent failed: " + future.exceptionNow() + ")";
2663 case CANCELLED, RUNNING -> "(subagent failed: cancelled)";
2664 })
2665 .toList();
26622666 }
26632667
26642668 // Run subtasks as parallel subagents, then run a second verification wave over
from line 2683
26792683 results = runAll(pool, subtasks, model);
26802684 System.err.println("[workflow] verifying " + results.size() + " results");
26812685 List<String> verifyPrompts = IntStream.range(0, subtasks.size())
2682 .mapToObj(index -> verifyPromptFor(subtasks.get(index), results.get(index)))
2683 .toList();
2686 .mapToObj(index -> verifyPromptFor(subtasks.get(index), results.get(index)))
2687 .toList();
26842688 verdicts = runAll(pool, verifyPrompts, model);
26852689 }
26862690 String joined = IntStream.range(0, subtasks.size())
2687 .mapToObj(index -> """
2688 [agent %d: %s]
2689 %s
2691 .mapToObj(index -> """
2692 [agent %d: %s]
2693 %s
26902694
2691 [verify %d]
2692 %s""".formatted(index + 1, subtasks.get(index), results.get(index), index + 1, verdicts.get(index)))
2693 .collect(Collectors.joining("\n\n"));
2695 [verify %d]
2696 %s""".formatted(index + 1, subtasks.get(index), results.get(index), index + 1, verdicts.get(index)))
2697 .collect(Collectors.joining("\n\n"));
26942698 if (dropped > 0) {
26952699 joined = """
2696 (note: %d subtasks beyond MAX_TOTAL_SUBTASKS=%d were not run; rerun them in a follow-up Workflow call)
2700 (note: %d subtasks beyond MAX_TOTAL_SUBTASKS=%d were not run; rerun them in a follow-up Workflow call)
26972701
2698 %s""".formatted(dropped, MAX_TOTAL_SUBTASKS, joined);
2702 %s""".formatted(dropped, MAX_TOTAL_SUBTASKS, joined);
26992703 }
27002704 return new ToolOutput(joined, false);
27012705 }
from line 3235
32313235 return due;
32323236 }
32333237
3234 // Send one user turn through the loop, executing tool calls until the model stops.
3238 // Send one user turn through the loop, running tool calls until the model stops.
32353239 async Task<string> Turn(string userInput)
32363240 {
32373241 // Mid-conversation system messages follow the user turn they apply to, which keeps
from line 3357
33533357 return due
33543358 }
33553359
3356 // turn sends one user turn through the loop, executing tool calls until the model stops.
3360 // turn sends one user turn through the loop, running tool calls until the model stops.
33573361 func (agent *modeAgent) turn(ctx context.Context, userInput string) (string, error) {
33583362 // Mid-conversation system messages follow the user turn they apply to, which keeps
33593363 // the cached prefix ahead of them untouched.
from line 3477
34733477 return MessageParam.ofSystem(content);
34743478 }
34753479
3476 // Send one user turn through the loop, executing tool calls until the model stops.
3480 // Send one user turn through the loop, running tool calls until the model stops.
34773481 String turn(String userInput) throws InterruptedException {
34783482 // Mid-conversation system messages follow the user turn they apply to, which keeps
34793483 // the cached prefix ahead of them untouched.
from line 3487
34833487
34843488 for (int turn = 0; turn < MAX_MAIN_TURNS; turn++) {
34853489 MessageCreateParams params = MessageCreateParams.builder()
3486 .model(model)
3487 .maxTokens(64000L)
3488 .system(SYSTEM_PROMPT) // static for the whole session
3489 .outputConfig(OutputConfig.builder().effort(EFFORT).build())
3490 .addTool(WORKFLOW_TOOL)
3491 .addTool(BASH_TOOL)
3492 .messages(messages)
3493 .build();
3490 .model(model)
3491 .maxTokens(64000L)
3492 .system(SYSTEM_PROMPT) // static for the whole session
3493 .outputConfig(OutputConfig.builder()
3494 .effort(EFFORT)
3495 .build())
3496 .addTool(WORKFLOW_TOOL)
3497 .addTool(BASH_TOOL)
3498 .messages(messages)
3499 .build();
34943500 MessageAccumulator accumulator = MessageAccumulator.create();
34953501 try (var stream = client.messages().createStreaming(params, REQUEST_OPTIONS)) {
34963502 stream.stream().forEach(accumulator::accumulate);
from line 3510
35043510 }
35053511 if (!StopReason.TOOL_USE.equals(stopReason)) {
35063512 String text = response.content().stream()
3507 .flatMap(block -> block.text().stream())
3508 .map(TextBlock::text)
3509 .collect(Collectors.joining());
3513 .flatMap(block -> block.text().stream())
3514 .map(TextBlock::text)
3515 .collect(Collectors.joining());
35103516 if (StopReason.MAX_TOKENS.equals(stopReason)) {
35113517 // Drop the truncated assistant message so later turns do not build on it.
35123518 messages.removeLast();
from line 3522
35163522 }
35173523
35183524 List<ToolUseBlock> toolUses = response.content().stream()
3519 .flatMap(block -> block.toolUse().stream())
3520 .toList();
3525 .flatMap(block -> block.toolUse().stream())
3526 .toList();
35213527 List<ContentBlockParam> toolResults = new ArrayList<>();
35223528 for (ToolUseBlock toolUse : toolUses) {
35233529 ToolOutput result = switch (toolUse.name()) {
35243530 case "Workflow" -> runWorkflow(model,
3525 toolInput(toolUse).getOrDefault("subtasks", JsonValue.from(List.of())));
3531 toolInput(toolUse).getOrDefault("subtasks", JsonValue.from(List.of())));
35263532 case "bash" -> handleBashBlock(toolUse);
35273533 default -> new ToolOutput("unknown tool: " + toolUse.name(), true);
35283534 };
35293535 toolResults.add(ContentBlockParam.ofToolResult(ToolResultBlockParam.builder()
3530 .toolUseId(toolUse.id())
3531 .content(result.output())
3532 .isError(result.isError())
3533 .build()));
3536 .toolUseId(toolUse.id())
3537 .content(result.output())
3538 .isError(result.isError())
3539 .build()));
35343540 }
35353541 messages.add(MessageParam.ofUserOfContentBlockParams(toolResults));
35363542 }
from line 3853
38473853 ```java Java
38483854 void main(String[] args) throws InterruptedException {
38493855 String task = args.length > 0 ? args[0] : """
3850 Explore the current directory, then give a thorough review: what it does, \
3851 code-quality issues, and concrete improvements.""";
3856 Explore the current directory, then give a thorough review: what it does, \
3857 code-quality issues, and concrete improvements.""";
38523858 ModeAgent agent = new ModeAgent(MODEL);
38533859 IO.println(agent.turn(task));
38543860 agent.setMode(false);
No line in this hunk matches that.