[PR #5541] [MERGED] Make sidecar JSON agents robust to inline thinking and Gemma delimiters #6806

Closed
opened 2026-10-23 04:13:54 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/5541
Author: @kolacheee
Created: 8/25/2026
Status: ✅ Merged
Merged: 8/25/2026
Merged by: @SpicyMarinara

Base: staging ← Head: fix/5537-sidecar-agent-json


📝 Commits (1)

  • 2243d54 fix(agents): make sidecar JSON agents robust to inline thinking and Gemma delimiters

📊 Changes

4 files changed (+128 additions, -1 deletions)

View changed files

📝 CHANGELOG.md (+1 -0)
📝 packages/server/src/services/agents/agent-executor.ts (+53 -0)
📝 packages/server/src/services/llm/textual-tool-call-parser.ts (+3 -1)
📝 scripts/regressions/agent-runtime.regression.ts (+71 -0)

📄 Description

Note

Stacked on #5540 (base branch fix/5538-local-model-card-expand). Merge #5540 first; GitHub retargets this PR to staging automatically. The diff shown here is then exactly this fix.

Linked issue

Closes #5537

Why this change

Every JSON-returning agent on the built-in Local Model fails with "Agent returned invalid JSON…" since the Aug 19 staging update (#5247): JSON agents now send reasoningEffort: "none", which the sidecar translates to reasoning_format: "none" + chat_template_kwargs.enable_thinking: false. reasoning_format: "none" makes llama.cpp leave any thinking inline in content — and the agent path asks for JSON by prompt alone, with no response_format/grammar anywhere, so a thinking preamble poisons the fence/brace extraction identically on the first call, the strict retry, and the batch fallback. Full analysis in #5537. (Ironically #5247 was itself a Gemma JSON fix; it fixed the empty-content mode and exposed this one.)

What changed

Three layers, from prevention to tolerance, all in packages/server:

1. Sidecar JSON agents are now grammar-constrained. executeAgent, the tool loop's final round, and executeAgentBatch attach responseFormat: { type: "json_object" } when the model is the local sidecar and the agent's result must parse as JSON. llama.cpp then constrains generation itself — the parse cannot be poisoned regardless of what the template does with thinking. Scoping decisions:

  • Sidecar only (model === LOCAL_SIDECAR_MODEL): it's the runtime we ship and the one guaranteed to support the parameter; remote providers keep their existing prompt-only behavior. The MLX backend already strips responseFormat in LocalSidecarProvider, so both sidecar backends are safe.
  • Not on tool rounds: a JSON grammar would constrain the completion before the model can emit tool-call tokens, so rounds that pass tools are excluded and the final no-tools round carries the format instead (commented in code).
  • Beholder lanes deliberately untouched: they have their own tuned call shape from #5251 and were not part of the breakage; the parse-tolerance layer below still covers them.
  • Side effect worth knowing: a set responseFormat switches LocalSidecarProvider to greedy sampling (temp 0 / topP 1) — the desired decoding for machine-readable output, but it does override an agent's configured temperature on the sidecar.

2. extractJson strips leading thinking blocks before the fence match. Uses the existing extractLeadingThinkingBlocks from @marinara-engine/shared (covers <think>, <thinking>, <thought>, bracketed variants). Ordering matters: a fenced draft inside the thinking region would otherwise win the fence regex. One change covers every extraction site — first call, retry, tool loop, beholder lanes, batch container, and batch per-agent fallback.

3. Gemma 4 <|"|> delimiters are normalized in the agent JSON path. normalizeGemma4Delimiters is now exported from the textual tool-call parser (previously module-private) and applied in extractJson, so the agent path tolerates the same model quirk the tool-call path already handles.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

Automated, from this branch:

  • pnpm lint passes (tsc on shared+server, ESLint on client).
  • node ./scripts/run-regressions.mjs --filter scripts/regressions/agent-runtime.regression.ts passes, including seven new assertions: thinking-prefixed JSON parses without a retry; a fenced draft inside a thinking block loses to the real payload; Gemma <|"|> delimiters parse; sidecar JSON agents request json_object; non-sidecar agents and text-result agents on the sidecar do not.
  • Touched files are Prettier-clean under the repo config (--end-of-line auto; repo-wide format:check fails pre-existing on CRLF Windows checkouts).

Needs a human with the local model downloaded (I could not run the sidecar binary in this environment):

  • The reporter's scenario: agents (e.g. persona-stats / trackers) explicitly set to Local Model (sidecar), default Gemma model, send messages — no more "invalid JSON" errors.
  • Confirm normal text generation through the sidecar (main chat) is unchanged.
  • Confirm an agent with tools on the sidecar still executes tool calls (tool rounds carry no response format).
  • If feasible, one run with LOG_LEVEL=debug to confirm requests carry response_format: {"type":"json_object"} and responses parse on the first call.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened (see CONTRIBUTING.md § Translated documentation)
  • Version/release files updated (only if this PR includes a version bump)

CHANGELOG entry under [Unreleased] → Fixed. No user-facing docs describe the agent JSON pipeline; no docs-i18n impact.

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability of structured JSON responses from local AI models.
    • Removed unwanted leading reasoning blocks from generated responses before processing.
    • Improved compatibility with Gemma 4 response formatting.
    • Preserved tool-call workflows while applying JSON formatting only to final responses.
  • Documentation

    • Added an unreleased changelog entry describing the local model response improvements.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/5541 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/25/2026 **Status:** ✅ Merged **Merged:** 8/25/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/5537-sidecar-agent-json` --- ### 📝 Commits (1) - [`2243d54`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2243d54802fb5314ff3748423fd1cf05615ca3bb) fix(agents): make sidecar JSON agents robust to inline thinking and Gemma delimiters ### 📊 Changes **4 files changed** (+128 additions, -1 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+1 -0) 📝 `packages/server/src/services/agents/agent-executor.ts` (+53 -0) 📝 `packages/server/src/services/llm/textual-tool-call-parser.ts` (+3 -1) 📝 `scripts/regressions/agent-runtime.regression.ts` (+71 -0) </details> ### 📄 Description > [!NOTE] > **Stacked on #5540** (base branch `fix/5538-local-model-card-expand`). Merge #5540 first; GitHub retargets this PR to `staging` automatically. The diff shown here is then exactly this fix. ## Linked issue Closes #5537 ## Why this change Every JSON-returning agent on the built-in Local Model fails with "Agent returned invalid JSON…" since the Aug 19 staging update (#5247): JSON agents now send `reasoningEffort: "none"`, which the sidecar translates to `reasoning_format: "none"` + `chat_template_kwargs.enable_thinking: false`. `reasoning_format: "none"` makes llama.cpp leave any thinking **inline in `content`** — and the agent path asks for JSON by prompt alone, with no `response_format`/grammar anywhere, so a thinking preamble poisons the fence/brace extraction identically on the first call, the strict retry, and the batch fallback. Full analysis in #5537. (Ironically #5247 was itself a Gemma JSON fix; it fixed the empty-content mode and exposed this one.) ## What changed Three layers, from prevention to tolerance, all in `packages/server`: **1. Sidecar JSON agents are now grammar-constrained.** `executeAgent`, the tool loop's final round, and `executeAgentBatch` attach `responseFormat: { type: "json_object" }` when the model is the local sidecar and the agent's result must parse as JSON. llama.cpp then constrains generation itself — the parse cannot be poisoned regardless of what the template does with thinking. Scoping decisions: - **Sidecar only** (`model === LOCAL_SIDECAR_MODEL`): it's the runtime we ship and the one guaranteed to support the parameter; remote providers keep their existing prompt-only behavior. The MLX backend already strips `responseFormat` in `LocalSidecarProvider`, so both sidecar backends are safe. - **Not on tool rounds**: a JSON grammar would constrain the completion before the model can emit tool-call tokens, so rounds that pass `tools` are excluded and the final no-tools round carries the format instead (commented in code). - **Beholder lanes deliberately untouched**: they have their own tuned call shape from #5251 and were not part of the breakage; the parse-tolerance layer below still covers them. - Side effect worth knowing: a set `responseFormat` switches `LocalSidecarProvider` to greedy sampling (temp 0 / topP 1) — the desired decoding for machine-readable output, but it does override an agent's configured temperature on the sidecar. **2. `extractJson` strips leading thinking blocks before the fence match.** Uses the existing `extractLeadingThinkingBlocks` from `@marinara-engine/shared` (covers `<think>`, `<thinking>`, `<thought>`, bracketed variants). Ordering matters: a fenced draft *inside* the thinking region would otherwise win the fence regex. One change covers every extraction site — first call, retry, tool loop, beholder lanes, batch container, and batch per-agent fallback. **3. Gemma 4 `<|"|>` delimiters are normalized in the agent JSON path.** `normalizeGemma4Delimiters` is now exported from the textual tool-call parser (previously module-private) and applied in `extractJson`, so the agent path tolerates the same model quirk the tool-call path already handles. ## Validation <!-- These are human tasks. Never tick a box for a check that was not actually performed. --> - [x] `pnpm check` passes locally - [x] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [x] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [x] Above manual verification completed (describe below) - [x] Read and followed `CONTRIBUTING.md` ### Manual verification notes Automated, from this branch: - `pnpm lint` passes (tsc on shared+server, ESLint on client). - `node ./scripts/run-regressions.mjs --filter scripts/regressions/agent-runtime.regression.ts` passes, including seven new assertions: thinking-prefixed JSON parses without a retry; a fenced draft inside a thinking block loses to the real payload; Gemma `<|"|>` delimiters parse; sidecar JSON agents request `json_object`; non-sidecar agents and text-result agents on the sidecar do not. - Touched files are Prettier-clean under the repo config (`--end-of-line auto`; repo-wide `format:check` fails pre-existing on CRLF Windows checkouts). Needs a human with the local model downloaded (I could not run the sidecar binary in this environment): - **The reporter's scenario**: agents (e.g. persona-stats / trackers) explicitly set to Local Model (sidecar), default Gemma model, send messages — no more "invalid JSON" errors. - Confirm normal *text* generation through the sidecar (main chat) is unchanged. - Confirm an agent with tools on the sidecar still executes tool calls (tool rounds carry no response format). - If feasible, one run with `LOG_LEVEL=debug` to confirm requests carry `response_format: {"type":"json_object"}` and responses parse on the first call. ## Docs and release impact - [ ] No docs changes needed - [x] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened (see CONTRIBUTING.md § Translated documentation) - [ ] Version/release files updated (only if this PR includes a version bump) CHANGELOG entry under `[Unreleased] → Fixed`. No user-facing docs describe the agent JSON pipeline; no `docs-i18n` impact. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Bug Fixes** - Improved reliability of structured JSON responses from local AI models. - Removed unwanted leading reasoning blocks from generated responses before processing. - Improved compatibility with Gemma 4 response formatting. - Preserved tool-call workflows while applying JSON formatting only to final responses. - **Documentation** - Added an unreleased changelog entry describing the local model response improvements. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-23 04:13:54 +07:00
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#6806
No description provided.