Craft Anything: understand how any software works, and craft your own.
Rust
Handle fenced calls with trailing protocol text (#1031)
Tomáš Doubekbccb9e1326d0
diff --git a/crates/ai/src/openai.rs b/crates/ai/src/openai.rsindex 875f0f78..26f65a83 100644--- a/crates/ai/src/openai.rs+++ b/crates/ai/src/openai.rs@@ -543,12 +543,14 @@ fn json_action(text: &str) -> Option<ReactStep> {/// Every fence must be a complete `json` (or unlabelled) call, and nothing but blank lines may/// follow the last one; anything else (other code, a `~~~` fence, a fence inside a fence, an/// unclosed fence, words after the call, a JSON object quoted inline) means the reply is text,-/// as before. So do the text protocol's own markers in the words (a final answer that ends in an-/// example is still the answer); inside a call's arguments they're only content.+/// as before. Protocol markers before the first call keep the reply as text; after a call they+/// require a retry even if another fence follows (it could be an example after a final answer).+/// Inside a call's arguments they're only content.fn parse_fenced_calls(text: &str) -> Option<(Vec<(String, Value)>, bool)> {let mut calls = Vec::new();let mut lines = text.lines();let mut words_after = false;+ let mut protocol_after = false;while let Some(line) = lines.next() {let opening = line.trim();// Anything in a tilde fence is an example, whatever it holds.@@ -558,7 +560,11 @@ fn parse_fenced_calls(text: &str) -> Option<(Vec<(String, Value)>, bool)> {let length = opening.bytes().take_while(|byte| *byte == b'`').count();if length < 3 {if ["Final Answer:", "Action:"].into_iter().any(|marker| line.contains(marker)) {- return None;+ if calls.is_empty() {+ return None;+ }+ // A later fence may be an example after a final answer, not another call.+ protocol_after = true;}words_after |= !opening.is_empty() && !calls.is_empty();continue;@@ -585,9 +591,10 @@ fn parse_fenced_calls(text: &str) -> Option<(Vec<(String, Value)>, bool)> {calls.push((tool, input));words_after = false;}- (!calls.is_empty()).then_some((calls, words_after))+ (!calls.is_empty()).then_some((calls, words_after || protocol_after))}+/// Returns fenced calls only when no nonblank text follows the final call.fn fenced_calls(text: &str) -> Option<Vec<(String, Value)>> {let (calls, words_after) = parse_fenced_calls(text)?;(!words_after).then_some(calls)@@ -704,10 +711,12 @@ mod tests {model: String::new(),follow_up: None,};- let mut r = turn(&several);- react_postprocess(&mut r, &[tool("look"), tool("write")], false);- assert_eq!(r.stop, StopReason::ToolUse);- assert_eq!(r.message.tool_uses().into_iter().map(|(_, name, _)| name.to_string()).collect::<Vec<_>>(), ["look", "write"]);+ for react in [false, true] {+ let mut r = turn(&several);+ react_postprocess(&mut r, &[tool("look"), tool("write")], react);+ assert_eq!(r.stop, StopReason::ToolUse, "react={react}");+ assert_eq!(r.message.tool_uses().into_iter().map(|(_, name, _)| name.to_string()).collect::<Vec<_>>(), ["look", "write"]);+ }let mut r = turn(&several);react_postprocess(&mut r, &[tool("look")], false);assert!(r.message.tool_uses().is_empty() && r.stop == StopReason::EndTurn, "one isn't offered: none run");@@ -723,17 +732,40 @@ mod tests {react_postprocess(&mut r, &[tool("look")], react);assert!(r.message.tool_uses().is_empty() && r.stop == StopReason::EndTurn, "react={react}");}- let summary = format!("{}\n### Summary:\nI listed the files.", call("look"));- let mut r = turn(&summary);- react_postprocess(&mut r, &[tool("look")], false);- assert!(r.message.tool_uses().is_empty());- assert_eq!(r.stop, StopReason::PauseTurn);- assert_eq!(- r.follow_up.as_deref(),- Some(- "The fenced tool call in your previous response was not run because text followed the closing fence. Send the tool call again without adding a summary or other text after it."- )- );+ for trailing in ["### Summary:\nI listed the files.", "Action: look\nAction Input: {}", "Final Answer: I listed the files."] {+ let text = format!("{}\n{}", call("look"), trailing);+ for react in [false, true] {+ let mut r = turn(&text);+ react_postprocess(&mut r, &[tool("look")], react);+ assert!(r.message.tool_uses().is_empty(), "react={react}, trailing={trailing}");+ assert_eq!(r.stop, StopReason::PauseTurn, "react={react}, trailing={trailing}");+ assert_eq!(+ r.follow_up.as_deref(),+ Some(+ "The fenced tool call in your previous response was not run because text followed the closing fence. Send the tool call again without adding a summary or other text after it."+ ),+ "react={react}, trailing={trailing}"+ );+ }+ }+ // Protocol text between calls must not be cleared by another fence (PR #1031).+ for marker in ["Action: look\nAction Input: {}", "Final Answer: Here's an example:"] {+ let text = format!("{}\n{marker}\n{}\nThen:\n{}", call("look"), call("write"), call("look"));+ assert!(fenced_calls(&text).is_none(), "{marker}");+ for react in [false, true] {+ let mut r = turn(&text);+ react_postprocess(&mut r, &[tool("look"), tool("write")], react);+ assert!(r.message.tool_uses().is_empty(), "react={react}, marker={marker}");+ assert_eq!(r.stop, StopReason::PauseTurn, "react={react}, marker={marker}");+ assert_eq!(+ r.follow_up.as_deref(),+ Some(+ "The fenced tool call in your previous response was not run because text followed the closing fence. Send the tool call again without adding a summary or other text after it."+ ),+ "react={react}, marker={marker}"+ );+ }+ }}/// Only the real OpenCode Go base gets its session header: not a look-alike host, path or scheme.diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex c9e7e95d..880ee876 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -340,6 +340,9 @@ been run live.#417's case both turns put "### Summary:" after their one `json` fence, nothing ran, and thebuild stopped after two turns with no files. The next message now says that it wasn't run— PR #1028, branch bugfix/r5.4-fenced-call-summary+- [x] Keep the retry condition when `Action:` or `Final Answer:` appears between fenced+ calls, without rejecting ordinary words between calls (PR #1031 review)+ — claimed: Codex, branch bugfix/r5.4-fenced-call-followup- [ ] A local builder spends its rounds on the project file and never writes the app: run 4 had acompiling `Cargo.toml` by check 3, its last, with `main.rs` still "Hello, world!". See whethermore rounds get there, or whether a small model needs the window and the `--screenshot`diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 3228a3c4..e78d3e3f 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -82,7 +82,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| Electron window comparisons | `app_graphs_compare` retains every unassigned window and every construction with a reused local binding. Windows are paired by module, binding and occurrence, so inserting comments does not hide preference changes. Colliding display labels receive a separate `#N` suffix without changing literal binding names or occurrence indices | Synthetic applications parsed through the ordinary analyzer exercise anonymous and reused bindings, shifted source lines, unequal counts, literal names resembling occurrence or collision suffixes, and stable labels when only one window changes. Pairing remains positional within each binding group; reordered constructions and real application releases were not checked for this correction || Rebuild workflow (Study → Build → Check → Refine) | `crates/ai/src/rebuild/` (kinds, checks and stacks are pluggable: docs/extending.md). Three kinds: website, app, game (a project whose stack is a game engine is always a game). The request decides how to build: a language, framework, engine or platform it names wins over the kind's default stack (Rust + egui for apps, Unity for games, the original's for websites), and the build check, the recorded stack and Play follow what was built (an Electron app opens in its own Electron; a plain static site has nothing to build and passes the build check as it is). Websites: Study also captures up to 4 other pages of the site; menus are opened on a computer and on a phone; the check serves the build on loopback and compares every page at 1440, 768 and 390 px (likeness = mean of layout and perceptual detail, SSIM, averaged over pages, leaving out the parts of the original that change by themselves, found by photographing it three times; the note adds text, page structure, the colours, font, text sizes and spacing the build misses, and per width a page that scrolls sideways, heading sizes and sections whose padding, items per row or content column differ, the errors, failed requests and accessibility gaps the build adds, and the opened menus and pop-ups). A stack or library named in the request (Next.js, shadcn/ui, Tailwind CSS…, `stacks.toml`) is what the builder uses; with none named, a website's stack is the builder's choice (told to match what the original is built with) and the stack it used is recorded from app/package.json. The builder leads: it studies, asks the tools follow-up questions, records what it can't find out as unknowns (`core_unknown_add`; the run reports the open ones), and tests its own build mid-turn with `rebuild_check` (the same checks, for every kind); a check with anything it couldn't compare, or any claim that fails (a website page that scrolls sideways, logs new errors, fails to load a file, lacks a landmark, or a menu that doesn't open; for games each self-test step, for Deep-mode sheets each original number in the code, for console apps the same exit and output as the original's runs), isn't good enough; apps and games by whether they build. Up to 6 refinement rounds, or until a website reaches 90% likeness. A turn cut off by a time limit, crash or dropped connection resumes (up to 3 times); builder turns may run 24 h. A project copied from another computer (or moved to another folder) keeps building with Claude Code: the project keeps a copy of the builder's session (`agent-session.jsonl`) after every turn and puts it back where Claude Code finds it on a computer without it, so the same conversation carries on (#451); when the session still isn't there, a new one starts from the brief, what's in app/ and the kept requests and replies (or the last summary), and questions about the build put the kept session back too, else are answered from the files and forget the missing session (#452). Live runs with Claude Code 2.1.316 on one Mac (2026-11-02), a second computer stood in for by a separate signed-in `CLAUDE_CONFIG_DIR`: a copied project's session was put back and resumed (the builder recalled its first reply from memory); a kept copy of another session was refused and the new session used the handoff; a real project synced from Windows whose session was missing started afresh and reached Ready. Not yet run between two real computers | Unit tests for prompts, stack choice, site detection, feed folding; live runs reached Build and decompiling (below) || Context-summary usage | Successful API context summaries contribute to the message totals consumed by build usage and receive a `model_turn` journal entry with `purpose: context_summary`. Input tokens include cached ones, as coding agents report them (Ollama 0.40 sends them apart). Cached-token pricing is retained; an unknown summary price makes the total unknown, and a failed call adds no invented usage | Scripted-model tests exercise the real `ApiConversation`, transcript resumption, exact input/output and cache-price totals, journal entries, empty summaries, local zero cost, unknown prices and failed summaries. No live provider or end-to-end rebuild was used for this correction |-| Local model builds | Not yet: Ollama 0.40.7 with `qwen2.5-coder:14b` (32k context) writes its calls as JSON text, which run whole or after a sentence; a fenced call followed by a summary is not run and the next model message says to retry it without trailing text; by check 3 its project compiles, but `main.rs` is still cargo's "Hello, world!", so the screenshot check fails it at the round limit (R5.4). A lean local builder's prompt asks for no memory tools it isn't offered, and a project one folder down is named in the check | Four live CLI builds of "a scientific calculator" on Windows (RTX 5090), 2026-11-04, one fix added per run |+| Local model builds | Regression coverage confirms that a fenced call followed by a summary or protocol marker is not run and the next model message says to retry it without trailing text (R5.4). Protocol markers between calls retain this retry condition even when later calls follow; ordinary words between calls remain supported in both ReAct modes. No live local-model build has been run after this change. Earlier, Ollama 0.40.7 with `qwen2.5-coder:14b` (32k context) wrote calls as JSON text, which ran whole or after a sentence; by check 3 its project compiled, but `main.rs` was still cargo's "Hello, world!", so the screenshot check failed at the round limit. A lean local builder's prompt asks for no memory tools it isn't offered, and a project one folder down is named in the check | Historical live evidence: four CLI builds of "a scientific calculator" on Windows (RTX 5090), 2026-11-04, one fix added per run || Backend context budgets | `context_tokens` in `[[ai.backends]]` controls when an API conversation is trimmed and summarised. Zero or omission retains local/cloud defaults; a nonzero conversation override takes priority. Before each attempt, including a fallback, fitting adds estimated history growth since the last successful request to its reported input size. Trimming resets that reference, and successful requests refresh it; summary usage remains in message totals | Regressions cover settings and model construction, defaults/overrides, smaller fallback budgets, large-budget arithmetic and new tool output growing beyond a fallback budget even when the history estimate alone is below the reported input. The latest tool results are preserved, and a short follow-up does not count already-sent history twice. This does not set server context parameters or guarantee that a complete request fits; no live provider was used || Games | Engine detection for 12 engines (Unreal, Unity, Godot, Source, GameMaker, RPG Maker, Ren'Py, MonoGame, LÖVE, CryEngine, Cocos, Cube) with versions. Unreal and Godot games are rebuilt in the same engine, others in Unity; installed engines are found, Godot installs itself, others get guided installs. Picking an inner folder (Engine, Binaries, Paks…) finds the game's folder. Just look inside a game shows what it's made of (`core_target_triage` on its folder: engine and version, how its code ships, the libraries its Unity assembly names give away, its own code, scenes and size) and opens it in the chat to ask about it. The builder keeps `app/MECHANICS.md` and its structured twin `app/mechanics.json` (checked after each build), in Deep mode only, may reuse the original's readable files for private use (never decrypting; generated pictures and 3D models replace its art when the person turns them on; Clean room copies none of its files), lists them in `CREDITS.md` (checked, with the private-use line in `README.md`); a game is ready only when its `--self-test` shows the player moving, acting and the HUD drawn, and the result can be started from the project page | Unit tests; live runs on Windows || Clean room and Deep mode | Clean room (the default) runs only the tools in `engine/src/clean_room.rs`: ones that touch no target or watch from outside (the website as a visitor sees it, pictures of a window, its controls, recorded runs, a phone's screen). Every other tool, a plugin's included, is refused in the app, CLI, MCP and agents, with a way to turn on Deep mode. A Clean room build studies an app or a game only from the person's pictures and words (and a picture of its window when runtime study is on); its builder's reads and commands go through an approval rule that keeps it out of the original's folder and site (with Claude Code, and with ACP agents for what they ask about; other agents aren't held to it, see roadmap R2.2). Deep mode (`deep_mode` in Settings, `--deep` for one CLI run) uses every tool: the builder sees them all, and a website's study also reads its JavaScript and watches its start page for ten seconds (capture/how-it-works.md). Ghidra adds its decompiler in Deep mode when it's installed: it is found, or installed after asking. Study starts one analysis of the main program, saved and shared with the builder's tool server through a lock file (up to 8 h, Java gets half the machine's memory or the amount set in Settings → Engines, 4 to 31 GB, four slow passes skipped). The builder must decompile before the build is checked; addresses the built-in analysis can't place go to Ghidra, which makes a function on demand (for this run only) where its analysis has none, e.g. code reached only through tables of pointers. Without Ghidra, Deep mode uses the built-in engines | Live runs with Ghidra 12.1.4 on Windows (a shared analysis, and a decompile in seconds on a large program). Live runs with Ghidra 12.2 on Linux x86-64 (decompiles by name in position-independent programs and shared libraries, whose addresses Ghidra moves). The guided install of Ghidra and its Java is offered on Linux and macOS too, but has only been tried on Windows. Clean room and Deep mode: engine, AI, MCP, CLI and app tests; no live Clean room build run yet |