mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #4753] [Feature]: Agents use weaker JSON repair than workspace agent; upgrading to the workspace approach is prudent #2614
Labels
No labels
android
bug
bugfix
ci
client
code freeze pause
container
dependencies
docs
documentation
duplicate
enhancement
feature
feature
feature
feature-creep
fixed-in-refactor
fixed-in-staging
good first issue
help wanted
in-pr
in-pr
needs-codeowner-decision
normal-scope
old-codebase
old-codebase
pull-request
qol
question
refactor
regression
revisit later
roadmap
scope-risk
scope-risk
server
server
shared
soup
upstream
windows
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Pasta-Devs/Marinara-Engine#2614
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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 fulljsonrepair@3.15.0library plus a customcloseOpenJsonContainers()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-9654-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-2985Single-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
{"a": 1,}//and/* */comments...ellipsis placeholders{'key': 'val'}{key: "val"}{"a": {closeOpenJsonContainers)Affected agents
All agents in the
JSON_AGENTSset (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,cyoaMost 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
runInterval: 8), agent firesextractJson()extracts the JSON from fencesrepairJson()strips comments and trailing commas but can't fix single quotesJSON.parse()fails →{ parseError: true }shouldAutomaticallyRetryAgentResultreturns true for non-timeout failures) — the agent executes a second time, with its own internal retry againagents_retry_failedSSE event → toast: "Lorebook Keeper failed: Invalid response. Use Retry Failed Agents in the Agents menu to try again."generate.routes.ts:8425gates onresult.success === true.Proposed solution
Option A: Share the workspace agent's repair pipeline (recommended)
Extract
tryParseJsonPayloadandcloseOpenJsonContainersinto a shared utility module (e.g.,packages/server/src/lib/json-repair.ts). Both the workspace agent and agent executor import from it.The
jsonrepairlibrary is already a dependency ofpackages/server. No new dependencies needed.Option B: Upgrade
repairJson()in placeAdd 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_AGENTSset. 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
maxTokensmid-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 withcloseOpenJsonContainers. 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
Related issues
maxOutputcauses 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
buildInvalidJsonRetryMessagesat 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.agentResponseIsJsoncheck (line 2887) uses theJSON_AGENTSset 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.jsonrepairimport 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 ofjsonrepair@3.15.0(npm library, full JSON repair) vs customrepairJson()pipeline (~90 lines total acrossrepairJson,stripTrailingCommas, andstripJsonRepairTokens— 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 →shouldAutomaticallyRetryAgentResultat route level →agents_retry_failedSSE → toast notification. Entries are lost only after all retries exhaust (not silently dropped).@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
stagingand will link it here shortly.@SpicyMarinara commented on GitHub (Aug 8, 2026):
Implementation is now tracked in draft PR #4761: https://github.com/Pasta-Devs/Marinara-Engine/pull/4761