[GH-ISSUE #4753] [Feature]: Agents use weaker JSON repair than workspace agent; upgrading to the workspace approach is prudent #2614

Closed
opened 2026-10-21 05:51:24 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @xDanteMD on GitHub (Aug 8, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/4753

Originally assigned to: @SpicyMarinara on GitHub.

What problem does this solve?

Download agents (Lorebook Keeper, Card Evolution Auditor, and 15+ others) use a minimal repairJson() function that only handles trailing commas, comments, and ellipsis. The workspace agent (Professor Mari) uses the full jsonrepair@3.15.0 library plus a custom closeOpenJsonContainers() function. This means the same model producing the same malformed JSON will succeed in the workspace agent but fail in download agents.

MoE models (Deepseek, Mimo, Kimi, GLM, etc.) have a known failure mode of producing JSON that is "a little bit off" — single quotes instead of double quotes, unquoted keys, missing closing brackets when truncated. The workspace agent's repair pipeline handles most of these; the agents' repair does not.

The two repair systems

Workspace agent (robust)

Location: workspace-agent.service.ts:947-965

function tryParseJsonPayload(raw: string): Record<string, unknown> | null {
  let repaired: string | null = null;
  try { repaired = jsonrepair(raw); } catch {}
  const candidates = [raw, repaired, closeOpenJsonContainers(raw),
                      repaired && closeOpenJsonContainers(repaired)];
  for (const candidate of candidates) {
    if (!candidate) continue;
    try { const parsed = JSON.parse(candidate); ... } catch {}
  }
  return null;
}

4-candidate waterfall: raw → jsonrepair → bracket-closing → combined. Retries up to 2 protocol repair rounds + 2 verification rounds.

Download agents (minimal)

Location: agent-executor.ts:2979-2985

function repairJson(str: string): string {
  try { JSON.parse(str); return str; }
  catch { return stripTrailingCommas(stripJsonRepairTokens(str)); }
}

Single-pass: tries parse, then strips comments/ellipsis + trailing commas. No quote fixing, no bracket closing, no structural repair. 1 internal retry with a generic reminder prompt, plus 1 route-level auto-retry that re-executes the entire agent (with its own internal retry).

What the agents' repair fixes vs misses

Malformed JSON pattern Workspace agent Download agents
Trailing commas: {"a": 1,} ✅ ✅
// and /* */ comments ✅ ✅
... ellipsis placeholders ✅ ✅
Single quotes: {'key': 'val'} ✅ ❌
Unquoted keys: {key: "val"} ✅ ❌
Missing closing brackets: {"a": { ✅ (closeOpenJsonContainers) ❌
Unescaped control characters ✅ ❌
Mixed structural issues ✅ (4-candidate waterfall) ❌

Affected agents

All agents in the JSON_AGENTS set (agent-executor.ts:2894-2915):

lorebook-keeper, card-evolution-auditor, world-state, prose-guardian, continuity, director, expression, echo-chamber, quest, illustrator, combat, background, character-tracker, persona-stats, custom-tracker, about-me-keeper, html, spotify, haptic, cyoa

Most impacted: Lorebook Keeper and Card Evolution Auditor — both request complex nested JSON with arrays of objects, which are particularly vulnerable to truncation and MoE formatting issues.

Real-world failure mode

  1. User enables Lorebook Keeper agent in chat settings
  2. After 8 messages (runInterval: 8), agent fires
  3. Model (e.g., Deepseek via NanoGPT) produces JSON with single quotes or a trailing comma after a truncation
  4. extractJson() extracts the JSON from fences
  5. repairJson() strips comments and trailing commas but can't fix single quotes
  6. JSON.parse() fails → { parseError: true }
  7. One internal retry with generic reminder → model produces similar output → fails again
  8. Route-level auto-retry fires (shouldAutomaticallyRetryAgentResult returns true for non-timeout failures) — the agent executes a second time, with its own internal retry again
  9. If all retries (2 agent calls × 2 internal retries = 4 LLM attempts) still fail → agents_retry_failed SSE event → toast: "Lorebook Keeper failed: Invalid response. Use Retry Failed Agents in the Agents menu to try again."
  10. If manual retry also fails, lorebook entries are lost — no degraded fallback or partial-write recovery exists. The persistence logic at generate.routes.ts:8425 gates on result.success === true.

Proposed solution

Option A: Share the workspace agent's repair pipeline (recommended)

Extract tryParseJsonPayload and closeOpenJsonContainers into a shared utility module (e.g., packages/server/src/lib/json-repair.ts). Both the workspace agent and agent executor import from it.

The jsonrepair library is already a dependency of packages/server. No new dependencies needed.

Option B: Upgrade repairJson() in place

Add single-quote fixing and bracket-closing to the existing repairJson() function. Less clean than sharing, but lower blast radius.

Option C: Increase retry budget for JSON agents

Currently 1 internal retry (+ 1 route-level auto-retry = 2 agent calls total). Increase the internal retry budget to 2-3 for agents in the JSON_AGENTS set. This doesn't fix the repair quality but gives the model more chances.

Recommended: Option A + C combined. Share the robust repair pipeline AND increase retries to 2 for JSON agents.

Truncation recovery gap (complementary issue)

When a model hits maxTokens mid-JSON (finish_reason: "length"), the workspace agent detects it at line 1964 but just breaks with a warning — no attempt to parse the truncated output with closeOpenJsonContainers. The truncation detection and the repair pipeline are disconnected.

The download agents have the same gap: extractJson() tries fence extraction + repairJson(), but neither attempts to close open brackets on truncated output. A truncated {"updates": [{"action": "create", "name": "Foo" would fail parse even though closing }]} would produce valid JSON.

Adding bracket-closing to the agent's extractJson() function would recover a significant class of truncation failures without any model retry.

Alternatives considered

  • Force all agents to use structured tool calls — ideal long-term, but agents are defined as prompt-only JSON (no tool schemas). The prompt asks for raw JSON, not tool-call format.
  • Use JSON Schema validation + retry — validate the parsed output against the expected schema and retry with specific error feedback. More work but more robust than generic "return valid JSON" reminders.
  • Add jsonrepair as a dependency to Marinara-Agents — agents are pure JSON definitions, no runtime code. The repair runs in the Engine, not in the agent package.
  • #4741 (Model catalog gaps): Incorrect maxOutput causes truncation mid-JSON, which is a separate failure mode from malformed-but-complete JSON. The catalog fix reduces truncation-induced parse failures, but does NOT fix MoE/quantized model failures where the JSON is structurally malformed despite having adequate token budget. Fixed in staging.

Additional context

  • The agent retry prompt (buildInvalidJsonRetryMessages at line 1604) sends the first 4000 chars of the failed response back as context. For truncated output, this includes the incomplete JSON — which may help the model understand what went wrong, but the repair still can't salvage it.
  • The agentResponseIsJson check (line 2887) uses the JSON_AGENTS set for hard-coded agent types, plus a heuristic for custom agents (!TEXT_RESULT_TYPES.has(resultType)). Custom agents that return structured JSON also get the weak repair.
  • The workspace agent's jsonrepair import is at line 9: import { jsonrepair } from "jsonrepair". The agent executor has no such import.

Research undertaken: analysis of agent-executor.ts (parseAgentResponse at lines 2935-2960, extractJson at lines 2962-2976, repairJson at lines 2979-2985, stripTrailingCommas at lines 2988-3022, stripJsonRepairTokens at lines 3024-3073, JSON_AGENTS set at lines 2894-2915, retry logic at lines 795-848, buildInvalidJsonRetryMessages at lines 1604-1622), workspace-agent.service.ts (tryParseJsonPayload at lines 947-965, closeOpenJsonContainers at lines 914-945, jsonrepair import at line 9). Compared repair capabilities of jsonrepair@3.15.0 (npm library, full JSON repair) vs custom repairJson() pipeline (~90 lines total across repairJson, stripTrailingCommas, and stripJsonRepairTokens — trailing commas, comments, and ellipsis only). Confirmed both Lorebook Keeper and Card Evolution Auditor are in the JSON_AGENTS set and request complex nested JSON structures from their prompt templates. Traced the full lorebook-keeper failure path: parseAgentResponse → shouldFailInvalidJsonResult → internal retry → shouldAutomaticallyRetryAgentResult at route level → agents_retry_failed SSE → toast notification. Entries are lost only after all retries exhaust (not silently dropped).

Originally created by @xDanteMD on GitHub (Aug 8, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/4753 Originally assigned to: @SpicyMarinara on GitHub. ## What problem does this solve? Download agents (Lorebook Keeper, Card Evolution Auditor, and 15+ others) use a minimal `repairJson()` function that only handles trailing commas, comments, and ellipsis. The workspace agent (Professor Mari) uses the full `jsonrepair@3.15.0` library plus a custom `closeOpenJsonContainers()` function. This means the same model producing the same malformed JSON will succeed in the workspace agent but fail in download agents. MoE models (Deepseek, Mimo, Kimi, GLM, etc.) have a known failure mode of producing JSON that is "a little bit off" — single quotes instead of double quotes, unquoted keys, missing closing brackets when truncated. The workspace agent's repair pipeline handles most of these; the agents' repair does not. ## The two repair systems ### Workspace agent (robust) Location: `workspace-agent.service.ts:947-965` ```ts function tryParseJsonPayload(raw: string): Record<string, unknown> | null { let repaired: string | null = null; try { repaired = jsonrepair(raw); } catch {} const candidates = [raw, repaired, closeOpenJsonContainers(raw), repaired && closeOpenJsonContainers(repaired)]; for (const candidate of candidates) { if (!candidate) continue; try { const parsed = JSON.parse(candidate); ... } catch {} } return null; } ``` **4-candidate waterfall:** raw → jsonrepair → bracket-closing → combined. Retries up to 2 protocol repair rounds + 2 verification rounds. ### Download agents (minimal) Location: `agent-executor.ts:2979-2985` ```ts function repairJson(str: string): string { try { JSON.parse(str); return str; } catch { return stripTrailingCommas(stripJsonRepairTokens(str)); } } ``` **Single-pass:** tries parse, then strips comments/ellipsis + trailing commas. No quote fixing, no bracket closing, no structural repair. **1 internal retry** with a generic reminder prompt, plus **1 route-level auto-retry** that re-executes the entire agent (with its own internal retry). ## What the agents' repair fixes vs misses | Malformed JSON pattern | Workspace agent | Download agents | | --- | --- | --- | | Trailing commas: `{"a": 1,}` | ✅ | ✅ | | `//` and `/* */` comments | ✅ | ✅ | | `...` ellipsis placeholders | ✅ | ✅ | | Single quotes: `{'key': 'val'}` | ✅ | ❌ | | Unquoted keys: `{key: "val"}` | ✅ | ❌ | | Missing closing brackets: `{"a": {` | ✅ (`closeOpenJsonContainers`) | ❌ | | Unescaped control characters | ✅ | ❌ | | Mixed structural issues | ✅ (4-candidate waterfall) | ❌ | ## Affected agents All agents in the `JSON_AGENTS` set (`agent-executor.ts:2894-2915`): `lorebook-keeper`, `card-evolution-auditor`, `world-state`, `prose-guardian`, `continuity`, `director`, `expression`, `echo-chamber`, `quest`, `illustrator`, `combat`, `background`, `character-tracker`, `persona-stats`, `custom-tracker`, `about-me-keeper`, `html`, `spotify`, `haptic`, `cyoa` **Most impacted:** Lorebook Keeper and Card Evolution Auditor — both request complex nested JSON with arrays of objects, which are particularly vulnerable to truncation and MoE formatting issues. ## Real-world failure mode 1. User enables Lorebook Keeper agent in chat settings 2. After 8 messages (`runInterval: 8`), agent fires 3. Model (e.g., Deepseek via NanoGPT) produces JSON with single quotes or a trailing comma after a truncation 4. `extractJson()` extracts the JSON from fences 5. `repairJson()` strips comments and trailing commas but can't fix single quotes 6. `JSON.parse()` fails → `{ parseError: true }` 7. One internal retry with generic reminder → model produces similar output → fails again 8. Route-level auto-retry fires (`shouldAutomaticallyRetryAgentResult` returns true for non-timeout failures) — the agent executes a second time, with its own internal retry again 9. If all retries (2 agent calls × 2 internal retries = 4 LLM attempts) still fail → `agents_retry_failed` SSE event → toast: *"Lorebook Keeper failed: Invalid response. Use Retry Failed Agents in the Agents menu to try again."* 10. If manual retry also fails, lorebook entries are lost — no degraded fallback or partial-write recovery exists. The persistence logic at `generate.routes.ts:8425` gates on `result.success === true`. ## Proposed solution **Option A: Share the workspace agent's repair pipeline (recommended)** Extract `tryParseJsonPayload` and `closeOpenJsonContainers` into a shared utility module (e.g., `packages/server/src/lib/json-repair.ts`). Both the workspace agent and agent executor import from it. The `jsonrepair` library is already a dependency of `packages/server`. No new dependencies needed. **Option B: Upgrade `repairJson()` in place** Add single-quote fixing and bracket-closing to the existing `repairJson()` function. Less clean than sharing, but lower blast radius. **Option C: Increase retry budget for JSON agents** Currently 1 internal retry (+ 1 route-level auto-retry = 2 agent calls total). Increase the internal retry budget to 2-3 for agents in the `JSON_AGENTS` set. This doesn't fix the repair quality but gives the model more chances. **Recommended: Option A + C combined.** Share the robust repair pipeline AND increase retries to 2 for JSON agents. ## Truncation recovery gap (complementary issue) When a model hits `maxTokens` mid-JSON (finish_reason: "length"), the workspace agent detects it at line 1964 but **just breaks with a warning** — no attempt to parse the truncated output with `closeOpenJsonContainers`. The truncation detection and the repair pipeline are disconnected. The download agents have the same gap: `extractJson()` tries fence extraction + `repairJson()`, but neither attempts to close open brackets on truncated output. A truncated `{"updates": [{"action": "create", "name": "Foo"` would fail parse even though closing `}]}` would produce valid JSON. Adding bracket-closing to the agent's `extractJson()` function would recover a significant class of truncation failures without any model retry. ## Alternatives considered - **Force all agents to use structured tool calls** — ideal long-term, but agents are defined as prompt-only JSON (no tool schemas). The prompt asks for raw JSON, not tool-call format. - **Use JSON Schema validation + retry** — validate the parsed output against the expected schema and retry with specific error feedback. More work but more robust than generic "return valid JSON" reminders. - **Add jsonrepair as a dependency to Marinara-Agents** — agents are pure JSON definitions, no runtime code. The repair runs in the Engine, not in the agent package. ## Related issues - **#4741 (Model catalog gaps):** Incorrect `maxOutput` causes truncation mid-JSON, which is a *separate* failure mode from malformed-but-complete JSON. The catalog fix reduces truncation-induced parse failures, but does NOT fix MoE/quantized model failures where the JSON is structurally malformed despite having adequate token budget. Fixed in staging. ## Additional context - The agent retry prompt (`buildInvalidJsonRetryMessages` at line 1604) sends the first 4000 chars of the failed response back as context. For truncated output, this includes the incomplete JSON — which may help the model understand what went wrong, but the repair still can't salvage it. - The `agentResponseIsJson` check (line 2887) uses the `JSON_AGENTS` set for hard-coded agent types, plus a heuristic for custom agents (`!TEXT_RESULT_TYPES.has(resultType)`). Custom agents that return structured JSON also get the weak repair. - The workspace agent's `jsonrepair` import is at line 9: `import { jsonrepair } from "jsonrepair"`. The agent executor has no such import. --- *Research undertaken: analysis of `agent-executor.ts` (parseAgentResponse at lines 2935-2960, extractJson at lines 2962-2976, repairJson at lines 2979-2985, stripTrailingCommas at lines 2988-3022, stripJsonRepairTokens at lines 3024-3073, JSON_AGENTS set at lines 2894-2915, retry logic at lines 795-848, buildInvalidJsonRetryMessages at lines 1604-1622), `workspace-agent.service.ts` (tryParseJsonPayload at lines 947-965, closeOpenJsonContainers at lines 914-945, jsonrepair import at line 9). Compared repair capabilities of `jsonrepair@3.15.0` (npm library, full JSON repair) vs custom `repairJson()` pipeline (~90 lines total across `repairJson`, `stripTrailingCommas`, and `stripJsonRepairTokens` — trailing commas, comments, and ellipsis only). Confirmed both Lorebook Keeper and Card Evolution Auditor are in the JSON_AGENTS set and request complex nested JSON structures from their prompt templates. Traced the full lorebook-keeper failure path: `parseAgentResponse` → `shouldFailInvalidJsonResult` → internal retry → `shouldAutomaticallyRetryAgentResult` at route level → `agents_retry_failed` SSE → toast notification. Entries are lost only after all retries exhaust (not silently dropped).*
Author
Owner

@SpicyMarinara commented on GitHub (Aug 8, 2026):

SpicyMarinara is taking this in the current assigned-issue sweep. I am preparing a focused draft PR against staging and will link it here shortly.

<!-- gh-comment-id:5226819957 --> @SpicyMarinara commented on GitHub (Aug 8, 2026): SpicyMarinara is taking this in the current assigned-issue sweep. I am preparing a focused draft PR against `staging` and will link it here shortly.
Author
Owner

@SpicyMarinara commented on GitHub (Aug 8, 2026):

Implementation is now tracked in draft PR #4761: https://github.com/Pasta-Devs/Marinara-Engine/pull/4761

<!-- gh-comment-id:5226823764 --> @SpicyMarinara commented on GitHub (Aug 8, 2026): Implementation is now tracked in draft PR #4761: https://github.com/Pasta-Devs/Marinara-Engine/pull/4761
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#2614
No description provided.