[PR #1389] [MERGED] Wire main-path tool calling into startGeneration #5057

Closed
opened 2026-10-22 04:12:51 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/1389
Author: @Romuromylus
Created: 5/27/2026
Status: ✅ Merged
Merged: 5/27/2026
Merged by: @Romuromylus

Base: refactor ← Head: fix/refactor-issue-1340-tool-call-parity


📝 Commits (6)

  • 1f1ae34 Wire main-path tool calling into startGeneration
  • d32f437 Merge branch 'refactor' into fix/refactor-issue-1340-tool-call-parity
  • f732e63 Correct the synthetic main-agent comment on executeMainToolCall
  • d11097e Address CodeRabbit review on main-path tool calling
  • da7a692 Merge remote-tracking branch 'upstream/refactor' into fix/refactor-issue-1340-tool-call-parity
  • 9468de8 Merge branch 'refactor' into fix/refactor-issue-1340-tool-call-parity

📊 Changes

5 files changed (+1602 additions, -406 deletions)

View changed files

📝 src/engine/generation/agent-runner.ts (+22 -368)
📝 src/engine/generation/generation-events.ts (+2 -0)
➕ src/engine/generation/main-tool-loop.test.ts (+828 -0)
📝 src/engine/generation/start-generation.ts (+203 -38)
➕ src/engine/generation/tools-runtime.ts (+547 -0)

📄 Description

Why this change

Closes #1340.

The refactor's startGeneration (src/engine/generation/start-generation.ts) never passed tools to deps.llm.stream(...) and never handled tool_call chunks coming back, so the per-chat enableTools + activeToolIds settings persisted by ChatSettingsDrawer were dead settings for the main character LLM call across every mode (chat / roleplay / game / conversation). All tool plumbing already existed scoped per-agent in agent-runner.ts, but was unreachable from the main character path. This was a regression versus the v1.6.x server build, where the main generation route resolved built-in + custom tools and ran a multi-turn tool-execution loop.

The audit comment on #1340 asked to verify that transport, command handling, and prompt assembly all agree on conversation-mode tool behavior. They did not: the UI claimed tools available, storage persisted enableTools / activeToolIds, and the transport / prompt-assembly layer ignored both. This change restores agreement across all three layers, mode-neutrally.

What changed

  • New module src/engine/generation/tools-runtime.ts — extracts the shared tool helpers (built-in tool map, custom-tool loader, executeBuiltInTool, normalization, dice / lorebook helpers) from agent-runner.ts and adds a mode-neutral public API (buildMainToolDefinitions, executeMainToolCall, chatToolsEnabledFor, chatActiveToolIdsFor). All extracted helpers are byte-identical to their previous behavior; the new API is additive.
  • src/engine/generation/agent-runner.ts — deletes the moved functions and re-imports them from ./tools-runtime. Agent-path behavior is unchanged.
  • src/engine/generation/start-generation.ts — adds a single streamMainGenerationLoop helper called by both LLM branches (agents-enabled and directMessages). Each iteration streams from the model, collects tool_call chunks, executes them via executeMainToolCall, appends the results back into the conversation, and re-streams. Iteration is capped at MAX_MAIN_TOOL_ITERATIONS = 8 with a visible phase event on cap-hit.
  • src/engine/generation/generation-events.ts — two new variants tool_call and tool_result so downstream consumers can observe the loop. No UI rendering is added in this PR — that is intentionally left for a follow-up.

Design choices

  • Mode-neutral by construction. The loop activates iff chat.metadata.enableTools is true and buildMainToolDefinitions returns at least one usable tool. There is no read of chat.mode anywhere in the new path. The change therefore restores parity uniformly across chat / roleplay / game / conversation; #1340 is framed as conversation-mode but the surface is broader.
  • Agent-only tools filtered out of the main toolset. read_chat_summary, append_chat_summary, read_chat_variable, and write_chat_variable are inter-agent coordination primitives — they should not be exposed to the main character, matching the legacy server's agentOnlyToolNames set.
  • Spotify tools filtered out of the main toolset. The Spotify integration is owned by the Spotify agent; routing it through the main character would conflate ownership and would also require a synthetic agent id with no Spotify credentials, which would just fail at execution time anyway. Agents that already have Spotify in their enabledTools continue to receive it via the unchanged agent path.
  • Custom-vs-built-in name collision — de-duplicated with the built-in winning. Matches the legacy generate.routes.ts:5984-5990 behavior.
  • Tool turns are conversation-internal only. Tool-call and tool-result messages are appended to the in-memory conversation: LlmMessage[] array between iterations but never flow into saveAssistantMessage; only the final accumulated assistant content is persisted, matching legacy.

Verification

  • pnpm check passes locally (check:architecture, check:frontend, check:rust, check:docs).
  • pnpm test passes (22 files / 128 tests including the new main-tool-loop.test.ts with 13 deterministic tests covering all ten rows of the implementation's risk matrix: Spotify filter, infinite-loop cap, custom-tool execution failure surfacing, non-persistence of tool turns, enableTools: false byte-identical baseline, agent-only filter, activeToolIds: [] semantics, mid-loop abort with no orphan tool-call events, Branch B parity with Branch A, and custom-vs-built-in name collision).
  • cargo clippy --workspace --all-targets -- -D warnings passes.
  • The verification is fully deterministic against stubbed deps.llm.stream / deps.integrations.customTools.execute / deps.storage; no real network, no flaky asserts.
  • I have not yet driven this end-to-end through the desktop shell against a live tool-capable provider. Reviewer judgement welcome on whether a manual end-to-end pass is required before promoting from draft.

Known caveat: streaming downgrade on some providers when tools are enabled

The marinara-llm crate's streaming router (src-tauri/crates/llm/src/lib.rs:95-119) only takes the true streaming path (stream_openai_compatible) when request.tools.is_empty() for any provider that is not openai_chatgpt, OpenAI Responses, Anthropic, Google, Google Vertex, or Claude subscription. Once tools are non-empty, those other providers fall through to complete_rich, which is a single non-streaming request that emits all tokens at once at the end of the turn.

This is a pre-existing limitation of the LLM crate, not introduced by this PR — but this PR is the first commit that makes the user-facing enableTools setting actually reach the streaming router. As a result, enabling tools on chats backed by OpenRouter, raw OpenAI Chat Completions (non-Responses), Mistral, Groq, KoboldCpp, llama.cpp, Together, etc. will silently drop token-by-token streaming for those chats. Tool calls themselves still work; only the streaming UX changes.

Tracking as a follow-up: extend stream_openai_compatible to support the OpenAI Chat Completions streaming-tool-delta path so the affected providers retain streaming UX with tools enabled.

Follow-ups (deferred, not blocking this PR)

  • Extend stream_openai_compatible with tool-call streaming for non-Responses-API providers (per the caveat above).
  • UI rendering for the new tool_call / tool_result events in the chat surface. This PR keeps the events as runtime signal only.
  • Abort-signal propagation into long-running custom-tool webhooks. Currently the loop honors abort at the next deps.llm.stream iteration boundary; a 30s+ webhook would still complete before the loop cancels. Matches existing agent-runner behavior.
  • Type unification: customToolDefinition returns LLMToolDefinition (from generation-core/llm/base-provider) while buildMainToolDefinitions packs the result into LlmToolDefinition[] (from capabilities/llm). Structurally identical so typecheck passes, but worth consolidating in a future cleanup.
  • Documenting the in-place mutation contract of updateChatMetadata (pre-existing in agent-runner.ts, now reachable from a second call site).
  • If includeSpotify: false is ever lifted from buildMainToolDefinitions, the caller must supply a real Spotify-agent id (or spotifyAgentId must be refactored to fall back to "" so find_by_field(... "type", "spotify") is reached) — the synthetic "main" literal will NOT resolve to default credentials. See the updated comment on executeMainToolCall for context.

Summary by CodeRabbit

  • New Features

    • Added tool_call and tool_result event types for improved tool execution visibility.
    • Implemented multi-turn tool execution loops with iteration caps to enhance conversation flow.
  • Refactor

    • Reorganized tool runtime logic to improve maintainability and separation of concerns.
  • Tests

    • Added comprehensive test suite for tool loop behavior, filtering, and error handling.

Review Change Stack


🔄 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/1389 **Author:** [@Romuromylus](https://github.com/Romuromylus) **Created:** 5/27/2026 **Status:** ✅ Merged **Merged:** 5/27/2026 **Merged by:** [@Romuromylus](https://github.com/Romuromylus) **Base:** `refactor` ← **Head:** `fix/refactor-issue-1340-tool-call-parity` --- ### 📝 Commits (6) - [`1f1ae34`](https://github.com/Pasta-Devs/Marinara-Engine/commit/1f1ae34a0fad0e3d870faa93c642621222bfd9ae) Wire main-path tool calling into startGeneration - [`d32f437`](https://github.com/Pasta-Devs/Marinara-Engine/commit/d32f4370164e68d87d08195a95abe078168f4e0f) Merge branch 'refactor' into fix/refactor-issue-1340-tool-call-parity - [`f732e63`](https://github.com/Pasta-Devs/Marinara-Engine/commit/f732e6398cbda0c72bc98688894c8edbebc587e9) Correct the synthetic main-agent comment on executeMainToolCall - [`d11097e`](https://github.com/Pasta-Devs/Marinara-Engine/commit/d11097e224f49f3a2439d37d5a231068c7fed133) Address CodeRabbit review on main-path tool calling - [`da7a692`](https://github.com/Pasta-Devs/Marinara-Engine/commit/da7a6929872362dd98c708b36c527a4b3b4176b6) Merge remote-tracking branch 'upstream/refactor' into fix/refactor-issue-1340-tool-call-parity - [`9468de8`](https://github.com/Pasta-Devs/Marinara-Engine/commit/9468de89c567ef244979b7c2c6f25b85d63f7ba4) Merge branch 'refactor' into fix/refactor-issue-1340-tool-call-parity ### 📊 Changes **5 files changed** (+1602 additions, -406 deletions) <details> <summary>View changed files</summary> 📝 `src/engine/generation/agent-runner.ts` (+22 -368) 📝 `src/engine/generation/generation-events.ts` (+2 -0) ➕ `src/engine/generation/main-tool-loop.test.ts` (+828 -0) 📝 `src/engine/generation/start-generation.ts` (+203 -38) ➕ `src/engine/generation/tools-runtime.ts` (+547 -0) </details> ### 📄 Description ## Why this change Closes #1340. The refactor's `startGeneration` (`src/engine/generation/start-generation.ts`) never passed `tools` to `deps.llm.stream(...)` and never handled `tool_call` chunks coming back, so the per-chat `enableTools` + `activeToolIds` settings persisted by `ChatSettingsDrawer` were dead settings for the main character LLM call across every mode (chat / roleplay / game / conversation). All tool plumbing already existed scoped per-agent in `agent-runner.ts`, but was unreachable from the main character path. This was a regression versus the v1.6.x server build, where the main generation route resolved built-in + custom tools and ran a multi-turn tool-execution loop. The audit comment on #1340 asked to verify that transport, command handling, and prompt assembly all agree on conversation-mode tool behavior. They did not: the UI claimed tools available, storage persisted `enableTools` / `activeToolIds`, and the transport / prompt-assembly layer ignored both. This change restores agreement across all three layers, mode-neutrally. ## What changed - **New module** `src/engine/generation/tools-runtime.ts` — extracts the shared tool helpers (built-in tool map, custom-tool loader, `executeBuiltInTool`, normalization, dice / lorebook helpers) from `agent-runner.ts` and adds a mode-neutral public API (`buildMainToolDefinitions`, `executeMainToolCall`, `chatToolsEnabledFor`, `chatActiveToolIdsFor`). All extracted helpers are byte-identical to their previous behavior; the new API is additive. - **`src/engine/generation/agent-runner.ts`** — deletes the moved functions and re-imports them from `./tools-runtime`. Agent-path behavior is unchanged. - **`src/engine/generation/start-generation.ts`** — adds a single `streamMainGenerationLoop` helper called by both LLM branches (agents-enabled and directMessages). Each iteration streams from the model, collects `tool_call` chunks, executes them via `executeMainToolCall`, appends the results back into the conversation, and re-streams. Iteration is capped at `MAX_MAIN_TOOL_ITERATIONS = 8` with a visible `phase` event on cap-hit. - **`src/engine/generation/generation-events.ts`** — two new variants `tool_call` and `tool_result` so downstream consumers can observe the loop. No UI rendering is added in this PR — that is intentionally left for a follow-up. ### Design choices - **Mode-neutral by construction.** The loop activates iff `chat.metadata.enableTools` is true and `buildMainToolDefinitions` returns at least one usable tool. There is no read of `chat.mode` anywhere in the new path. The change therefore restores parity uniformly across chat / roleplay / game / conversation; #1340 is framed as conversation-mode but the surface is broader. - **Agent-only tools filtered out of the main toolset.** `read_chat_summary`, `append_chat_summary`, `read_chat_variable`, and `write_chat_variable` are inter-agent coordination primitives — they should not be exposed to the main character, matching the legacy server's `agentOnlyToolNames` set. - **Spotify tools filtered out of the main toolset.** The Spotify integration is owned by the Spotify agent; routing it through the main character would conflate ownership and would also require a synthetic agent id with no Spotify credentials, which would just fail at execution time anyway. Agents that already have Spotify in their `enabledTools` continue to receive it via the unchanged agent path. - **Custom-vs-built-in name collision** — de-duplicated with the built-in winning. Matches the legacy `generate.routes.ts:5984-5990` behavior. - **Tool turns are conversation-internal only.** Tool-call and tool-result messages are appended to the in-memory `conversation: LlmMessage[]` array between iterations but never flow into `saveAssistantMessage`; only the final accumulated assistant content is persisted, matching legacy. ## Verification - `pnpm check` passes locally (`check:architecture`, `check:frontend`, `check:rust`, `check:docs`). - `pnpm test` passes (22 files / 128 tests including the new `main-tool-loop.test.ts` with 13 deterministic tests covering all ten rows of the implementation's risk matrix: Spotify filter, infinite-loop cap, custom-tool execution failure surfacing, non-persistence of tool turns, `enableTools: false` byte-identical baseline, agent-only filter, `activeToolIds: []` semantics, mid-loop abort with no orphan tool-call events, Branch B parity with Branch A, and custom-vs-built-in name collision). - `cargo clippy --workspace --all-targets -- -D warnings` passes. - The verification is fully deterministic against stubbed `deps.llm.stream` / `deps.integrations.customTools.execute` / `deps.storage`; no real network, no flaky asserts. - I have not yet driven this end-to-end through the desktop shell against a live tool-capable provider. Reviewer judgement welcome on whether a manual end-to-end pass is required before promoting from draft. ## Known caveat: streaming downgrade on some providers when tools are enabled The `marinara-llm` crate's streaming router (`src-tauri/crates/llm/src/lib.rs:95-119`) only takes the true streaming path (`stream_openai_compatible`) when `request.tools.is_empty()` for any provider that is not `openai_chatgpt`, OpenAI Responses, Anthropic, Google, Google Vertex, or Claude subscription. Once tools are non-empty, those other providers fall through to `complete_rich`, which is a single non-streaming request that emits all tokens at once at the end of the turn. This is a pre-existing limitation of the LLM crate, not introduced by this PR — but this PR is the first commit that makes the user-facing `enableTools` setting actually reach the streaming router. As a result, enabling tools on chats backed by OpenRouter, raw OpenAI Chat Completions (non-Responses), Mistral, Groq, KoboldCpp, llama.cpp, Together, etc. will silently drop token-by-token streaming for those chats. Tool calls themselves still work; only the streaming UX changes. Tracking as a follow-up: extend `stream_openai_compatible` to support the OpenAI Chat Completions streaming-tool-delta path so the affected providers retain streaming UX with tools enabled. ## Follow-ups (deferred, not blocking this PR) - Extend `stream_openai_compatible` with tool-call streaming for non-Responses-API providers (per the caveat above). - UI rendering for the new `tool_call` / `tool_result` events in the chat surface. This PR keeps the events as runtime signal only. - Abort-signal propagation into long-running custom-tool webhooks. Currently the loop honors abort at the next `deps.llm.stream` iteration boundary; a 30s+ webhook would still complete before the loop cancels. Matches existing agent-runner behavior. - Type unification: `customToolDefinition` returns `LLMToolDefinition` (from `generation-core/llm/base-provider`) while `buildMainToolDefinitions` packs the result into `LlmToolDefinition[]` (from `capabilities/llm`). Structurally identical so typecheck passes, but worth consolidating in a future cleanup. - Documenting the in-place mutation contract of `updateChatMetadata` (pre-existing in `agent-runner.ts`, now reachable from a second call site). - If `includeSpotify: false` is ever lifted from `buildMainToolDefinitions`, the caller must supply a real Spotify-agent id (or `spotifyAgentId` must be refactored to fall back to `""` so `find_by_field(... "type", "spotify")` is reached) — the synthetic `"main"` literal will NOT resolve to default credentials. See the updated comment on `executeMainToolCall` for context. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added `tool_call` and `tool_result` event types for improved tool execution visibility. * Implemented multi-turn tool execution loops with iteration caps to enhance conversation flow. * **Refactor** * Reorganized tool runtime logic to improve maintainability and separation of concerns. * **Tests** * Added comprehensive test suite for tool loop behavior, filtering, and error handling. <!-- review_stack_entry_start --> [![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/Pasta-Devs/Marinara-Engine/pull/1389?utm_source=github_walkthrough&utm_medium=github&utm_campaign=change_stack) <!-- review_stack_entry_end --> <!-- 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-22 04:12:51 +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#5057
No description provided.