STRA-338 size-fn: gateway-text: parse_call, parse_text, json_call, content_text, write_json, Lenient::array within limits

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 18:08:45 +01:00
parent 5a14bc26b0
commit 491c7cd902
4 changed files with 62 additions and 31 deletions
+20 -8
View File
@@ -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<String, String> {
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<String, String> {
}
}
/// 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 {
@@ -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(()),
}
}
}
@@ -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<Segment>, 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 `<tool_call>` wrapper).
fn next_opener(text: &str, code: &CodeState, tools: &[Value], options: Options) -> Option<(usize, bool)> {
let wrapped = text.find("<tool_call>");
@@ -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']);
@@ -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<PatchShell>), 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`.