[GH-ISSUE #2792] [Issue]: OpenAI-compatible tool calls leak as raw text / repeat-loop on models that emit a non-native format (sidecar + Custom llama.cpp/LM Studio/KoboldCPP + remote GLM/DeepSeek) — no textual tool-call fallback; Mari & agents can't … #1417

Closed
opened 2026-10-21 05:33:28 +07:00 by bsakaguchi · 8 comments
Owner

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

Summary

Tool calls do not work for OpenAI-compatible backends whose model emits a non-native tool-call format in 2.0.0. This is not limited to the bundled llama.cpp sidecar — it also affects Custom (OAI-Compatible) connections pointed at llama.cpp, LM Studio, and KoboldCPP, and remote models that free-text their tool calls such as GLM 5 / 5.1 / 5.2 and DeepSeek v4 (via Custom OAI / OpenRouter / Zhipu / DeepSeek) — all confirmed via user reports + code, including a controlled test at temperature 0 in a fresh chat that still fails (so it is a format/parsing problem, not sampling or context). The underlying defect is that the OpenAI-compatible provider has no textual tool-call fallback, so any backend that returns its tool call as the model's trained/free-text format (instead of native tool_calls JSON) has the call leaked into the chat as text — and, on the Professor Mari path, can spiral into a visible repeat-loop of the reasoning preamble (see fix 4/5).

Symptoms by path:

  • Home-screen Professor Mari workspace: the model's tool call leaks into the chat as raw text (e.g. a piped toolcall token wrapper or a tool_code block) instead of executing and rendering as a tool pill. Occasionally — when the model happens to emit exactly the JSON shape Mari asks for — it works and renders a pill, which makes the bug look intermittent.
  • Regular in-chat assistant / agents:
    • With the bundled sidecar, it hard-errors with "Local sidecar native tool calls are disabled" the moment a tool is offered.
    • With a Custom OAI connection (llama.cpp / LM Studio / KoboldCPP), there is no such gate, so it silently leaks the textual call as content instead of erroring.

This is a regression: the same Gemma + llama.cpp setup tool-calls fine in SillyTavern/Cline (which parse llama.cpp's native textual tool-call format), and worked in 1.6.1, which had neither of the two gating mechanisms introduced in the 2.0 cycle.

Symptom & UX impact

  • Professor Mari "list my characters" / any mari_db-triggering request prints the model's internal tool-call token as a normal assistant message. No tool runs, no data comes back.
  • Because no tool result is fed back into the loop, the agent re-asks and the model repeats the same malformed call — at low temperature the model adheres more strongly to its trained format, which makes repeat loops worse, not better.
  • "Naked" think sections leak for the same reason (model-native output passed straight through).
  • On the main assistant/agents path: the bundled sidecar is dead on arrival (throws before generation); Custom local connections silently leak the call as text.
  • Net effect: every tool-dependent local feature (Professor Mari workspace tools, agent tools) is unusable on a local install — bundled sidecar or a self-hosted llama.cpp / LM Studio / KoboldCPP behind a Custom connection.

Steps to reproduce

Bundled sidecar:

  1. Enable the bundled local AI model (llama.cpp sidecar) with a Gemma 3/4-class GGUF. Leave Native Tool Calls off (default — enableNativeToolCalls: false).
  2. Home screen → ask Professor Mari "list my characters" (triggers mari_db). Observed: the model's tool-call token leaks as a normal Mari message; no pill, no tool result. (Occasionally a request where the model emits exactly {"tool_calls":[{"name":"…","arguments":{…}}]} renders correctly as a pill.)
  3. Regular chat with the same local connection, give the assistant/an agent a tool. Observed: throws "Local sidecar native tool calls are disabled…".
  4. Lower the temperature and retry — the model adheres more strongly to its trained format and falls into a repeat loop.

Custom (OAI-Compatible) connection — llama.cpp / LM Studio / KoboldCPP:

  1. Create a Custom (OAI-Compatible) connection with the Base URL of a self-hosted llama.cpp llama-server (started without --jinja + a tool template), LM Studio, or KoboldCPP. (Setting "treat as local endpoint" routes Mari through the JSON protocol; either way the native path has no textual fallback.)
  2. Ask Professor Mari, or use an agent/assistant tool, in a chat on that connection.
  3. Observed: the tool call leaks into the chat as raw text (<|tool_call>…, <tool_code>…, or malformed JSON); no pill, no tool result, no error.

Root cause (file:line trace)

Two distinct, mutually reinforcing failures — both reachable by Custom local connections, not just the sidecar.

A. Professor Mari workspace path: brittle JSON-only tool-call parser (the leak)

MARI_SYSTEM_PROMPT is hardcoded at packages/server/src/services/professor-mari/workspace-agent.service.ts:215.

The JSON-only protocol is gated on a local flag, not on "is sidecar":

// workspace-agent.service.ts:511-513
function shouldUseJsonToolProtocol(connection: WorkspaceConnection): boolean {
  return isLocalSidecarConnection(connection) || bool(connection.treatAsLocalEndpoint);
}

treatAsLocalEndpoint is a real per-connection flag (packages/server/src/db/schema/connections.ts:66, default "false") that users enable for Custom local endpoints. So a Custom OAI connection with "treat as local" on routes through the same runJsonToolProtocol (workspace-agent.service.ts:1119-1129) as the sidecar.

runJsonToolProtocol injects jsonToolProtocolInstruction (:515-531) asking the model to emit {"tool_calls":[{"name":…,"arguments":{}}]}, then parses with parseJsonToolProtocolCalls (:565), which is brittle:

  • extractJsonToolPayload (:533-554) only accepts the whole trimmed string as JSON, a fenced ```json block, or the substring between the first { and last }.
  • rawJsonToolCalls (:556-563) only recognizes tool_calls / toolCalls / calls / tool_call / toolCall, or a top-level name.

llama.cpp / LM Studio / Kobold GGUFs emit their trained format instead (a piped toolcall token wrapper, a tool_code block, or function-call XML). The first-to-last-brace slice yields an object whose only key is e.g. command: it JSON-parses but has no name/tool_calls, so the parser returns [], and:

// workspace-agent.service.ts:603-605
const toolCalls = parseJsonToolProtocolCalls(result.content ?? "", tools);
if (toolCalls.length === 0) return result;          // returns raw model text UNCHANGED
return { ...result, content: null, toolCalls, finishReason: "tool_calls" };

The raw text is then rendered/persisted via pushTextDelta (:1131). No fallback recognizes textual/native-token formats.

B. Main assistant / agents path: OAI-compatible provider only assembles native tool_calls (no textual fallback)

  • Non-streaming: packages/server/src/services/llm/providers/openai.provider.ts:1219 — normalizeToolCalls(choice?.message?.tool_calls) only.
  • Streaming: openai.provider.ts:1333-1377 — assembles only from delta.tool_calls.
  • There is no path that inspects message content for a textual tool call (<|tool_call>…<tool_call|>, <tool_code>, fenced ```json, or bare top-level JSON). So for any OAI-compatible local backend returning its tool call as content, toolCalls is empty and the call leaks as text. This is provider-wide and applies to every Custom OAI connection, not just the sidecar.

Sidecar-only gate (why sidecar throws but Custom leaks):

  • SIDECAR_DEFAULT_CONFIG.enableNativeToolCalls is false — packages/shared/src/types/sidecar.ts:293.
  • buildLlamaArgs only appends --jinja (which makes the bundled llama-server expose OpenAI-compatible tool calls) when that flag is on — packages/server/src/services/sidecar/sidecar-launch-plan.ts:35-38.
  • assertToolCallsAvailable throws when tools are requested with the flag off — packages/server/src/services/llm/providers/local-sidecar.provider.ts:39-43. This is sidecar-only. A Custom connection has no such gate, so it does not error — it silently leaks (matches the Custom-connection reports).

Per-backend nuance:

  • llama.cpp (llama-server) only exposes native tool_calls when launched with --jinja and a chat template matching the model's tool format. A user's own server (Custom connection) usually isn't started that way → textual leak.
  • KoboldCPP generally emits the model's raw text for tools (no native envelope) → leak.
  • LM Studio does native tool calls for some models/templates and falls back to text for others → intermittent, model-dependent leak.

Why this is a regression from 1.6.1

Both gating mechanisms are new in the 2.0 cycle: the native-tool gate + --jinja plumbing (commit c29ed255, #2646) and the runJsonToolProtocol / extractJsonToolPayload / shouldUseJsonToolProtocol scaffolding (commit caca4e0d). 1.6.1 had neither. The same setups that tool-call fine in Cline/SillyTavern (which parse the native textual format) now leak (Mari + Custom) or throw (sidecar agents). The "works at exact JSON, repeats at low temp" symptom is consistent: when the model complies with the requested JSON it parses; when it falls back to its trained format the call is returned as content with no result fed back, so the loop re-asks and repeats the malformed call.

Suggested fix

(1) Primary — a tolerant textual tool-call fallback, homed in the OpenAI-compatible provider so it covers ALL local OAI backends.
Add a shared parser that, when native tool_calls is empty but content contains a recognizable tool call, parses it and surfaces it as a toolCalls result. Wire it into the OAI provider's tool-call assembly (openai.provider.ts:1219 non-streaming and :1333-1377 streaming) and share it with Mari's runJsonToolProtocol (workspace-agent.service.ts:603). Recognize, in order:

  1. native tool_calls JSON (current behavior),
  2. the piped toolcall token form (<|tool_call> … optional call: prefix, tool name, optional brace object … <tool_call|>),
  3. tool_code blocks,
  4. fenced ```json blocks,
  5. bare name + arguments / tool objects,
  6. XML-ish <tool_call>…</tool_call> / <tool_call>…</arg_value> wrappers (tolerant of mismatched close tags) around a command-style payload — e.g. DeepSeek/GLM emit <tool_call>mari db tables</arg_value>; map the leading token to the matching tool (mari_db) and the remainder to its args ({command: "tables"} / {args: "db tables"}),

parsing arguments leniently and matching captured names against the known tool set. Only return raw text when no known tool name matches (so plain prose is unaffected). Sketch:

function parseToolCallsTolerant(content: string, tools: LLMToolDefinition[]): LLMToolCall[] {
  const known = new Set(tools.map((t) => t.function.name));
  const json = parseJsonToolProtocolCalls(content, tools); // existing
  if (json.length) return json;
  const calls: LLMToolCall[] = [];
  for (const cand of extractTextualToolCandidates(content)) { // <|tool_call>, tool_code, XML, bare name+args
    if (known.has(cand.name)) {
      calls.push({ id: makeId(), type: "function", function: { name: cand.name, arguments: JSON.stringify(cand.args ?? {}) } });
    }
  }
  return calls;
}

(2) Secondary — stop the bundled sidecar agent path being dead on arrival.
Replace the hard throw at local-sidecar.provider.ts:39-43 with auto-passing --jinja when a request carries tools (or default enableNativeToolCalls to true, sidecar.ts:293), paired with the tolerant parser above so non-conforming models degrade gracefully rather than throwing.

(3) Alignment.
Prefer native jinja tool calls for templated models (what Cline/ST use), reserving the custom JSON protocol for backends with no working template — always paired with the tolerant fallback so trained-format output is recognized regardless of connection type.

(4) Force greedy/low sampling for the Mari JSON-protocol tool turn (fixes the GLM/remote repeat-loop).
runJsonToolProtocol runs the tool-call generation at the user's RP temperature — provider.chatComplete(fallbackMessages, { ...baseOptions, stream: false }) (workspace-agent.service.ts:602) — with no override. At high temp (e.g. GLM @ 0.8) the model free-texts its reasoning preamble and degenerates into a repeat loop ("Let me find Portia's character and any linked lorebooks." ×N) instead of committing to the tool JSON. Override temperature: 0 (and topP: 1) for that single tool-protocol generation, mirroring how the local-sidecar provider already forces greedy sampling for structured output. This applies to remote OAI models too (GLM / DeepSeek via Custom OAI / OpenRouter / Zhipu), not just local backends. Caveat (confirmed by a temp-0 + fresh-chat test): this is necessary but not sufficient — DeepSeek/GLM still emit their trained <tool_call>…</arg_value> format at temp 0, so fix (1) [tolerant parser] and preferring native tool-calling for capable providers are the load-bearing fixes; (4) only improves format compliance at the margin.

(5) Add a repeat / no-progress guard.
When a tool turn yields no parseable tool call (or the model repeats the same preamble), stop and surface an error / fall back rather than letting it spiral into the visible repeat loop. This bounds the degeneration even for models whose output the tolerant parser still cannot recognize.

Alternatives considered: tightening the Mari prompt (rejected — does not control what the model emits; leak persists on trained-format fallback); only flipping enableNativeToolCalls (rejected as sole fix — does not help Custom connections or models whose native output differs from strict OpenAI JSON, and leaves the OAI provider with no textual fallback).

Affected files

  • packages/server/src/services/llm/providers/openai.provider.ts (:1219, :1333-1377) — primary home for the textual fallback (covers Custom OAI connections + sidecar + agents)
  • packages/server/src/services/professor-mari/workspace-agent.service.ts (:215, :511-513, :515-531, :533-563, :565-584, :586-606, :1119-1131)
  • packages/server/src/services/llm/providers/local-sidecar.provider.ts (:31-43)
  • packages/server/src/services/sidecar/sidecar-launch-plan.ts (:35-38)
  • packages/shared/src/types/sidecar.ts (:293)
  • packages/server/src/db/schema/connections.ts (:66 — treatAsLocalEndpoint)

Validation

  • pnpm check passes (TypeScript + ESLint).
  • Add parser regression tests: (a) the piped <|tool_call> token form, (b) a tool_code block, (c) a fenced ```json block — each asserting exactly one tool call is produced.
  • Add a test asserting plain prose (no tool intent) still returns text unchanged (no false-positive tool calls).
  • Manually verify with the bundled sidecar + Gemma 3/4 GGUF: Professor Mari "list my characters" returns a tool pill + real data, not leaked text.
  • Manually verify with a Custom (OAI-Compatible) connection to llama.cpp (no --jinja): tool calls execute (pill + result), not leaked text.
  • Manually verify with a Custom connection to LM Studio and to KoboldCPP: tool calls execute.
  • Manually verify the bundled-sidecar agents path can call a tool without throwing "native tool calls are disabled".
  • Manually verify low-temperature runs no longer fall into a repeat-call loop.
  • Manually verify tool-call pills render correctly in group-chat bubbles and on a mobile viewport.

AI-investigated against released 2.0.0 (main); verify before fixing. Scope expanded from the original (sidecar-only) framing after a user reported the same failure on Custom connections to llama.cpp / LM Studio / KoboldCPP.

Originally created by @kolacheee on GitHub (Jun 22, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2792 ## Summary Tool calls do not work for **OpenAI-compatible backends whose model emits a non-native tool-call format** in 2.0.0. This is **not** limited to the bundled llama.cpp sidecar — it also affects **Custom (OAI-Compatible) connections** pointed at **llama.cpp, LM Studio, and KoboldCPP**, and **remote** models that free-text their tool calls such as **GLM 5 / 5.1 / 5.2** and **DeepSeek v4** (via Custom OAI / OpenRouter / Zhipu / DeepSeek) — all confirmed via user reports + code, including a controlled test at **temperature 0 in a fresh chat** that still fails (so it is a format/parsing problem, not sampling or context). The underlying defect is that the OpenAI-compatible provider has **no textual tool-call fallback**, so any backend that returns its tool call as the model's *trained/free-text format* (instead of native `tool_calls` JSON) has the call leaked into the chat as text — and, on the Professor Mari path, can spiral into a visible repeat-loop of the reasoning preamble (see fix 4/5). Symptoms by path: - **Home-screen Professor Mari workspace:** the model's tool call **leaks into the chat as raw text** (e.g. a piped `toolcall` token wrapper or a `tool_code` block) instead of executing and rendering as a tool pill. Occasionally — when the model happens to emit exactly the JSON shape Mari asks for — it works and renders a pill, which makes the bug look intermittent. - **Regular in-chat assistant / agents:** - With the **bundled sidecar**, it **hard-errors** with "Local sidecar native tool calls are disabled" the moment a tool is offered. - With a **Custom OAI connection** (llama.cpp / LM Studio / KoboldCPP), there is no such gate, so it **silently leaks** the textual call as content instead of erroring. This is a regression: the same Gemma + llama.cpp setup tool-calls fine in SillyTavern/Cline (which parse llama.cpp's native textual tool-call format), and worked in 1.6.1, which had neither of the two gating mechanisms introduced in the 2.0 cycle. ## Symptom & UX impact - Professor Mari "list my characters" / any `mari_db`-triggering request prints the model's internal tool-call token as a normal assistant message. No tool runs, no data comes back. - Because no tool result is fed back into the loop, the agent re-asks and the model **repeats the same malformed call** — at low temperature the model adheres more strongly to its trained format, which makes repeat loops worse, not better. - "Naked" think sections leak for the same reason (model-native output passed straight through). - On the main assistant/agents path: the **bundled sidecar** is dead on arrival (throws before generation); **Custom local connections** silently leak the call as text. - Net effect: every tool-dependent local feature (Professor Mari workspace tools, agent tools) is unusable on a local install — bundled sidecar **or** a self-hosted llama.cpp / LM Studio / KoboldCPP behind a Custom connection. ## Steps to reproduce **Bundled sidecar:** 1. Enable the bundled local AI model (llama.cpp sidecar) with a Gemma 3/4-class GGUF. Leave **Native Tool Calls** off (default — `enableNativeToolCalls: false`). 2. Home screen → ask Professor Mari "list my characters" (triggers `mari_db`). Observed: the model's tool-call token leaks as a normal Mari message; no pill, no tool result. (Occasionally a request where the model emits exactly `{"tool_calls":[{"name":"…","arguments":{…}}]}` renders correctly as a pill.) 3. Regular chat with the same local connection, give the assistant/an agent a tool. Observed: throws "Local sidecar native tool calls are disabled…". 4. Lower the temperature and retry — the model adheres more strongly to its trained format and falls into a repeat loop. **Custom (OAI-Compatible) connection — llama.cpp / LM Studio / KoboldCPP:** 1. Create a Custom (OAI-Compatible) connection with the Base URL of a self-hosted llama.cpp `llama-server` (started without `--jinja` + a tool template), LM Studio, or KoboldCPP. (Setting "treat as local endpoint" routes Mari through the JSON protocol; either way the native path has no textual fallback.) 2. Ask Professor Mari, or use an agent/assistant tool, in a chat on that connection. 3. Observed: the tool call leaks into the chat as raw text (`<|tool_call>…`, `<tool_code>…`, or malformed JSON); no pill, no tool result, no error. ## Root cause (file:line trace) Two distinct, mutually reinforcing failures — both reachable by Custom local connections, not just the sidecar. ### A. Professor Mari workspace path: brittle JSON-only tool-call parser (the leak) `MARI_SYSTEM_PROMPT` is hardcoded at `packages/server/src/services/professor-mari/workspace-agent.service.ts:215`. The JSON-only protocol is gated on a **local** flag, not on "is sidecar": ```ts // workspace-agent.service.ts:511-513 function shouldUseJsonToolProtocol(connection: WorkspaceConnection): boolean { return isLocalSidecarConnection(connection) || bool(connection.treatAsLocalEndpoint); } ``` `treatAsLocalEndpoint` is a real per-connection flag (`packages/server/src/db/schema/connections.ts:66`, default `"false"`) that users enable for Custom local endpoints. So **a Custom OAI connection with "treat as local" on routes through the same `runJsonToolProtocol`** (`workspace-agent.service.ts:1119-1129`) as the sidecar. `runJsonToolProtocol` injects `jsonToolProtocolInstruction` (`:515-531`) asking the model to emit `{"tool_calls":[{"name":…,"arguments":{}}]}`, then parses with `parseJsonToolProtocolCalls` (`:565`), which is brittle: - `extractJsonToolPayload` (`:533-554`) only accepts the whole trimmed string as JSON, a fenced ```` ```json ```` block, or the substring between the **first `{` and last `}`**. - `rawJsonToolCalls` (`:556-563`) only recognizes `tool_calls` / `toolCalls` / `calls` / `tool_call` / `toolCall`, or a top-level `name`. llama.cpp / LM Studio / Kobold GGUFs emit their **trained** format instead (a piped `toolcall` token wrapper, a `tool_code` block, or function-call XML). The first-to-last-brace slice yields an object whose only key is e.g. `command`: it JSON-parses but has no `name`/`tool_calls`, so the parser returns `[]`, and: ```ts // workspace-agent.service.ts:603-605 const toolCalls = parseJsonToolProtocolCalls(result.content ?? "", tools); if (toolCalls.length === 0) return result; // returns raw model text UNCHANGED return { ...result, content: null, toolCalls, finishReason: "tool_calls" }; ``` The raw text is then rendered/persisted via `pushTextDelta` (`:1131`). **No fallback recognizes textual/native-token formats.** ### B. Main assistant / agents path: OAI-compatible provider only assembles *native* `tool_calls` (no textual fallback) - Non-streaming: `packages/server/src/services/llm/providers/openai.provider.ts:1219` — `normalizeToolCalls(choice?.message?.tool_calls)` only. - Streaming: `openai.provider.ts:1333-1377` — assembles only from `delta.tool_calls`. - **There is no path that inspects message `content`** for a textual tool call (`<|tool_call>…<tool_call|>`, `<tool_code>`, fenced ```` ```json ````, or bare top-level JSON). So for any OAI-compatible local backend returning its tool call as content, `toolCalls` is empty and the call **leaks as text**. This is provider-wide and applies to every Custom OAI connection, not just the sidecar. **Sidecar-only gate (why sidecar throws but Custom leaks):** - `SIDECAR_DEFAULT_CONFIG.enableNativeToolCalls` is `false` — `packages/shared/src/types/sidecar.ts:293`. - `buildLlamaArgs` only appends `--jinja` (which makes the bundled `llama-server` expose OpenAI-compatible tool calls) when that flag is on — `packages/server/src/services/sidecar/sidecar-launch-plan.ts:35-38`. - `assertToolCallsAvailable` **throws** when tools are requested with the flag off — `packages/server/src/services/llm/providers/local-sidecar.provider.ts:39-43`. **This is sidecar-only.** A Custom connection has no such gate, so it does not error — it silently leaks (matches the Custom-connection reports). **Per-backend nuance:** - **llama.cpp (`llama-server`)** only exposes native `tool_calls` when launched with `--jinja` *and* a chat template matching the model's tool format. A user's own server (Custom connection) usually isn't started that way → textual leak. - **KoboldCPP** generally emits the model's raw text for tools (no native envelope) → leak. - **LM Studio** does native tool calls for some models/templates and falls back to text for others → intermittent, model-dependent leak. ### Why this is a regression from 1.6.1 Both gating mechanisms are new in the 2.0 cycle: the native-tool gate + `--jinja` plumbing (commit `c29ed255`, #2646) and the `runJsonToolProtocol` / `extractJsonToolPayload` / `shouldUseJsonToolProtocol` scaffolding (commit `caca4e0d`). 1.6.1 had neither. The same setups that tool-call fine in Cline/SillyTavern (which parse the **native textual** format) now leak (Mari + Custom) or throw (sidecar agents). The "works at exact JSON, repeats at low temp" symptom is consistent: when the model complies with the requested JSON it parses; when it falls back to its trained format the call is returned as content with no result fed back, so the loop re-asks and repeats the malformed call. ## Suggested fix **(1) Primary — a tolerant textual tool-call fallback, homed in the OpenAI-compatible provider so it covers ALL local OAI backends.** Add a shared parser that, when native `tool_calls` is empty but `content` contains a recognizable tool call, parses it and surfaces it as a `toolCalls` result. Wire it into the OAI provider's tool-call assembly (`openai.provider.ts:1219` non-streaming and `:1333-1377` streaming) **and** share it with Mari's `runJsonToolProtocol` (`workspace-agent.service.ts:603`). Recognize, in order: 1. native `tool_calls` JSON (current behavior), 2. the piped `toolcall` token form (`<|tool_call>` … optional `call:` prefix, tool name, optional brace object … `<tool_call|>`), 3. `tool_code` blocks, 4. fenced ```` ```json ```` blocks, 5. bare `name` + `arguments` / `tool` objects, 6. **XML-ish `<tool_call>…</tool_call>` / `<tool_call>…</arg_value>` wrappers (tolerant of mismatched close tags) around a *command-style* payload** — e.g. DeepSeek/GLM emit `<tool_call>mari db tables</arg_value>`; map the leading token to the matching tool (`mari_db`) and the remainder to its args (`{command: "tables"}` / `{args: "db tables"}`), parsing arguments leniently and matching captured names against the known tool set. Only return raw text when **no known tool name matches** (so plain prose is unaffected). Sketch: ```ts function parseToolCallsTolerant(content: string, tools: LLMToolDefinition[]): LLMToolCall[] { const known = new Set(tools.map((t) => t.function.name)); const json = parseJsonToolProtocolCalls(content, tools); // existing if (json.length) return json; const calls: LLMToolCall[] = []; for (const cand of extractTextualToolCandidates(content)) { // <|tool_call>, tool_code, XML, bare name+args if (known.has(cand.name)) { calls.push({ id: makeId(), type: "function", function: { name: cand.name, arguments: JSON.stringify(cand.args ?? {}) } }); } } return calls; } ``` **(2) Secondary — stop the bundled sidecar agent path being dead on arrival.** Replace the hard throw at `local-sidecar.provider.ts:39-43` with auto-passing `--jinja` when a request carries tools (or default `enableNativeToolCalls` to `true`, `sidecar.ts:293`), paired with the tolerant parser above so non-conforming models degrade gracefully rather than throwing. **(3) Alignment.** Prefer **native jinja tool calls** for templated models (what Cline/ST use), reserving the custom JSON protocol for backends with no working template — always paired with the tolerant fallback so trained-format output is recognized regardless of connection type. **(4) Force greedy/low sampling for the Mari JSON-protocol tool turn (fixes the GLM/remote repeat-loop).** `runJsonToolProtocol` runs the tool-call generation at the user's RP temperature — `provider.chatComplete(fallbackMessages, { ...baseOptions, stream: false })` (`workspace-agent.service.ts:602`) — with no override. At high temp (e.g. GLM @ 0.8) the model free-texts its reasoning preamble and degenerates into a repeat loop ("*Let me find Portia's character and any linked lorebooks.*" ×N) instead of committing to the tool JSON. Override `temperature: 0` (and `topP: 1`) for that single tool-protocol generation, mirroring how the local-sidecar provider already forces greedy sampling for structured output. This applies to **remote** OAI models too (GLM / DeepSeek via Custom OAI / OpenRouter / Zhipu), not just local backends. **Caveat (confirmed by a temp-0 + fresh-chat test):** this is *necessary but not sufficient* — DeepSeek/GLM still emit their trained `<tool_call>…</arg_value>` format at temp 0, so fix (1) [tolerant parser] and preferring native tool-calling for capable providers are the load-bearing fixes; (4) only improves format compliance at the margin. **(5) Add a repeat / no-progress guard.** When a tool turn yields no parseable tool call (or the model repeats the same preamble), stop and surface an error / fall back rather than letting it spiral into the visible repeat loop. This bounds the degeneration even for models whose output the tolerant parser still cannot recognize. **Alternatives considered:** tightening the Mari prompt (rejected — does not control what the model emits; leak persists on trained-format fallback); only flipping `enableNativeToolCalls` (rejected as sole fix — does not help Custom connections or models whose native output differs from strict OpenAI JSON, and leaves the OAI provider with no textual fallback). ## Affected files - `packages/server/src/services/llm/providers/openai.provider.ts` (`:1219`, `:1333-1377`) — **primary home for the textual fallback (covers Custom OAI connections + sidecar + agents)** - `packages/server/src/services/professor-mari/workspace-agent.service.ts` (`:215`, `:511-513`, `:515-531`, `:533-563`, `:565-584`, `:586-606`, `:1119-1131`) - `packages/server/src/services/llm/providers/local-sidecar.provider.ts` (`:31-43`) - `packages/server/src/services/sidecar/sidecar-launch-plan.ts` (`:35-38`) - `packages/shared/src/types/sidecar.ts` (`:293`) - `packages/server/src/db/schema/connections.ts` (`:66` — `treatAsLocalEndpoint`) ## Validation - [ ] `pnpm check` passes (TypeScript + ESLint). - [ ] Add parser regression tests: (a) the piped `<|tool_call>` token form, (b) a `tool_code` block, (c) a fenced ```` ```json ```` block — each asserting exactly one tool call is produced. - [ ] Add a test asserting plain prose (no tool intent) still returns text unchanged (no false-positive tool calls). - [ ] Manually verify with the bundled sidecar + Gemma 3/4 GGUF: Professor Mari "list my characters" returns a tool pill + real data, not leaked text. - [ ] Manually verify with a **Custom (OAI-Compatible) connection to llama.cpp** (no `--jinja`): tool calls execute (pill + result), not leaked text. - [ ] Manually verify with a **Custom connection to LM Studio** and to **KoboldCPP**: tool calls execute. - [ ] Manually verify the bundled-sidecar agents path can call a tool without throwing "native tool calls are disabled". - [ ] Manually verify low-temperature runs no longer fall into a repeat-call loop. - [ ] Manually verify tool-call pills render correctly in group-chat bubbles and on a mobile viewport. --- *AI-investigated against released 2.0.0 (`main`); verify before fixing. Scope expanded from the original (sidecar-only) framing after a user reported the same failure on Custom connections to llama.cpp / LM Studio / KoboldCPP.*
Author
Owner

@kolacheee commented on GitHub (Jun 22, 2026):

Thanks for the added data point — confirmed, and it widens the root cause. This is not sidecar-specific. The underlying defect is that the OpenAI-compatible provider has no textual tool-call fallback, so it affects every OAI-compatible local backend — the bundled sidecar and a Custom (OAI-Compatible) connection pointed at llama.cpp / LM Studio / KoboldCPP. (Re-verified against the released main tree.)

Why Custom connections are affected too

There are two code paths, and Custom local connections fall into both failure modes:

1. Professor Mari path — the JSON-only protocol gates on a local flag, not on "is sidecar".

  • packages/server/src/services/professor-mari/workspace-agent.service.ts:512
    function shouldUseJsonToolProtocol(connection: WorkspaceConnection): boolean {
      return isLocalSidecarConnection(connection) || bool(connection.treatAsLocalEndpoint);
    }
    
  • treatAsLocalEndpoint is a real per-connection flag (packages/server/src/db/schema/connections.ts:66, default "false") that users set for Custom local endpoints. So a Custom OAI connection with "treat as local" on routes through runJsonToolProtocol and the same brittle parser (extractJsonToolPayload / rawJsonToolCalls, :533-563) that only accepts {"tool_calls":[…]}-shaped JSON. llama.cpp / Kobold / LM Studio emitting their trained textual format (<|tool_call> token, tool_code block, function-call XML) → parser returns [] → raw text is returned unchanged (:603-605) and rendered as a Mari message. Identical leak to the sidecar.
  • And if treatAsLocalEndpoint is off, Mari instead uses the native path below — which has the same gap. Either way it leaks.

2. Main assistant / agents path — the OAI-compatible provider only assembles native tool_calls, with no textual fallback.

  • Non-streaming: packages/server/src/services/llm/providers/openai.provider.ts:1219 — normalizeToolCalls(choice?.message?.tool_calls) only.
  • Streaming: openai.provider.ts:1333-1377 — assembles only from delta.tool_calls.
  • There is no path anywhere that inspects message content for a textual tool call (<|tool_call>…<tool_call|>, <tool_code>, fenced ```json, or bare top-level JSON). So for any OAI-compatible local backend that returns its tool call as content instead of native tool_calls, toolCalls is empty and the call leaks into the chat.
  • Note: the sidecar-only hard error (assertToolCallsAvailable throwing "native tool calls are disabled", local-sidecar.provider.ts:39-43) does not apply to Custom connections — they have no such gate, so they don't error, they just silently leak. That matches this report exactly.

Per-backend nuance

  • llama.cpp (llama-server) only exposes OpenAI-style native tool_calls when launched with --jinja and a chat template that matches the model's tool format. A user's own llama-server (Custom connection) usually isn't started that way, so it returns the model's trained textual format → leaks.
  • KoboldCPP generally emits the model's raw text for tools (no native tool_calls envelope) → leaks.
  • LM Studio can do native tool calls for some models/templates but falls back to textual for others → intermittent leak, model-dependent.

This is why "encourage raw JSON" sometimes works (the model happens to emit the exact shape the parser accepts) and lower temperature makes the repeat-loop worse (stronger adherence to the trained textual format).

Fix — same shape, broader home

The fix from the original write-up still applies, but it should live where it covers all OAI-compatible connections, not just the sidecar/Mari:

  1. Add a tolerant textual tool-call fallback to the OpenAI-compatible provider's tool-call assembly (openai.provider.ts non-streaming :1219 and streaming :1333-1377): when native tool_calls is empty but content contains a recognizable tool call, parse it and surface it as a toolCalls result instead of as text. Recognize the common forms: the <|tool_call>…<tool_call|> token wrapper, <tool_code>…</tool_code>, a fenced ```json block, and a bare top-level JSON object with name/arguments (or tool_calls/tool_call). Share this parser with Mari's runJsonToolProtocol so both paths use one implementation.
  2. Keep the sidecar native path working (default --jinja / enableNativeToolCalls) as the preferred route, but the fallback above is what makes Custom llama.cpp/LM Studio/Kobold connections work without per-user server reconfiguration.

Suggested scope/title update: this is broader than "sidecar" — it's "local OpenAI-compatible tool calls leak as text (sidecar + Custom llama.cpp/LM Studio/KoboldCPP) because the OAI provider has no textual tool-call fallback."

AI-investigated against the released 2.0.0 (main) tree; please verify the traces before fixing.

<!-- gh-comment-id:4771419499 --> @kolacheee commented on GitHub (Jun 22, 2026): > Thanks for the added data point — confirmed, and it widens the root cause. This is **not** sidecar-specific. The underlying defect is that the **OpenAI-compatible provider has no textual tool-call fallback**, so it affects *every* OAI-compatible local backend — the bundled sidecar **and** a Custom (OAI-Compatible) connection pointed at llama.cpp / LM Studio / KoboldCPP. (Re-verified against the released `main` tree.) ## Why Custom connections are affected too There are two code paths, and Custom local connections fall into both failure modes: **1. Professor Mari path — the JSON-only protocol gates on a *local* flag, not on "is sidecar".** - `packages/server/src/services/professor-mari/workspace-agent.service.ts:512` ```ts function shouldUseJsonToolProtocol(connection: WorkspaceConnection): boolean { return isLocalSidecarConnection(connection) || bool(connection.treatAsLocalEndpoint); } ``` - `treatAsLocalEndpoint` is a real per-connection flag (`packages/server/src/db/schema/connections.ts:66`, default `"false"`) that users set for Custom local endpoints. So a **Custom OAI connection with "treat as local" on** routes through `runJsonToolProtocol` and the same brittle parser (`extractJsonToolPayload` / `rawJsonToolCalls`, `:533-563`) that only accepts `{"tool_calls":[…]}`-shaped JSON. llama.cpp / Kobold / LM Studio emitting their trained textual format (`<|tool_call>` token, `tool_code` block, function-call XML) → parser returns `[]` → raw text is returned unchanged (`:603-605`) and rendered as a Mari message. Identical leak to the sidecar. - And if `treatAsLocalEndpoint` is **off**, Mari instead uses the native path below — which has the same gap. Either way it leaks. **2. Main assistant / agents path — the OAI-compatible provider only assembles *native* `tool_calls`, with no textual fallback.** - Non-streaming: `packages/server/src/services/llm/providers/openai.provider.ts:1219` — `normalizeToolCalls(choice?.message?.tool_calls)` only. - Streaming: `openai.provider.ts:1333-1377` — assembles only from `delta.tool_calls`. - There is **no path** anywhere that inspects message `content` for a textual tool call (`<|tool_call>…<tool_call|>`, `<tool_code>`, fenced ```` ```json ````, or bare top-level JSON). So for any OAI-compatible local backend that returns its tool call as **content** instead of native `tool_calls`, `toolCalls` is empty and the call leaks into the chat. - Note: the sidecar-only hard error (`assertToolCallsAvailable` throwing "native tool calls are disabled", `local-sidecar.provider.ts:39-43`) does **not** apply to Custom connections — they have no such gate, so they don't error, they just **silently leak**. That matches this report exactly. ### Per-backend nuance - **llama.cpp (`llama-server`)** only exposes OpenAI-style native `tool_calls` when launched with `--jinja` *and* a chat template that matches the model's tool format. A user's own `llama-server` (Custom connection) usually isn't started that way, so it returns the model's trained textual format → leaks. - **KoboldCPP** generally emits the model's raw text for tools (no native `tool_calls` envelope) → leaks. - **LM Studio** can do native tool calls for some models/templates but falls back to textual for others → intermittent leak, model-dependent. This is why "encourage raw JSON" sometimes works (the model happens to emit the exact shape the parser accepts) and lower temperature makes the repeat-loop worse (stronger adherence to the trained textual format). ## Fix — same shape, broader home The fix from the original write-up still applies, but it should live where it covers **all** OAI-compatible connections, not just the sidecar/Mari: 1. **Add a tolerant textual tool-call fallback to the OpenAI-compatible provider's tool-call assembly** (`openai.provider.ts` non-streaming `:1219` and streaming `:1333-1377`): when native `tool_calls` is empty but `content` contains a recognizable tool call, parse it and surface it as a `toolCalls` result instead of as text. Recognize the common forms: the `<|tool_call>…<tool_call|>` token wrapper, `<tool_code>…</tool_code>`, a fenced ```` ```json ```` block, and a bare top-level JSON object with `name`/`arguments` (or `tool_calls`/`tool_call`). Share this parser with Mari's `runJsonToolProtocol` so both paths use one implementation. 2. **Keep the sidecar native path working** (default `--jinja` / `enableNativeToolCalls`) as the preferred route, but the fallback above is what makes Custom llama.cpp/LM Studio/Kobold connections work without per-user server reconfiguration. Suggested scope/title update: this is broader than "sidecar" — it's **"local OpenAI-compatible tool calls leak as text (sidecar + Custom llama.cpp/LM Studio/KoboldCPP) because the OAI provider has no textual tool-call fallback."** _AI-investigated against the released 2.0.0 (`main`) tree; please verify the traces before fixing._
Author
Owner

@lyrakat commented on GitHub (Jun 22, 2026):

Issue isn't limited to professor mari, nor is it limited to local sidecar. It also affects tool calls in conversations using a local model on the OpenAPI compatible connection (koboldcpp / gemma4 26b)

Image
<!-- gh-comment-id:4771470526 --> @lyrakat commented on GitHub (Jun 22, 2026): Issue isn't limited to professor mari, nor is it limited to local sidecar. It also affects tool calls in conversations using a local model on the OpenAPI compatible connection (koboldcpp / gemma4 26b) <img width="1082" height="306" alt="Image" src="https://github.com/user-attachments/assets/2fa082eb-98a4-4dc5-8b9d-f0de2ae73b22" />
Author
Owner

@lyrakat commented on GitHub (Jun 22, 2026):

Because this issue is related to my work on custom tools for ME I've been poking around it alongside Claude (opus 4.8) and in regards to the issue it also had this to say:

One addition on the streaming path, since the provider-side fallback needs to
cover it or local users who stream will still see leaks even after the parser lands.

Professor Mari's runJsonToolProtocol only works today because it forces
stream: false and parses the full result.content afterward. The general path
(chat() / chatComplete() in openai.provider.ts) streams tokens to the client
as they arrive — so a <tool_code>… / <|tool_call|>… call is emitted into the
chat before the provider can recognize it. Adding a tolerant parser to the final
assembled result fixes the non-streaming case but not this one.

Two ways to handle it:

  • Force non-streaming whenever tools are present on a local / OAI-compatible
    connection (simplest, mirrors Mari), or
  • Buffer/withhold trailing content that could be the start of a textual tool call
    until it can be classified, flushing as visible content only once it's ruled out.

Supporting data point for homing the fix in the provider: a direct, non-streaming
POST /v1/chat/completions to KoboldCPP (Gemma) with tools returns a clean
native tool_calls object for a trivial prompt (finish_reason: tool_calls, empty
content). So the backend is fully capable — the leak appears under heavier prompts,
streaming, or non---jinja configs where the model's trained textual format slips
through. A tolerant fallback at the provider (matched against known tool names) is
robust to all three, which is why the provider is the right home rather than any
single call site.

As for the "twp ways to handle it" I don't think force non-streaming is a good approach, as unless I'm mistaken this would break tool calls in thinking (user message > think > tool call > think more with results > tool call > etc > final reply), though I could be wrong about that.

I am not sure if this is valuable feedback entirely so sorry for that. It's a little over my head.
Also fwiw, my setup is koboldcpp with --jinja and --jinjatools, the most up to date jinja template, gemma4 26b

<!-- gh-comment-id:4771563774 --> @lyrakat commented on GitHub (Jun 22, 2026): Because this issue is related to my work on custom tools for ME I've been poking around it alongside Claude (opus 4.8) and in regards to the issue it also had this to say: > One addition on the **streaming path**, since the provider-side fallback needs to > cover it or local users who stream will still see leaks even after the parser lands. > > Professor Mari's `runJsonToolProtocol` only works today because it forces > `stream: false` and parses the full `result.content` afterward. The general path > (`chat()` / `chatComplete()` in `openai.provider.ts`) streams tokens to the client > as they arrive — so a `<tool_code>…` / `<|tool_call|>…` call is emitted into the > chat *before* the provider can recognize it. Adding a tolerant parser to the final > assembled result fixes the non-streaming case but not this one. > > Two ways to handle it: > - Force non-streaming whenever `tools` are present on a local / OAI-compatible > connection (simplest, mirrors Mari), or > - Buffer/withhold trailing content that could be the start of a textual tool call > until it can be classified, flushing as visible content only once it's ruled out. > > Supporting data point for homing the fix in the provider: a direct, non-streaming > `POST /v1/chat/completions` to KoboldCPP (Gemma) **with `tools`** returns a clean > native `tool_calls` object for a trivial prompt (`finish_reason: tool_calls`, empty > content). So the backend is fully capable — the leak appears under heavier prompts, > streaming, or non-`--jinja` configs where the model's trained textual format slips > through. A tolerant fallback at the provider (matched against known tool names) is > robust to all three, which is why the provider is the right home rather than any > single call site. As for the "twp ways to handle it" I don't think force non-streaming is a good approach, as unless I'm mistaken this would break tool calls in thinking (user message > think > tool call > think more with results > tool call > etc > final reply), though I could be wrong about that. I am not sure if this is valuable feedback entirely so sorry for that. It's a little over my head. Also fwiw, my setup is koboldcpp with --jinja and --jinjatools, the most up to date jinja template, gemma4 26b
Author
Owner

@kolacheee commented on GitHub (Jun 22, 2026):

@lyrakat Thank you for your feedback! The ticket has been updated to reflect the true scope of the issue. Marinara will decide how best to tackle this bug.

<!-- gh-comment-id:4771642099 --> @kolacheee commented on GitHub (Jun 22, 2026): @lyrakat Thank you for your feedback! The ticket has been updated to reflect the true scope of the issue. Marinara will decide how best to tackle this bug.
Author
Owner

@kolacheee commented on GitHub (Jun 22, 2026):

Further data point — this also affects remote models, not just local backends. Multiple users report GLM 5 / 5.1 / 5.2 tool-call failures (and others on the same models report no issue), which is the same root cause as this issue. Confirmed against the released tree.

GLM is the same defect, triggered remotely

Professor Mari on GLM (e.g. GLM 5.2 @ temp 0.8) gets stuck repeating its reasoning preamble — "Let me find Portia's character and any linked lorebooks." over and over — instead of executing the tool:

Image
  • runJsonToolProtocol (workspace-agent.service.ts:586-606) injects the "emit {tool_calls:[…]} JSON" instruction, does one generation, then parses with parseJsonToolProtocolCalls (:565-583), which requires an exact name + known-tool JSON shape.
  • GLM (like Gemma / local models) doesn't reliably emit that exact shape — it free-texts the preamble instead of committing to the tool JSON (or native tool_calls). The parser finds nothing → returns the raw text → no tool result is fed back → the model re-asks / degenerates into the visible repeat loop.

This is the same "works at exact JSON, fails on the model's free-text format" pattern already described here. The expanded scope of this issue ("any OAI-compatible backend whose model emits a non-native tool format") already covers GLM, whether reached via a Custom OAI connection, OpenRouter, or Zhipu's API.

Why some GLM users work and others don't (it is NOT the model version)

Reporters confirm GLM 5, 5.1 and 5.2 all behave the same, so it is not a model-version problem. Two config/runtime variables decide the outcome:

  1. Whether native tool_calls come back. If the GLM connection/proxy returns proper OpenAI tool_calls and Mari uses the native path → works. If GLM free-texts the call (or the connection routes through the JSON protocol) → the no-fallback parser fails.
  2. Sampling temperature. runJsonToolProtocol runs the tool-call turn at the user's temperature — provider.chatComplete(fallbackMessages, { ...baseOptions, stream: false }) at :602 — with no greedy/low-temp override. At temp 0.8 the model is far more likely to free-text and fall into a repetition loop. (Contrast: the local-sidecar provider forces temperature: 0 for structured output; the Mari JSON protocol does not.)

Two fix additions (now folded into the issue body)

On top of the tolerant textual fallback parser already proposed:

  • Force greedy/low sampling for the tool-protocol turn. In runJsonToolProtocol (:602), override temperature: 0 (and topP: 1) for that single generation so the model commits to the tool JSON instead of free-texting at the user's RP temperature.
  • Add a repeat / no-progress guard. When a tool turn yields no parseable tool call (or the model repeats the same preamble), stop and surface an error / fall back rather than letting it spiral into the visible repeat loop.

AI-investigated against the released 2.0.0 (main) tree; verify before fixing.

<!-- gh-comment-id:4772126545 --> @kolacheee commented on GitHub (Jun 22, 2026): > Further data point — this also affects **remote** models, not just local backends. Multiple users report **GLM 5 / 5.1 / 5.2** tool-call failures (and others on the same models report no issue), which is the same root cause as this issue. Confirmed against the released tree. ## GLM is the same defect, triggered remotely Professor Mari on GLM (e.g. GLM 5.2 @ temp 0.8) gets stuck repeating its reasoning preamble — *"Let me find Portia's character and any linked lorebooks."* over and over — instead of executing the tool: <img width="1080" height="2340" alt="Image" src="https://github.com/user-attachments/assets/c5821dc0-9e36-4954-9b55-86f89c54cfed" /> - `runJsonToolProtocol` (`workspace-agent.service.ts:586-606`) injects the "emit `{tool_calls:[…]}` JSON" instruction, does **one** generation, then parses with `parseJsonToolProtocolCalls` (`:565-583`), which requires an exact `name` + known-tool JSON shape. - GLM (like Gemma / local models) doesn't reliably emit that exact shape — it free-texts the preamble instead of committing to the tool JSON (or native `tool_calls`). The parser finds nothing → returns the raw text → **no tool result is fed back** → the model re-asks / degenerates into the visible repeat loop. This is the same "works at exact JSON, fails on the model's free-text format" pattern already described here. The expanded scope of this issue ("any OAI-compatible backend whose model emits a non-native tool format") **already covers GLM**, whether reached via a Custom OAI connection, OpenRouter, or Zhipu's API. ## Why some GLM users work and others don't (it is NOT the model version) Reporters confirm GLM 5, 5.1 and 5.2 all behave the same, so it is not a model-version problem. Two config/runtime variables decide the outcome: 1. **Whether native `tool_calls` come back.** If the GLM connection/proxy returns proper OpenAI `tool_calls` and Mari uses the native path → works. If GLM free-texts the call (or the connection routes through the JSON protocol) → the no-fallback parser fails. 2. **Sampling temperature.** `runJsonToolProtocol` runs the tool-call turn at the **user's** temperature — `provider.chatComplete(fallbackMessages, { ...baseOptions, stream: false })` at `:602` — with **no greedy/low-temp override**. At temp 0.8 the model is far more likely to free-text and fall into a repetition loop. (Contrast: the local-sidecar provider forces `temperature: 0` for structured output; the Mari JSON protocol does not.) ## Two fix additions (now folded into the issue body) On top of the tolerant textual fallback parser already proposed: - **Force greedy/low sampling for the tool-protocol turn.** In `runJsonToolProtocol` (`:602`), override `temperature: 0` (and `topP: 1`) for that single generation so the model commits to the tool JSON instead of free-texting at the user's RP temperature. - **Add a repeat / no-progress guard.** When a tool turn yields no parseable tool call (or the model repeats the same preamble), stop and surface an error / fall back rather than letting it spiral into the visible repeat loop. _AI-investigated against the released 2.0.0 (`main`) tree; verify before fixing._
Author
Owner

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

Addressed in PR #2790 / commit acab1fba: OpenAI-compatible tool requests now use non-streaming completion when tools are present, parse textual tool-call fallbacks, and local sidecar no longer hard-fails when native llama.cpp tool calls are disabled.

<!-- gh-comment-id:4772440965 --> @SpicyMarinara commented on GitHub (Jun 22, 2026): Addressed in PR #2790 / commit acab1fba: OpenAI-compatible tool requests now use non-streaming completion when tools are present, parse textual tool-call fallbacks, and local sidecar no longer hard-fails when native llama.cpp tool calls are disabled.
Author
Owner

@kolacheee commented on GitHub (Jun 22, 2026):

Follow-up test from an affected user — this sharpens the root cause and the fix, and adds DeepSeek 4 as another affected model.

New test data (DeepSeek 4 + GLM, temp 0, fresh chat)

A user re-ran with controlled conditions: temperature 0 and a brand-new chat (to rule out sampling and context pollution). Tool calls still fail to format, on both GLM and DeepSeek v4 Pro. The models emit their trained tool-call format as text, e.g.:

<tool_call>mari db tables</arg_value>
<tool_call>mari --help</arg_value> <tool_call>mari agents --help 2>/dev/null || echo "No agents helper"</arg_value> <tool_call>mari db tables</arg_value>

Two important takeaways:

1. It is purely a FORMAT/PARSING problem — not sampling. Since temp 0 + a fresh chat still fail, the earlier "force greedy sampling" fix (item 4) is necessary but not sufficient: these models simply don't speak the requested JSON protocol regardless of temperature. The tolerant fallback parser (fix 1) is the load-bearing fix.

2. The emitted format is currently 100% unparseable. The protocol asks for {"tool_calls":[{"name":…,"arguments":{}}]} (workspace-agent.service.ts:523-525), and extractJsonToolPayload (:533-554) only looks for JSON — the whole string as JSON, a fenced ```json block, or the substring between the first { and last }. The DeepSeek/GLM output <tool_call>mari db tables</arg_value> contains no { or } at all, so there are zero JSON candidates → extractJsonToolPayload returns null → parseJsonToolProtocolCalls returns [] → the raw text is returned and shown. (GLM then degenerates into the agree/repeat loop; DeepSeek "at least created the agent on text" — both fail to produce a tool call.)

Note the shape: an XML-ish <tool_call>…</arg_value> wrapper (often with mismatched open/close tags) around a command-style invocation (mari db tables), not a JSON args object. The parser needs to handle both the wrapper and the non-JSON payload.

Refined fix priority

  1. Prefer NATIVE tool calling for providers/models that support it (now the top priority for remote models). DeepSeek and GLM via their OpenAI-compatible APIs return proper native tool_calls when the request carries tools and the model's chat template is used. The Mari path forces the custom JSON-text protocol whenever shouldUseJsonToolProtocol is true (isLocalSidecarConnection || treatAsLocalEndpoint, :512), which bypasses native tool calling and fights the model's training. For remote OAI providers that support native tools, route through native tool_calls instead of the JSON-text protocol — that alone should fix DeepSeek/GLM.

  2. Make the tolerant fallback parser handle this XML/command format, not just JSON: recognize <tool_call>…</tool_call> / <tool_call>…</arg_value> wrappers (tolerant of mismatched close tags), and map a command-style payload (mari db tables) to the matching tool + args (e.g. mari_db with {command: "tables"} / {args: "db tables"}), matching the leading token against the known tool set. This is the safety net for any backend that can't do native tools.

  3. Item 4 (force temp 0/greedy) stays, but as a minor compliance aid only — this test shows it does not fix the format mismatch on its own.

This keeps the throughline: the bug is the missing tolerant parsing + over-eager routing through a JSON-text protocol that many capable models (Gemma, GLM, DeepSeek, local llama.cpp/LM Studio/Kobold) won't follow.

AI-investigated against the released 2.0.0 (main) tree; verify before fixing.

<!-- gh-comment-id:4772467996 --> @kolacheee commented on GitHub (Jun 22, 2026): > Follow-up test from an affected user — this **sharpens the root cause and the fix**, and adds **DeepSeek 4** as another affected model. ## New test data (DeepSeek 4 + GLM, temp 0, fresh chat) A user re-ran with controlled conditions: **temperature 0** and a **brand-new chat** (to rule out sampling and context pollution). Tool calls **still fail to format**, on both **GLM** and **DeepSeek v4 Pro**. The models emit their *trained* tool-call format as text, e.g.: ``` <tool_call>mari db tables</arg_value> <tool_call>mari --help</arg_value> <tool_call>mari agents --help 2>/dev/null || echo "No agents helper"</arg_value> <tool_call>mari db tables</arg_value> ``` Two important takeaways: **1. It is purely a FORMAT/PARSING problem — not sampling.** Since temp 0 + a fresh chat still fail, the earlier "force greedy sampling" fix (item 4) is **necessary but not sufficient**: these models simply don't speak the requested JSON protocol regardless of temperature. **The tolerant fallback parser (fix 1) is the load-bearing fix.** **2. The emitted format is currently 100% unparseable.** The protocol asks for `{"tool_calls":[{"name":…,"arguments":{}}]}` (`workspace-agent.service.ts:523-525`), and `extractJsonToolPayload` (`:533-554`) only looks for JSON — the whole string as JSON, a fenced ```` ```json ```` block, or the substring between the first `{` and last `}`. The DeepSeek/GLM output `<tool_call>mari db tables</arg_value>` contains **no `{` or `}` at all**, so there are zero JSON candidates → `extractJsonToolPayload` returns `null` → `parseJsonToolProtocolCalls` returns `[]` → the raw text is returned and shown. (GLM then degenerates into the agree/repeat loop; DeepSeek "at least created the agent on text" — both fail to produce a tool call.) Note the shape: an **XML-ish `<tool_call>…</arg_value>` wrapper** (often with mismatched open/close tags) around a **command-style invocation** (`mari db tables`), not a JSON args object. The parser needs to handle both the wrapper *and* the non-JSON payload. ## Refined fix priority 1. **Prefer NATIVE tool calling for providers/models that support it (now the top priority for remote models).** DeepSeek and GLM via their OpenAI-compatible APIs return proper native `tool_calls` when the request carries `tools` and the model's chat template is used. The Mari path forces the custom JSON-**text** protocol whenever `shouldUseJsonToolProtocol` is true (`isLocalSidecarConnection || treatAsLocalEndpoint`, `:512`), which **bypasses** native tool calling and fights the model's training. For remote OAI providers that support native tools, route through native `tool_calls` instead of the JSON-text protocol — that alone should fix DeepSeek/GLM. 2. **Make the tolerant fallback parser handle this XML/command format**, not just JSON: recognize `<tool_call>…</tool_call>` / `<tool_call>…</arg_value>` wrappers (tolerant of mismatched close tags), and map a **command-style payload** (`mari db tables`) to the matching tool + args (e.g. `mari_db` with `{command: "tables"}` / `{args: "db tables"}`), matching the leading token against the known tool set. This is the safety net for any backend that can't do native tools. 3. **Item 4 (force temp 0/greedy) stays, but as a minor compliance aid only** — this test shows it does not fix the format mismatch on its own. This keeps the throughline: the bug is the missing tolerant parsing + over-eager routing through a JSON-text protocol that many capable models (Gemma, GLM, DeepSeek, local llama.cpp/LM Studio/Kobold) won't follow. _AI-investigated against the released 2.0.0 (`main`) tree; verify before fixing._
Author
Owner

@lyrakat commented on GitHub (Jun 23, 2026):

This still seems to happen in 2.0.2

<!-- gh-comment-id:4775600510 --> @lyrakat commented on GitHub (Jun 23, 2026): This still seems to happen in 2.0.2
bsakaguchi changed title from [GH-ISSUE #2792] [Issue]: OpenAI-compatible tool calls leak as raw text / repeat-loop on models that emit a non-native format (sidecar + Custom llama.cpp/LM Studio/KoboldCPP + remote GLM/DeepSeek) — no textual tool-call fallback; Mari & agents can't … to [GH-ISSUE #2792] [Issue]: OpenAI-compatible tool calls leak as raw text / repeat-loop on models that emit a non-native format (sidecar + Custom llama.cpp/LM Studio/KoboldCPP + remote GLM/DeepSeek) — no textual tool-call fallback; Mari & agents can't … 2026-11-07 16:42:01 +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#1417
No description provided.