[GH-ISSUE #2990] [Issue]: Retry tool attachment never wires the edit_chat_message tool, so message-editing agents silently lose it on retry #1565

Closed
opened 2026-10-21 05:39:14 +07:00 by bsakaguchi · 1 comment
Owner

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

Originally assigned to: @SpicyMarinara on GitHub.

What's wrong
The main generation path resolves an agent's full tool set in one pass, including edit_chat_message for agents that enabled it and hold the edit_messages capability. The retry path instead uses three narrow attach helpers (spotify / chat-metadata / lorebook-write) — none of which know about edit_chat_message. So a custom agent that uses edit_chat_message ends up with no tool context on retry, the model is told it has no tools, and its message-editing behavior fails on retry even though it works on initial generation.

How to reproduce (try it yourself)

  1. Create a custom agent, enable the edit_messages capability and the edit_chat_message tool (the editor saves the tool into enabledTools only when edit_messages is on). Give it a prompt instructing it to call edit_chat_message.
  2. Generate a turn — the agent receives the tool (main path) and can edit messages.
  3. Trigger an agent retry for that agent type (POST /retry-agents).

You'll see: on retry, entry.resolved.toolContext stays undefined, the agent runs with no tool loop, and it cannot edit messages.
Expected: same tool availability as initial generation.

Where it is
packages/server/src/routes/generate/retry-agents-route.ts:1262-1268 (allow-lists), :3078-3085 (only three attach helpers called), :2010-2011 (batch-vs-tool split — no toolContext means no tool loop), agent-executor.ts:388 (tool loop only when toolContext.tools is non-empty). Main-path comparison: packages/server/src/services/generation/tool-resolution-runtime.ts:692-707 (and executor at 631-650).

What's happening
The retry tool-context logic was reimplemented as three special-case helpers instead of mirroring the main path's generic per-agent enabledTools resolution. edit_chat_message was simply not added to any allow-list, and no helper injects a replaceChatMessageContent executor on retry.

Suggested fix
Add a fourth retry attach helper that mirrors the main path's edit_chat_message handling, gated on the edit_messages capability, that MERGES into any existing toolContext, and call it LAST (after spotify/metadata/lorebook) so it composes with the others. The helper validates the message belongs to this chat and is user/assistant role (mirroring tool-resolution-runtime.ts:631-650), only attaches when the agent enabled the tool AND has customAgentHasCapability(settings, "edit_messages"), and delegates non-edit calls to any pre-existing executor:

const EDIT_CHAT_MESSAGE_TOOL_NAME = "edit_chat_message";

async function attachRetryEditChatMessageToolContexts(args: {
  chats: ReturnType<typeof createChatsStorage>;
  chatId: string;
  resolvedAgents: ResolvedRetryAgent[];
}) {
  const { chats, chatId, resolvedAgents } = args;
  const tool = toLLMToolDefinition(EDIT_CHAT_MESSAGE_TOOL_NAME);
  if (!tool) return;

  const replaceChatMessageContent = async (input: { messageId: string; content: string; reason?: string }) => {
    const message = await chats.getMessage(input.messageId);
    if (!message || message.chatId !== chatId) {
      return { error: "Message not found in this chat.", messageId: input.messageId };
    }
    if (message.role !== "user" && message.role !== "assistant") {
      return { error: "Only user or assistant messages can be edited.", messageId: input.messageId };
    }
    await chats.updateMessageContent(input.messageId, input.content);
    return { applied: true, messageId: input.messageId, role: message.role, reason: input.reason ?? null };
  };

  for (const entry of resolvedAgents) {
    const settings = parseSettingsRecord(entry.resolved.settings);
    const enabledNames = Array.isArray(settings.enabledTools) ? (settings.enabledTools as string[]) : [];
    if (!enabledNames.includes(EDIT_CHAT_MESSAGE_TOOL_NAME)) continue;
    if (!customAgentHasCapability(settings, "edit_messages")) continue;

    const existingContext = entry.resolved.toolContext;
    const tools = existingContext?.tools.some((item) => item.function.name === EDIT_CHAT_MESSAGE_TOOL_NAME)
      ? [...existingContext.tools]
      : [...(existingContext?.tools ?? []), tool];

    entry.resolved.toolContext = {
      tools,
      executeToolCall: async (call) => {
        if (call.function.name !== EDIT_CHAT_MESSAGE_TOOL_NAME) {
          if (existingContext) return existingContext.executeToolCall(call);
          return JSON.stringify({
            error: `Tool not allowed for agent ${entry.resolved.type}: ${call.function.name}`,
            allowed: [EDIT_CHAT_MESSAGE_TOOL_NAME],
          });
        }
        const results = await executeToolCalls([call], { replaceChatMessageContent });
        return results[0]?.result ?? "Tool execution failed";
      },
    };
  }
}

Then at retry-agents-route.ts:3078-3085, add await attachRetryEditChatMessageToolContexts({ chats, chatId, resolvedAgents }); AFTER the existing three. Regression avoided: do NOT "converge onto the generic resolveGenerationTools" — the three retry helpers carry retry-only behavior (spotify before-play capture used by validateSpotifyRetryPlayback, lorebook write-approval envelopes) and operate on a different shape; converging would break those. The capability gate MUST be preserved so retry doesn't expose message-editing to an agent the initial generation denies, and the helper must run LAST and merge so agents combining edit_chat_message with metadata/spotify tools don't lose those.


AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.

Originally created by @kolacheee on GitHub (Jun 29, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2990 Originally assigned to: @SpicyMarinara on GitHub. **What's wrong** The main generation path resolves an agent's full tool set in one pass, including `edit_chat_message` for agents that enabled it and hold the `edit_messages` capability. The retry path instead uses three narrow attach helpers (spotify / chat-metadata / lorebook-write) — none of which know about `edit_chat_message`. So a custom agent that uses `edit_chat_message` ends up with no tool context on retry, the model is told it has no tools, and its message-editing behavior fails on retry even though it works on initial generation. **How to reproduce (try it yourself)** 1. Create a custom agent, enable the `edit_messages` capability and the `edit_chat_message` tool (the editor saves the tool into enabledTools only when edit_messages is on). Give it a prompt instructing it to call edit_chat_message. 2. Generate a turn — the agent receives the tool (main path) and can edit messages. 3. Trigger an agent retry for that agent type (POST /retry-agents). You'll see: on retry, `entry.resolved.toolContext` stays undefined, the agent runs with no tool loop, and it cannot edit messages. Expected: same tool availability as initial generation. **Where it is** `packages/server/src/routes/generate/retry-agents-route.ts:1262-1268` (allow-lists), `:3078-3085` (only three attach helpers called), `:2010-2011` (batch-vs-tool split — no toolContext means no tool loop), `agent-executor.ts:388` (tool loop only when toolContext.tools is non-empty). Main-path comparison: `packages/server/src/services/generation/tool-resolution-runtime.ts:692-707` (and executor at 631-650). **What's happening** The retry tool-context logic was reimplemented as three special-case helpers instead of mirroring the main path's generic per-agent enabledTools resolution. `edit_chat_message` was simply not added to any allow-list, and no helper injects a `replaceChatMessageContent` executor on retry. **Suggested fix** Add a fourth retry attach helper that mirrors the main path's edit_chat_message handling, gated on the `edit_messages` capability, that MERGES into any existing toolContext, and call it LAST (after spotify/metadata/lorebook) so it composes with the others. The helper validates the message belongs to this chat and is user/assistant role (mirroring tool-resolution-runtime.ts:631-650), only attaches when the agent enabled the tool AND has `customAgentHasCapability(settings, "edit_messages")`, and delegates non-edit calls to any pre-existing executor: ```ts const EDIT_CHAT_MESSAGE_TOOL_NAME = "edit_chat_message"; async function attachRetryEditChatMessageToolContexts(args: { chats: ReturnType<typeof createChatsStorage>; chatId: string; resolvedAgents: ResolvedRetryAgent[]; }) { const { chats, chatId, resolvedAgents } = args; const tool = toLLMToolDefinition(EDIT_CHAT_MESSAGE_TOOL_NAME); if (!tool) return; const replaceChatMessageContent = async (input: { messageId: string; content: string; reason?: string }) => { const message = await chats.getMessage(input.messageId); if (!message || message.chatId !== chatId) { return { error: "Message not found in this chat.", messageId: input.messageId }; } if (message.role !== "user" && message.role !== "assistant") { return { error: "Only user or assistant messages can be edited.", messageId: input.messageId }; } await chats.updateMessageContent(input.messageId, input.content); return { applied: true, messageId: input.messageId, role: message.role, reason: input.reason ?? null }; }; for (const entry of resolvedAgents) { const settings = parseSettingsRecord(entry.resolved.settings); const enabledNames = Array.isArray(settings.enabledTools) ? (settings.enabledTools as string[]) : []; if (!enabledNames.includes(EDIT_CHAT_MESSAGE_TOOL_NAME)) continue; if (!customAgentHasCapability(settings, "edit_messages")) continue; const existingContext = entry.resolved.toolContext; const tools = existingContext?.tools.some((item) => item.function.name === EDIT_CHAT_MESSAGE_TOOL_NAME) ? [...existingContext.tools] : [...(existingContext?.tools ?? []), tool]; entry.resolved.toolContext = { tools, executeToolCall: async (call) => { if (call.function.name !== EDIT_CHAT_MESSAGE_TOOL_NAME) { if (existingContext) return existingContext.executeToolCall(call); return JSON.stringify({ error: `Tool not allowed for agent ${entry.resolved.type}: ${call.function.name}`, allowed: [EDIT_CHAT_MESSAGE_TOOL_NAME], }); } const results = await executeToolCalls([call], { replaceChatMessageContent }); return results[0]?.result ?? "Tool execution failed"; }, }; } } ``` Then at retry-agents-route.ts:3078-3085, add `await attachRetryEditChatMessageToolContexts({ chats, chatId, resolvedAgents });` AFTER the existing three. Regression avoided: do NOT "converge onto the generic resolveGenerationTools" — the three retry helpers carry retry-only behavior (spotify before-play capture used by validateSpotifyRetryPlayback, lorebook write-approval envelopes) and operate on a different shape; converging would break those. The capability gate MUST be preserved so retry doesn't expose message-editing to an agent the initial generation denies, and the helper must run LAST and merge so agents combining edit_chat_message with metadata/spotify tools don't lose those. --- *AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.*
Author
Owner

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

Fixed in merged staging PR #3004.

<!-- gh-comment-id:4832280414 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Fixed in merged staging PR #3004.
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#1565
No description provided.