[GH-ISSUE #3009] [Issue]: Tool call is silently dropped when a string argument value contains the literal closing tag (e.g. </tool_call>) #1581

Closed
opened 2026-10-21 05:39:49 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @kolacheee on GitHub (Jun 29, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3009

Originally assigned to: @SpicyMarinara on GitHub.

What's wrong

The tagged-snippet extraction regexes are non-greedy and stop at the FIRST occurrence of the closing delimiter, even when that delimiter appears INSIDE a JSON string argument. For the <tool_call> pattern, an argument like {"q":"check </tool_call> now"} causes the capture to end at the embedded </tool_call>, yielding truncated, invalid JSON. That snippet then fails parseJsonishObject, fails the name{...} regex, and (because the command fallback is on for this pattern) normalizeMariCommand rejects it too — so the call is dropped entirely. If it was the only tool call in the turn, the whole turn produces zero tool calls and the model's intended action is lost. The same truncation affects </arg_value>, the <|tool_call|> variants, and the Llama <|eom_id|>/<|eot_id|>/<|end_header_id|> delimiters whenever those literal substrings appear inside a string argument.

How to reproduce (try it yourself)

  1. With a non-native-tool-calling model via the OpenAI-compatible provider, return content exactly <tool_call>{"name":"get_weather","arguments":{"q":"check </tool_call> now"}}</tool_call>.

You'll see: parseTextualToolCalls returns []. The captured group truncates to {"name":"get_weather","arguments":{"q":"check, which is invalid JSON and rejected by every fallback. With two calls where the first contains the literal closing tag and the second is clean, only the second survives. Confirmed by faithful reproduction (count 0); the identical content without the embedded tag parses cleanly, proving the embedded delimiter is the sole cause.

Expected: the tool call is parsed correctly; a closing-tag substring inside a quoted argument value does not terminate the capture.

Where it is

packages/server/src/services/llm/textual-tool-call-parser.ts: pattern 2 in parseTaggedSnippets at lines 78-82 (function defined 70-109), consumed at lines 217-225 (snippetToPayload → null). Invoked from packages/server/src/services/llm/providers/openai.provider.ts:1259 and :1427.

What's happening

The patterns delimit tool-call payloads with [\s\S]*? up to the first literal closing token, with no awareness of JSON string boundaries/escaping. A closing-tag substring inside a quoted argument value prematurely terminates the capture, producing unparseable truncated JSON that all downstream fallbacks reject.

Suggested fix

Rewrite parseTaggedSnippets so each tag pattern captures its OPENING tag as group 1 and the body as group 2, then add a string/escape-aware balanced-JSON recovery that runs ONLY when the captured body fails to produce a payload, anchored at that match's own position.

Add a helper that extracts the first balanced {...} or [...] respecting JSON string/escape state:

function extractBalancedJson(text: string): string | null {
  const brace = text.indexOf("{");
  const bracket = text.indexOf("[");
  const start = brace === -1 ? bracket : bracket === -1 ? brace : Math.min(brace, bracket);
  if (start < 0) return null;
  const open = text[start];
  const close = open === "{" ? "}" : "]";
  let depth = 0, inString = false, escaped = false;
  for (let i = start; i < text.length; i++) {
    const ch = text[i];
    if (inString) {
      if (escaped) escaped = false;
      else if (ch === "\\") escaped = true;
      else if (ch === '"') inString = false;
      continue;
    }
    if (ch === '"') { inString = true; continue; }
    if (ch === open) depth++;
    else if (ch === close && --depth === 0) return text.slice(start, i + 1);
  }
  return null;
}

Then, in each pattern's match loop, capture the opening tag as group 1 and the body as group 2; when snippetToPayload(captured, options) returns null, re-extract from this match's own body offset (match.index + match[1].length) using extractBalancedJson and use it only if parseJsonishObject accepts it. Otherwise keep the original captured text.

Regression avoided: the recovery must be (a) GATED — only attempted when the primary captured snippet fails snippetToPayload, so name{...} command-form snippets, the normalizeMariCommand fallback, and </arg_value>-structured forms keep their exact behavior — and (b) PER-MATCH ANCHORED — extracted from this match's own offset, not a fresh content-wide scan, otherwise a truncated SECOND call recovers the FIRST call's JSON, and a name{...} snippet loses its leading tool name. Both constraints were verified empirically (embedded </tool_call>/<|/tool_call|> recovered; happy path, name{...}, mari-command, two-call/second-truncated, and arg_value-structured cases all unchanged). Gemma <|"|> delimiters are still normalized on the final snippet text at the call site.


AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.

Originally created by @kolacheee on GitHub (Jun 29, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3009 Originally assigned to: @SpicyMarinara on GitHub. **What's wrong** The tagged-snippet extraction regexes are non-greedy and stop at the FIRST occurrence of the closing delimiter, even when that delimiter appears INSIDE a JSON string argument. For the `<tool_call>` pattern, an argument like `{"q":"check </tool_call> now"}` causes the capture to end at the embedded `</tool_call>`, yielding truncated, invalid JSON. That snippet then fails `parseJsonishObject`, fails the `name{...}` regex, and (because the command fallback is on for this pattern) `normalizeMariCommand` rejects it too — so the call is dropped entirely. If it was the only tool call in the turn, the whole turn produces zero tool calls and the model's intended action is lost. The same truncation affects `</arg_value>`, the `<|tool_call|>` variants, and the Llama `<|eom_id|>`/`<|eot_id|>`/`<|end_header_id|>` delimiters whenever those literal substrings appear inside a string argument. **How to reproduce (try it yourself)** 1. With a non-native-tool-calling model via the OpenAI-compatible provider, return content exactly `<tool_call>{"name":"get_weather","arguments":{"q":"check </tool_call> now"}}</tool_call>`. You'll see: `parseTextualToolCalls` returns `[]`. The captured group truncates to `{"name":"get_weather","arguments":{"q":"check`, which is invalid JSON and rejected by every fallback. With two calls where the first contains the literal closing tag and the second is clean, only the second survives. Confirmed by faithful reproduction (count 0); the identical content without the embedded tag parses cleanly, proving the embedded delimiter is the sole cause. Expected: the tool call is parsed correctly; a closing-tag substring inside a quoted argument value does not terminate the capture. **Where it is** `packages/server/src/services/llm/textual-tool-call-parser.ts`: pattern 2 in `parseTaggedSnippets` at lines 78-82 (function defined 70-109), consumed at lines 217-225 (`snippetToPayload` → null). Invoked from `packages/server/src/services/llm/providers/openai.provider.ts:1259` and `:1427`. **What's happening** The patterns delimit tool-call payloads with `[\s\S]*?` up to the first literal closing token, with no awareness of JSON string boundaries/escaping. A closing-tag substring inside a quoted argument value prematurely terminates the capture, producing unparseable truncated JSON that all downstream fallbacks reject. **Suggested fix** Rewrite `parseTaggedSnippets` so each tag pattern captures its OPENING tag as group 1 and the body as group 2, then add a string/escape-aware balanced-JSON recovery that runs ONLY when the captured body fails to produce a payload, anchored at that match's own position. Add a helper that extracts the first balanced `{...}` or `[...]` respecting JSON string/escape state: ```ts function extractBalancedJson(text: string): string | null { const brace = text.indexOf("{"); const bracket = text.indexOf("["); const start = brace === -1 ? bracket : bracket === -1 ? brace : Math.min(brace, bracket); if (start < 0) return null; const open = text[start]; const close = open === "{" ? "}" : "]"; let depth = 0, inString = false, escaped = false; for (let i = start; i < text.length; i++) { const ch = text[i]; if (inString) { if (escaped) escaped = false; else if (ch === "\\") escaped = true; else if (ch === '"') inString = false; continue; } if (ch === '"') { inString = true; continue; } if (ch === open) depth++; else if (ch === close && --depth === 0) return text.slice(start, i + 1); } return null; } ``` Then, in each pattern's match loop, capture the opening tag as group 1 and the body as group 2; when `snippetToPayload(captured, options)` returns null, re-extract from this match's own body offset (`match.index + match[1].length`) using `extractBalancedJson` and use it only if `parseJsonishObject` accepts it. Otherwise keep the original captured text. *Regression avoided:* the recovery must be (a) GATED — only attempted when the primary captured snippet fails `snippetToPayload`, so `name{...}` command-form snippets, the `normalizeMariCommand` fallback, and `</arg_value>`-structured forms keep their exact behavior — and (b) PER-MATCH ANCHORED — extracted from this match's own offset, not a fresh content-wide scan, otherwise a truncated SECOND call recovers the FIRST call's JSON, and a `name{...}` snippet loses its leading tool name. Both constraints were verified empirically (embedded `</tool_call>`/`<|/tool_call|>` recovered; happy path, `name{...}`, mari-command, two-call/second-truncated, and arg_value-structured cases all unchanged). Gemma `<|"|>` delimiters are still normalized on the final snippet text at the call site. --- *AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.*
Author
Owner

@SpicyMarinara commented on GitHub (Jun 29, 2026):

Fixed in merged staging PR #3018.

<!-- gh-comment-id:4833017416 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Fixed in merged staging PR #3018.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#1581
No description provided.