fix: a string argument that quotes a tool call is no longer cut at the quoted text

tool_output::find_parameter_end ended a value at the first </parameter> followed by <parameter= or </function>, so a write
whose content quoted a whole call (a file that documents the format, a heredoc, a test) was published with content cut at the
quote and the rest as plain text, whole and streamed, without any error (upstream #4078, fixed there in 77794e34 and b72f56e0).
It now follows upstream's quote rule: a close inside a call the value itself quotes (more quoted <function=NAME> openers
followed by <parameter= or </function> than </function> closers before it) is part of the value. One forward pass over the
value. Incremental also stops re-trying candidate call ends it has already rejected.

A call whose value quotes an opener and never closes it is now unterminated (an error) instead of being cut at the first
plausible close, so a long write that quotes a call and is itself cut by the token limit is not published truncated.

Deliberately not taken from upstream: a value that reopens its own parameter (</parameter><parameter=content> inside content).
Upstream reads it as text; here it is byte for byte a parameter written twice, which desktop-core's
native_tools_sdet::unknown_incomplete_duplicate_or_late_invalid_call_refuses_entire_output requires to be refused, and merging
the two into one argument would hide a malformed call. It stays an error (duplicate tool parameter), listed as known failure.

Regression tests: specimens 4078-nested-call and 4078-heredoc and the quoted-value shapes "quoted call", "quoted call at the
end" and "heredoc" of the ported corpus failed on the previous commit and pass here (13 of 41 specimens, 5 of 6 shapes), plus a
unit test for the cut outer call. The 8 existing tool_output tests and the 14 native_tools_sdet tests pass unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-30 03:45:24 +01:00
co-authored by Claude Sonnet 5.5
parent c5c60ac66a
commit 9b07fdd995
3 changed files with 183 additions and 64 deletions
+114 -4
View File
@@ -14,6 +14,9 @@ pub struct Incremental<'a> {
buffer: String,
in_call: bool,
after_call: bool,
/// Candidate call ends (`</tool_call>`) before this offset of the buffer were tried and are not the end of the call; the
/// text before a candidate does not change when more arrives, so they are not tried again.
tried: usize,
}
impl<'a> Incremental<'a> {
@@ -23,6 +26,7 @@ impl<'a> Incremental<'a> {
buffer: String::new(),
in_call: false,
after_call: false,
tried: 0,
}
}
@@ -40,7 +44,7 @@ impl<'a> Incremental<'a> {
if self.buffer.len() > 16 * 1024 * 1024 {
return Err("tool call exceeds the 16 MiB streaming buffer".into());
}
let mut search = 0;
let mut search = self.tried;
let mut completed = None;
while let Some(relative) = self.buffer[search..].find("</tool_call>") {
let end = search + relative + "</tool_call>".len();
@@ -55,10 +59,12 @@ impl<'a> Incremental<'a> {
search = end;
}
let Some((end, call)) = completed else {
self.tried = search;
break;
};
out.push(call);
self.buffer.drain(..end);
self.tried = 0;
self.in_call = false;
self.after_call = true;
} else if let Some(start) = self.buffer.find("<tool_call>") {
@@ -67,6 +73,7 @@ impl<'a> Incremental<'a> {
out.push(Segment::Text(prefix.to_owned()));
}
self.buffer.drain(..start + "<tool_call>".len());
self.tried = 0;
self.in_call = true;
} else {
let mut safe = self.buffer.len() - held_tag_prefix(&self.buffer, "<tool_call>");
@@ -260,19 +267,96 @@ fn parameter_value(raw: &str, declared: Option<&Value>) -> Value {
parsed
}
/// Where a parameter value in `text` (which starts at the value) ends: the first `</parameter>` that is followed, after
/// whitespace, by the next `<parameter=` or by `</function>`. The same text inside a value (a file that documents the call
/// format) is part of the value, and so is a close that belongs to a call the value itself quotes (upstream #4078): a
/// `</parameter>` counts only when the quoted openers (`<function=NAME>` followed by `<parameter=` or `</function>`) before it
/// are no more than the `</function>` closers before it. A value that reopens its own parameter (`</parameter><parameter=NAME>`
/// of the same name) still ends at the first close: that text is indistinguishable from a parameter written twice, which is
/// refused (`duplicate tool parameter`) rather than merged into one argument.
fn find_parameter_end(text: &str) -> Option<usize> {
let mut balance = QuoteBalance::new(text);
let mut search = 0;
while let Some(relative) = text[search..].find("</parameter>") {
let at = search + relative;
let after = text[at + "</parameter>".len()..].trim_start();
if after.starts_with("<parameter=") || after.starts_with("</function>") {
return Some(at);
if balance.opened_before(at) <= balance.closed_before(at) {
let after = text[at + "</parameter>".len()..].trim_start();
if after.starts_with("<parameter=") || after.starts_with("</function>") {
return Some(at);
}
}
search = at + 1;
}
None
}
/// Counts, for increasing positions, the calls a value quotes: openers `<function=NAME>` that are followed by `<parameter=` or
/// `</function>` (a bare `<function=` in prose or code is not one), and the `</function>` closers. Both cursors only move
/// forward, so walking every `</parameter>` candidate of a value costs one pass over it.
struct QuoteBalance<'a> {
text: &'a str,
opener_at: usize,
openers: usize,
closer_at: usize,
closers: usize,
}
impl<'a> QuoteBalance<'a> {
fn new(text: &'a str) -> Self {
Self { text, opener_at: 0, openers: 0, closer_at: 0, closers: 0 }
}
/// The end of a quoted opener that starts at `start` (`<function=`), or `None` when it is not one.
fn opener_end(&self, start: usize) -> Option<usize> {
let rest = &self.text[start + "<function=".len()..];
let name = rest.find(|c: char| c == '<' || c == '>' || c.is_whitespace())?;
if name == 0 || !rest[name..].starts_with('>') {
return None;
}
let after = &rest[name + 1..];
let follower = after.trim_start();
let skipped = after.len() - follower.len();
let token = if follower.starts_with("<parameter=") {
"<parameter=".len()
} else if follower.starts_with("</function>") {
"</function>".len()
} else {
return None;
};
Some(start + "<function=".len() + name + 1 + skipped + token)
}
/// Quoted openers that end at or before `at`.
fn opened_before(&mut self, at: usize) -> usize {
while let Some(relative) = self.text[self.opener_at..].find("<function=") {
let start = self.opener_at + relative;
match self.opener_end(start) {
Some(end) if end <= at => {
self.openers += 1;
self.opener_at = end;
}
Some(_) => break,
None if start + "<function=".len() > at => break,
None => self.opener_at = start + 1,
}
}
self.openers
}
/// `</function>` closers that end at or before `at`.
fn closed_before(&mut self, at: usize) -> usize {
while let Some(relative) = self.text[self.closer_at..].find("</function>") {
let end = self.closer_at + relative + "</function>".len();
if end > at {
break;
}
self.closers += 1;
self.closer_at = end;
}
self.closers
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -447,4 +531,30 @@ mod tests {
.unwrap();
assert!(cut.finish().is_err());
}
#[test]
fn a_quoted_call_in_a_value_does_not_end_the_value_and_a_cut_outer_call_is_not_published() {
let tools = [json!({"name":"write","parameters":{"properties":{"path":{"type":"string"},"content":{"type":"string"}}}})];
let quoted =
"<tool_call>\n<function=write>\n<parameter=path>\nx.txt\n</parameter>\n</function>\n</tool_call>";
let content = format!("transcript:\n{quoted}\nafter");
let call = |tail: &str| {
format!("<tool_call>\n<function=write>\n<parameter=path>\np.txt\n</parameter>\n<parameter=content>\n{content}{tail}")
};
let whole = call("\n</parameter>\n</function>\n</tool_call>");
assert_eq!(
parse_complete(&whole, &tools).unwrap(),
vec![Segment::Call { name: "write".into(), arguments: json!({"path":"p.txt","content":content}) }]
);
// the outer call was cut (token limit) right after the quoted one: the quoted call's closers must not end the value,
// or a truncated write would be published as a whole call
let cut = format!("<tool_call>\n<function=write>\n<parameter=path>\np.txt\n</parameter>\n<parameter=content>\ntranscript:\n{quoted}");
assert!(parse_complete(&cut, &tools).is_err());
let mut parser = Incremental::new(&tools);
assert_eq!(parser.feed(&cut).unwrap(), vec![]);
assert!(parser.finish().is_err());
// a parameter written twice stays refused, not merged into one argument
let twice = "<tool_call><function=write><parameter=content>a\n</parameter>\n<parameter=content>\nb</parameter></function></tool_call>";
assert!(parse_complete(twice, &tools).unwrap_err().contains("duplicate tool parameter: content"));
}
}
+2 -9
View File
@@ -187,11 +187,9 @@ const KNOWN_FAILURES: &[&str] = &[
"4427-todos-stray-items",
"4427-todos-single-quotes",
"4427-todos-trailing-comma-and-open-bracket",
"4078-reopened-parameter",
"4427-todos-json-string-of-an-array",
"4427-one-line-in-thinking",
"4078-nested-call",
"4078-reopened-parameter",
"4078-heredoc",
"4077-stray-think-line",
"4077-stray-think-in-a-fence",
"4077-stray-think-after-a-backtick",
@@ -365,12 +363,7 @@ fn quoted_value_failures() -> Vec<(&'static str, String)> {
}
/// Value shapes that are not yet read exactly (strict both ways, like `KNOWN_FAILURES`).
const KNOWN_QUOTED_FAILURES: &[&str] = &[
"quoted call",
"quoted call at the end",
"heredoc",
"repeated parameter",
];
const KNOWN_QUOTED_FAILURES: &[&str] = &["repeated parameter"];
#[test]
fn quoted_call_values_stay_exact() {
+67 -51
View File
@@ -29,64 +29,80 @@ Origin of the question: upstream issue #4078 (a string argument that quotes a to
| stage | specimens read as upstream expects (of 41) |
| --- | --- |
| main (before) | 11 |
| after 2 | 13 |
## Specimens
`ok`: the calls, the answer text and the reasoning text are what upstream expects, whole and in every streamed cut. A reason is the first difference found at the final stage shown. `recover` marks specimens upstream reads only with `tool_call_recovery` on.
| specimen | what it is | recover | main (before) | first difference at the last stage |
| --- | --- | --- | --- | --- |
| `4427-todos-valid` | #4427 first example (the Harness todo_write call) | | ok | |
| `4427-todos-stray-items` | #4427 second example: `"status": "pending", "in_progress", "pending": false` | | FAIL | whole: calls: got todo_write want todo_write |
| `4427-todos-single-quotes` | #4427 shape: Python quotes | | FAIL | whole: calls: got todo_write want todo_write |
| `4427-todos-trailing-comma-and-open-bracket` | #4427 shape: a cut array | | FAIL | whole: calls: got todo_write want todo_write |
| `4427-todos-json-string-of-an-array` | #4427 shape: the array written as a JSON string | | FAIL | whole: calls: got todo_write want todo_write |
| `4427-todos-not-json-stays-text` | #4427: text that is no array stays the text it is | | ok | |
| `4427-one-line` | #4427: the tags on one line | | ok | |
| `4427-one-line-in-thinking` | #4427: written inside the thinking, the turn ends on it | | FAIL | whole: error: reasoning ended without </think> |
| `4078-nested-call` | #4078: a value holding a whole call | | FAIL | whole: calls: got write_file want write_file |
| `4078-reopened-parameter` | #4078: a value that reopens its own parameter | | FAIL | whole: error: duplicate tool parameter: content |
| `4078-heredoc` | #4078: a heredoc that prints a quoted call | | FAIL | whole: calls: got bash want bash |
| `4078-call-format-in-a-file` | #210: a file that documents the format | | ok | |
| `4077-stray-think-line` | #4077: the model quoted the closing tag at a line start | | FAIL | whole: content differs |
| `4077-stray-think-in-a-fence` | #4077: the quote sat in a code fence, so the fence closes in the 'answer' | | FAIL | whole: content differs |
| `4077-stray-think-after-a-backtick` | #4077: an open backtick | | FAIL | whole: content differs |
| `4077-quoted-think-stays-reasoning` | #537: a closing tag after a backtick is still reasoning (control) | | FAIL | whole: content differs |
| `4077-closer-in-the-answer-text-is-kept-mid-line` | a closing tag inside a sentence of the answer is text (control) | | ok | |
| `4077-no-second-closer-is-the-normal-case` | control | | ok | |
| `qwen-one-call` | the template's own form | | ok | |
| `qwen-int-argument` | a declared integer | | ok | |
| `qwen-after-thinking` | the normal agent turn | | ok | |
| `qwen-call-in-the-thinking` | #804: the turn ends inside the thinking, on the call | | FAIL | whole: error: reasoning ended without </think> |
| `qwen-three-calls` | parallel calls, one wrapper each | | ok | |
| `qwen-calls-with-prose-between` | prose between calls | | ok | |
| `qwen-three-calls-in-the-thinking` | #804: two calls at the end of the thinking | | FAIL | whole: error: reasoning ended without </think> |
| `qwen-function-close-left-out` | #4427 shape: no </function> (PR #3960's Coder-L slip) | | FAIL | whole: error: tool parameter is incomplete |
| `qwen-function-close-left-out-in-thinking` | the same inside the thinking | | FAIL | whole: error: reasoning ended without </think> |
| `qwen-wrapper-close-left-out` | the output ends on </function> (the server always streams) | | FAIL | whole: error: tool call is missing </tool_call> |
| `qwen-wrapper-close-left-out-in-thinking` | the same inside the thinking | | FAIL | whole: error: reasoning ended without </think> |
| `qwen-wrapper-close-left-out-two-calls` | a following opener confirms the missing closer | | FAIL | whole: error: tool call is missing </tool_call> |
| `qwen-wrapper-close-left-out-two-calls-in-thinking` | the same inside the thinking | | FAIL | whole: error: reasoning ended without </think> |
| `qwen-undeclared-name-is-text` | by design: a call for a tool the request did not declare comes back as text (and is counted) | | FAIL | whole: error: undeclared function in tool call: format_disk |
| `qwen-cut-inside-a-value` | an unterminated tag: the output stopped at the token limit; no call | | FAIL | whole: error: tool parameter is incomplete |
| `qwen-cut-inside-the-opener` | cut inside the name | | FAIL | whole: error: tool call function name is incomplete |
| `qwen-cut-after-function-close-on-length` | a turn cut by the token limit is not a natural stop: no call | | FAIL | whole: error: tool call is missing </tool_call> |
| `qwen-quoted-in-a-fence` | #1058: a call in a code fence is a quote | | FAIL | whole: calls: got read want |
| `qwen-prose-names-the-format` | prose that names the tag | | FAIL | whole: error: tool call needs <function=NAME> |
| `drift-parameter-as-opener` | corpus 300dfba2 (x11) | yes | FAIL | whole: error: tool call needs <function=NAME> |
| `drift-json-in-the-wrapper` | corpus 5e847539 (x6) | yes | FAIL | whole: error: tool call needs <function=NAME> |
| `drift-bare-function` | corpus 395efd4c / 6e71eed4 (x5 each) | yes | FAIL | whole: calls: got want write |
| `drift-batch-in-one-wrapper` | corpus 0912870b / 51b155c9 | yes | FAIL | whole: error: tool call is missing </tool_call> |
| specimen | what it is | recover | main (before) | after 2 | first difference at the last stage |
| --- | --- | --- | --- | --- | --- |
| `4427-todos-valid` | #4427 first example (the Harness todo_write call) | | ok | ok | |
| `4427-todos-stray-items` | #4427 second example: `"status": "pending", "in_progress", "pending": false` | | FAIL | FAIL | whole: calls: got todo_write want todo_write |
| `4427-todos-single-quotes` | #4427 shape: Python quotes | | FAIL | FAIL | whole: calls: got todo_write want todo_write |
| `4427-todos-trailing-comma-and-open-bracket` | #4427 shape: a cut array | | FAIL | FAIL | whole: calls: got todo_write want todo_write |
| `4427-todos-json-string-of-an-array` | #4427 shape: the array written as a JSON string | | FAIL | FAIL | whole: calls: got todo_write want todo_write |
| `4427-todos-not-json-stays-text` | #4427: text that is no array stays the text it is | | ok | ok | |
| `4427-one-line` | #4427: the tags on one line | | ok | ok | |
| `4427-one-line-in-thinking` | #4427: written inside the thinking, the turn ends on it | | FAIL | FAIL | whole: error: reasoning ended without </think> |
| `4078-nested-call` | #4078: a value holding a whole call | | FAIL | ok | |
| `4078-reopened-parameter` | #4078: a value that reopens its own parameter | | FAIL | FAIL | whole: error: duplicate tool parameter: content |
| `4078-heredoc` | #4078: a heredoc that prints a quoted call | | FAIL | ok | |
| `4078-call-format-in-a-file` | #210: a file that documents the format | | ok | ok | |
| `4077-stray-think-line` | #4077: the model quoted the closing tag at a line start | | FAIL | FAIL | whole: content differs |
| `4077-stray-think-in-a-fence` | #4077: the quote sat in a code fence, so the fence closes in the 'answer' | | FAIL | FAIL | whole: content differs |
| `4077-stray-think-after-a-backtick` | #4077: an open backtick | | FAIL | FAIL | whole: content differs |
| `4077-quoted-think-stays-reasoning` | #537: a closing tag after a backtick is still reasoning (control) | | FAIL | FAIL | whole: content differs |
| `4077-closer-in-the-answer-text-is-kept-mid-line` | a closing tag inside a sentence of the answer is text (control) | | ok | ok | |
| `4077-no-second-closer-is-the-normal-case` | control | | ok | ok | |
| `qwen-one-call` | the template's own form | | ok | ok | |
| `qwen-int-argument` | a declared integer | | ok | ok | |
| `qwen-after-thinking` | the normal agent turn | | ok | ok | |
| `qwen-call-in-the-thinking` | #804: the turn ends inside the thinking, on the call | | FAIL | FAIL | whole: error: reasoning ended without </think> |
| `qwen-three-calls` | parallel calls, one wrapper each | | ok | ok | |
| `qwen-calls-with-prose-between` | prose between calls | | ok | ok | |
| `qwen-three-calls-in-the-thinking` | #804: two calls at the end of the thinking | | FAIL | FAIL | whole: error: reasoning ended without </think> |
| `qwen-function-close-left-out` | #4427 shape: no </function> (PR #3960's Coder-L slip) | | FAIL | FAIL | whole: error: tool parameter is incomplete |
| `qwen-function-close-left-out-in-thinking` | the same inside the thinking | | FAIL | FAIL | whole: error: reasoning ended without </think> |
| `qwen-wrapper-close-left-out` | the output ends on </function> (the server always streams) | | FAIL | FAIL | whole: error: tool call is missing </tool_call> |
| `qwen-wrapper-close-left-out-in-thinking` | the same inside the thinking | | FAIL | FAIL | whole: error: reasoning ended without </think> |
| `qwen-wrapper-close-left-out-two-calls` | a following opener confirms the missing closer | | FAIL | FAIL | whole: error: tool call is missing </tool_call> |
| `qwen-wrapper-close-left-out-two-calls-in-thinking` | the same inside the thinking | | FAIL | FAIL | whole: error: reasoning ended without </think> |
| `qwen-undeclared-name-is-text` | by design: a call for a tool the request did not declare comes back as text (and is counted) | | FAIL | FAIL | whole: error: undeclared function in tool call: format_disk |
| `qwen-cut-inside-a-value` | an unterminated tag: the output stopped at the token limit; no call | | FAIL | FAIL | whole: error: tool parameter is incomplete |
| `qwen-cut-inside-the-opener` | cut inside the name | | FAIL | FAIL | whole: error: tool call function name is incomplete |
| `qwen-cut-after-function-close-on-length` | a turn cut by the token limit is not a natural stop: no call | | FAIL | FAIL | whole: error: tool call is missing </tool_call> |
| `qwen-quoted-in-a-fence` | #1058: a call in a code fence is a quote | | FAIL | FAIL | whole: calls: got read want |
| `qwen-prose-names-the-format` | prose that names the tag | | FAIL | FAIL | whole: error: tool call needs <function=NAME> |
| `drift-parameter-as-opener` | corpus 300dfba2 (x11) | yes | FAIL | FAIL | whole: error: tool call needs <function=NAME> |
| `drift-json-in-the-wrapper` | corpus 5e847539 (x6) | yes | FAIL | FAIL | whole: error: tool call needs <function=NAME> |
| `drift-bare-function` | corpus 395efd4c / 6e71eed4 (x5 each) | yes | FAIL | FAIL | whole: calls: got want write |
| `drift-batch-in-one-wrapper` | corpus 0912870b / 51b155c9 | yes | FAIL | FAIL | whole: error: tool call is missing </tool_call> |
## Quoted-call value shapes (`serve/test_quoted_call_values.py`)
Six string-argument shapes, each read whole and streamed in pieces of 1, 7 and everything; the argument must come back exact and no text may leak.
| shape | main (before) |
| --- | --- |
| quoted call | FAIL |
| quoted call at the end | FAIL |
| heredoc | FAIL |
| repeated parameter | FAIL |
| unclosed opener in prose | ok |
| unclosed opener in code | ok |
| shape | main (before) | after 2 |
| --- | --- | --- |
| quoted call | FAIL | ok |
| quoted call at the end | FAIL | ok |
| heredoc | FAIL | ok |
| repeated parameter | FAIL | FAIL |
| unclosed opener in prose | ok | ok |
| unclosed opener in code | ok | ok |
## What each stage changed
* **after 2 (truncation fix).** A string argument that quotes a whole tool call is no longer cut at the quoted text.
`find_parameter_end` ends a value at the first `</parameter>` that is followed by the next `<parameter=` or `</function>` and
that is not inside a call the value quotes: the quoted openers (`<function=NAME>` then `<parameter=` or `</function>`) before it
must not outnumber the `</function>` closers before it. A bare `<function=` in prose or code does not count. Whole and streamed
reading agree. A call whose value quotes an opener and never closes it is now treated as unterminated (an error) instead of
being cut at the first plausible close; the previous behaviour would have published a truncated call whenever a long write
that quotes a call was itself cut by the token limit.
Not changed, on purpose: a value that reopens its own parameter (`4078-reopened-parameter`, the `repeated parameter` shape).
Upstream reads `</parameter><parameter=content>` inside a `content` value as text. Here it is the same bytes as a parameter
written twice, which `native_tools_sdet::unknown_incomplete_duplicate_or_late_invalid_call_refuses_entire_output` requires to
be refused; reading it as one value would merge two arguments of a malformed call into a corrupt one without an error. It
stays an error (`duplicate tool parameter`).