From 491c7cd902c8241ed6ddde040a67ca3622e0ba99 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 18:08:45 +0100 Subject: [PATCH] STRA-338 size-fn: gateway-text: parse_call, parse_text, json_call, content_text, write_json, Lenient::array within limits --- crates/gateway-text/src/prompt/json_string.rs | 28 +++++++++++++------ .../src/tool_output/parameter_value.rs | 15 ++++++---- .../src/tool_output/parse_text.rs | 24 ++++++++++------ .../src/tool_output/starts_batched_call.rs | 26 ++++++++++------- 4 files changed, 62 insertions(+), 31 deletions(-) diff --git a/crates/gateway-text/src/prompt/json_string.rs b/crates/gateway-text/src/prompt/json_string.rs index df97d465..327dc524 100644 --- a/crates/gateway-text/src/prompt/json_string.rs +++ b/crates/gateway-text/src/prompt/json_string.rs @@ -42,8 +42,7 @@ fn push_json_char(c: char, ensure_ascii: bool, out: &mut String) { pub(super) fn write_json(value: &Value, sort_keys: bool, ensure_ascii: bool, out: &mut String) -> Result<(), Error> { match value.kind() { - ValueKind::None => out.push_str("null"), - ValueKind::Bool => out.push_str(if value.is_true() { "true" } else { "false" }), + ValueKind::None | ValueKind::Bool => out.push_str(json_literal(value)), ValueKind::Number => write_number(value, out)?, ValueKind::String => json_string(value.as_str().unwrap_or_default(), ensure_ascii, out), ValueKind::Seq | ValueKind::Iterable => write_array(value, sort_keys, ensure_ascii, out)?, @@ -58,6 +57,15 @@ pub(super) fn write_json(value: &Value, sort_keys: bool, ensure_ascii: bool, out Ok(()) } +/// `null`, `true` or `false`. +fn json_literal(value: &Value) -> &'static str { + match value.kind() { + ValueKind::None => "null", + _ if value.is_true() => "true", + _ => "false", + } +} + fn write_number(value: &Value, out: &mut String) -> Result<(), Error> { if value.is_integer() { out.push_str(&value.to_string()); @@ -143,12 +151,7 @@ pub(super) fn content_text(content: Option<&Json>) -> Result { let mut text = String::new(); for part in parts { let Json::Object(_) = part else { continue }; - let text_part = match part.get("type") { - None | Some(Json::Null) => true, - Some(Json::String(kind)) => kind == "text" || kind == "input_text", - Some(_) => false, - }; - if !text_part { + if !is_text_part(part) { continue; } match part.get("text") { @@ -165,6 +168,15 @@ pub(super) fn content_text(content: Option<&Json>) -> Result { } } +/// A part of type `text`, `input_text` or no type. +fn is_text_part(part: &Json) -> bool { + match part.get("type") { + None | Some(Json::Null) => true, + Some(Json::String(kind)) => kind == "text" || kind == "input_text", + Some(_) => false, + } +} + /// `serve/frontend.py` `_has_image`: a list content with an `image_url`, `input_image` or `image` part. pub(super) fn content_has_image(content: Option<&Json>) -> bool { let Some(Json::Array(parts)) = content else { diff --git a/crates/gateway-text/src/tool_output/parameter_value.rs b/crates/gateway-text/src/tool_output/parameter_value.rs index 9e859d99..29bf7004 100644 --- a/crates/gateway-text/src/tool_output/parameter_value.rs +++ b/crates/gateway-text/src/tool_output/parameter_value.rs @@ -267,11 +267,16 @@ impl Lenient { Some(_) => {} } items.push(self.value(depth)?); - match self.peek() { - Some(',' | ']') => {} - None if self.lossy => {} - _ => return Err(()), - } + self.item_end()?; + } + } + + /// After an array item comes a comma or the closing bracket (or the end of the text, in `lossy` mode). + fn item_end(&mut self) -> Result<(), ()> { + match self.peek() { + Some(',' | ']') => Ok(()), + None if self.lossy => Ok(()), + _ => Err(()), } } } diff --git a/crates/gateway-text/src/tool_output/parse_text.rs b/crates/gateway-text/src/tool_output/parse_text.rs index d7c5cdba..092695b2 100644 --- a/crates/gateway-text/src/tool_output/parse_text.rs +++ b/crates/gateway-text/src/tool_output/parse_text.rs @@ -13,10 +13,7 @@ pub(super) fn parse_text( let mut notes = Notes::default(); while let Some((start, is_bare)) = next_opener(text, &code, tools, options) { let raw = &text[..start]; - let prefix = raw.trim_end_matches('\n'); - if !prefix.is_empty() { - segments.push(Segment::Text(prefix.to_owned())); - } + push_text_before_call(&mut segments, raw); if options.recovery { code.feed(raw); } @@ -35,6 +32,14 @@ pub(super) fn parse_text( Ok(Parsed { segments, notes }) } +/// The text before a call, without the newlines that separate it from the call, is a text segment. +fn push_text_before_call(segments: &mut Vec, raw: &str) { + let prefix = raw.trim_end_matches('\n'); + if !prefix.is_empty() { + segments.push(Segment::Text(prefix.to_owned())); + } +} + /// Where the next call opens in `text` and whether it is a bare function (else a `` wrapper). fn next_opener(text: &str, code: &CodeState, tools: &[Value], options: Options) -> Option<(usize, bool)> { let wrapped = text.find(""); @@ -176,10 +181,7 @@ pub(super) fn json_call(text: &str, tools: &[Value]) -> Option<(Segment, usize)> object = unfence(fenced)?; } let value: Value = serde_json::from_str(object).ok()?; - let name = value.get("name")?.as_str()?; - if !is_declared(name, tools) { - return None; - } + let name = declared_name(&value, tools)?; let arguments = json_call_arguments(&value)?; arguments.is_object().then(|| { ( @@ -192,6 +194,12 @@ pub(super) fn json_call(text: &str, tools: &[Value]) -> Option<(Segment, usize)> }) } +/// `name` of a JSON call, when it names a declared tool. +fn declared_name<'v>(value: &'v Value, tools: &[Value]) -> Option<&'v str> { + let name = value.get("name")?.as_str()?; + is_declared(name, tools).then_some(name) +} + /// The JSON inside a Markdown fence whose opening backticks are already stripped (`json` tag optional). fn unfence(fenced: &str) -> Option<&str> { let after = fenced.trim_start_matches([' ', '\t']); diff --git a/crates/gateway-text/src/tool_output/starts_batched_call.rs b/crates/gateway-text/src/tool_output/starts_batched_call.rs index c08d13c7..77394878 100644 --- a/crates/gateway-text/src/tool_output/starts_batched_call.rs +++ b/crates/gateway-text/src/tool_output/starts_batched_call.rs @@ -28,6 +28,21 @@ pub(super) fn parse_call( if name.is_empty() { return Err("tool call function name is empty".to_owned()); } + let (tool, patch_shell) = resolve_tool(tools, name)?; + let mut scan = CallScan::new(text, tools, options, (closes_call, bare), offset); + while scan.step(tool)? {} + notes.absorb(&scan.found); + let (offset, more) = (scan.offset, scan.more); + if let Some(shell) = &patch_shell { + let (name, arguments) = shell.rewrite(&scan.arguments); + return Ok((Segment::Call { name, arguments }, offset, more)); + } + let arguments = Value::Object(scan.arguments); + Ok((Segment::Call { name: name.to_owned(), arguments }, offset, more)) +} + +/// The declared tool called `name`, or the shell tool that runs an undeclared `apply_patch`. +fn resolve_tool<'t>(tools: &'t [Value], name: &str) -> Result<(Option<&'t Value>, Option), String> { let tool = find_tool(tools, name); // The model sometimes calls `apply_patch` as a function although the agent declared none (Codex runs patches as // `apply_patch <<'PATCH'` through its shell tool): run it that way instead of failing the stream, which the agent @@ -42,16 +57,7 @@ pub(super) fn parse_call( // take that for the end of its turn). The client sees a failed response and retries. return Err(format!("undeclared function in tool call: {name}")); } - let mut scan = CallScan::new(text, tools, options, (closes_call, bare), offset); - while scan.step(tool)? {} - notes.absorb(&scan.found); - let (offset, more) = (scan.offset, scan.more); - if let Some(shell) = &patch_shell { - let (name, arguments) = shell.rewrite(&scan.arguments); - return Ok((Segment::Call { name, arguments }, offset, more)); - } - let arguments = Value::Object(scan.arguments); - Ok((Segment::Call { name: name.to_owned(), arguments }, offset, more)) + Ok((tool, patch_shell)) } /// The declared tool called `name`.