Skip to content
TheChatArchiveThe Chat Archive
MiniMaxminimax/minimax-m3· unknownHugging Face ibragim-bad/swe_rebench_07_2026_trajectories

ISSUE DESCRIPTION Subagent toolcalls not handled when using LiteLLM proxy Summary When…

  1. User

    ISSUE DESCRIPTION

    Subagent tool_calls not handled when using LiteLLM proxy

    Summary

    When using cagent with a LiteLLM proxy (OpenAI-compatible API), a subagent can return a valid tool_calls response, but the host agent reports “no response from subagent” and does not execute the tool call.

    Environment

    • cagent: v1.19.7
    • OS: Linux (WSL2) x86_64
    • LLM: gemini-pro via LiteLLM proxy (OpenAI-compatible)

    Expected

    Host agent receives the subagent response and executes the tool call(s), then continues the conversation with the tool result.

    Actual

    Host agent reports there is “no response from subagent” even though the subagent response contains a valid tool_calls entry. The requested tool call is not executed.

    Minimal reproduction

    1. Configure cagent to use LiteLLM as the model provider (OpenAI-compatible API).
    2. Run a workflow where the subagent is asked to use tools.
    3. The subagent returns a tool call (e.g., company_search with JSON arguments) and finishes with finish_reason: "stop".
    4. The host agent logs “no response from subagent” and does not invoke the tool.

    Notes

    • The subagent response includes a valid tool call object (type: function, name: company_search, arguments: {"datasources": ["confluence", "github", "gdrive"], "query": "LiteLLM usage teams integrations standards"}).
    • I can reproduce consistently with LiteLLM as the proxy in front of an OpenAI-compatible endpoint.

    Please let me know if you want a sanitized example payload or a minimal agent config.

    Interface

    No new interfaces are introduced.

    ADDITIONAL ADVICE

    Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use git checkout <file> to restore the file to its original state. You can also reset all changes in the repository using git reset --hard command. Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands. However you don't need to use git add or git commit before submitting your changes. In fact, submit only submits currently unstaged changes because it uses git diff to get the changes that need to be submitted.

    CHECKLIST

    Before submitting your solution, please go over the following checklist and make sure you've done everything:

    • If an error was reported in the issue description, I have successfully reproduced it.
    • If an error was reported in the issue description, I have confirmed that my fix resolves the error.
    • I have thought about edge cases and made sure my fix handles them as well.
    • I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.

    Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!

    (Current directory: /docker-agent, current file: none) bash-$

  2. MiniMax Assistant

    Let me start by exploring the repository structure to understand the codebase.

  3. MiniMax Assistant

    The error message "no response from subagent" is not in the code. Let me search more broadly.

  4. MiniMax Assistant

    Let me look at the loop.go for the part that handles tool calls and processes responses from subagents.

  5. MiniMax Assistant

    Let me now search for "no response from subagent" - the issue says this error appears, but my search found nothing. Let me look at the agenttool package which is used for "agent" tool calls (RunAgent).

  6. MiniMax Assistant

    Let me now look at the loop.go to understand the message processing more thoroughly. I need to understand how messages with tool_calls are processed.

  7. MiniMax Assistant

    Now I have a clearer picture. The host agent calls the subagent, and the response is delivered via s.GetLastAssistantMessageContent(). Let me check what the function returns when the assistant message contains only tool_calls but no text content.

  8. MiniMax Assistant

    Now let me understand the issue more. The issue says when the subagent returns a response with tool_calls and finish_reason: "stop" (not tool_calls), then the host agent does NOT execute the tool call. Let me trace this through.

  9. MiniMax Assistant

    Now let me look at the OpenAI-compatible provider to understand how it processes the responses. Let me also see how a non-streaming response is processed:

  10. MiniMax Assistant

    Now let me look at how the streaming handles the LiteLLM-style responses. LiteLLM might use the older chat completions API with tool_calls in the delta:

  11. MiniMax Assistant

    Now let me search for "subagent" related text directly in the loop/streaming code:

  12. MiniMax Assistant

    Let me look at how the adapter processes tool_calls deltas:

  13. MiniMax Assistant

    Now let me see how the streamed LiteLLM output gets processed. Let me also look at what happens to messages that have tool_calls (the OpenAI format) - this could be the issue. The LiteLLM proxy sends a response with tool_calls and finish_reason: "stop". Let me see how this is processed in streaming.go and the chat completion delta logic:

  14. MiniMax Assistant

    Interesting! When trackUsage is true and the finish reason is "stop" or "length", it sets finishReasonStr = "". This is done to preserve it until the usage chunk arrives. But there's a possible issue here. When a tool_calls chunk has finish_reason="tool_calls" or even just "stop" with tool calls, the OpenAI stream will include the tool calls and a finish_reason. Let me trace this more carefully.

    Let me check where trackUsage is set and what happens when a subagent returns tool calls:

  15. MiniMax Assistant

    Now let me look at the actual flow. The issue says: "host agent reports there is 'no response from subagent' even though the subagent response contains a valid tool_calls entry."

    Let me check how the assistant message is converted to a response that the parent agent gets. The key is s.GetLastAssistantMessageContent() which is called in runForwarding. When the assistant message only contains tool calls and no content, this returns an empty string!

  16. MiniMax Assistant

    Now let me look more carefully at the issue. The user is saying that when a subagent returns tool_calls (and the LLM/parent agent expects that the tool is actually executed as part of the subagent workflow), the parent host agent reports "no response from subagent" and doesn't execute the tool call.

    Let me re-read the issue:

    The subagent response includes a valid tool call object (type: function, name: company_search, arguments: {"datasources": ["confluence", "github", "gdrive"], "query": "LiteLLM usage teams integrations standards"}). I can reproduce consistently with LiteLLM as the proxy in front of an OpenAI-compatible endpoint.

    So when the subagent returns a response with tool_calls and finish_reason: "stop", the host agent should execute the tool calls but it doesn't. The finish_reason being "stop" rather than "tool_calls" is a specific aspect of how LiteLLM proxies Gemini.

    Let me look at the streaming.go more carefully:

  17. MiniMax Assistant

    OK so when finish_reason is "stop" and toolCalls > 0, the finish_reason is changed to "tool_calls" - that seems fine. Now let me look at the issue with the parent's reaction:

    When the subagent returns a tool_calls response, the parent agent processes the tool calls. Then the parent might also have a tool_call (like transfer_task) for the subagent. The tool result of the subagent call becomes a "user" message in the conversation. If the tool returns empty content (because GetLastAssistantMessageContent() returns empty when the assistant message only has tool calls), then the user message has empty content.

    Let me check more carefully:

  18. MiniMax Assistant

    Let me search for the literal error message:

  19. MiniMax Assistant

    The error message "no response from subagent" is not in the code - it may be paraphrased from user observation. The actual issue is that when the subagent returns tool calls only (no content), the host agent has nothing to display. Let me look at the runForwarding function more carefully:

  20. MiniMax Assistant

    Now I see the key piece. s.GetLastAssistantMessageContent() returns the trimmed content of the last assistant message. If the last message is just a tool call (no content), it returns an empty string.

    So when the subagent does:

    1. LLM call → returns tool_calls with no content
    2. Tool call is processed
    3. LLM call again → returns the actual response

    The session would have two assistant messages, and the last one would have the content. So this works.

    But if the subagent does:

    1. LLM call → returns tool_calls with no content
    2. Tool call is processed

    And stops there (because something), then GetLastAssistantMessageContent() returns empty. Or if the host agent asks for a tool, and the subagent just calls another tool in response, the parent gets the tool result.

    Let me look more carefully at the issue. The key claim is that with LiteLLM proxying OpenAI-compatible endpoints, the finish_reason is "stop" instead of "tool_calls" and the host agent doesn't execute the tool.

    Wait, I see. The issue says "the subagent response includes a valid tool call". The subagent is the LLM model itself, not the agent. The host agent receives the tool_calls and is supposed to execute them, but it doesn't. So the problem is in the host agent's processing of its own LLM response.

    Hmm, but the issue mentions specifically "Subagent tool_calls not handled". So it's the subagent's tool_calls.

    Let me re-read:

    When using cagent with a LiteLLM proxy (OpenAI-compatible API), a subagent can return a valid tool_calls response, but the host agent reports "no response from subagent" and does not execute the tool call.

    So the subagent returns tool_calls but the host agent doesn't execute them. Let me trace this:

    1. Host agent calls LLM
    2. LLM returns transfer_task tool_call to invoke subagent
    3. Host agent invokes subagent via runForwarding
    4. Subagent calls LLM (via LiteLLM)
    5. LiteLLM returns a tool_calls (e.g., company_search) with finish_reason: "stop" (not tool_calls)
    6. Subagent processes this... or does it?

    In step 5, the LLM is the subagent's LLM. The subagent should:

    1. Receive the LLM response with tool_calls
    2. Execute the tool calls
    3. Get tool results
    4. Call LLM again with tool results
    5. Get final response
    6. Return that response to the host agent

    Let me look at how streaming.go handles the LiteLLM case where finish_reason is "stop" but tool_calls is present. Look at line 132:

  21. MiniMax Assistant

    OK so this code handles the case finish_reason: "stop" && len(toolCalls) > 0 correctly by changing the finish reason to "tool_calls" and returning with Stopped: false. So the subagent should continue processing the tool calls.

    Let me look more carefully. Perhaps the issue is with how the tool_calls are accumulated through the OpenAI adapter. Let me look at how the LiteLLM proxy format works:

  22. MiniMax Assistant

    Wait, I see a potential issue at line 60! When trackUsage is true and the finish reason is "stop", it sets finishReasonStr = "". But this is done in the chunk BEFORE the usage chunk. The reason for this is to use the tracked finish reason (a.lastFinishReason) instead of the current chunk's finish reason when usage info arrives.

    But there's a problem. If the finish_reason "stop" arrives in the same chunk as tool_calls (which is normal for OpenAI's streaming), the finish reason is dropped! And the tool_calls are processed correctly, but the FinishReason field in the response is "" (empty).

    Then in streaming.go:

    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
    

    This check fails because the FinishReason was blanked. Then the code goes to the next iteration or processes the tool calls. But wait, the loop will continue to the next chunk and call Recv() again. If the stream is exhausted, then it goes to the EOF path and falls back to inferring the finish reason.

    Actually, this isn't the problem either. The tool calls are still accumulated. The issue is at line 60: if the OpenAI stream sends a chunk with finish_reason: "stop" AND tool_calls, the FinishReason is blanked out because of the trackUsage flag. Then the code in streaming.go checks the FinishReason but it's empty, so it falls through.

    Wait, but LiteLLM sends finish_reason: "stop" not "tool_calls". With tool_calls present. Let me check what happens when trackUsage is true:

    1. Chunk 1: role="assistant", delta={tool_calls: [...]}, finish_reason=""
    2. Chunk 2: delta={tool_calls: [...]}, finish_reason="" (continued args)
    3. Chunk N: delta={}, finish_reason="stop" <-- this is the LAST chunk
    4. Chunk N+1 (usage chunk): usage={...}, finish_reason="" or omitted

    With trackUsage=true:

    • Chunks 1, 2: finish_reasonStr="" → FinishReason=""
    • Chunk N: finish_reasonStr was "stop" → cleared to "" → FinishReason=""
    • BUT: a.lastFinishReason is also "" because the check if finishReason != chat.FinishReasonNull && finishReason != "" fails.

    Wait wait wait. Let me re-read:

    finishReasonStr := choice.FinishReason
    if a.trackUsage && (finishReasonStr == "stop" || finishReasonStr == "length") {
        finishReasonStr = ""
    }
    
    finishReason := chat.FinishReason(finishReasonStr)
    // Track the finish reason for when we get usage info
    if finishReason != chat.FinishReasonNull && finishReason != "" {
        a.lastFinishReason = finishReason
    }
    

    So when trackUsage=true and finish_reason="stop":

    • finishReasonStr = ""
    • finishReason = ""
    • a.lastFinishReason is NOT updated because finishReason == "".

    Then later when the usage chunk arrives, the finish_reason check uses a.lastFinishReason which is empty.

    finishReason := a.lastFinishReason
    if finishReason == chat.FinishReasonNull || finishReason == "" {
        finishReason = chat.FinishReasonStop
    }
    

    So it defaults to FinishReasonStop. So if trackUsage=true and the stream ends with finish_reason: "stop", the lastFinishReason becomes FinishReasonStop because the empty check fails.

    But the question is: what about the previous code path where the streaming.go code sees a finish_reason of "" (empty) in a non-usage chunk? It doesn't trigger the early-return path. It continues the loop.

    Wait, let me look more carefully at how this works. Let me look at the test file to understand the actual flow:

  23. MiniMax Assistant

    Let me look at how the openai-go SDK decodes the chunk:

  24. MiniMax Assistant

    OK, so I confirmed the API. The issue is clear now. Let me look at the LiteLLM behavior:

    When LiteLLM proxies a model and returns finish_reason: "stop" with tool_calls, the stream:

    1. Sends chunks with tool_calls deltas (finish_reason empty in each)
    2. Sends a final chunk with delta: {} (or some final) and finish_reason: "stop" (or "tool_calls" depending on model)

    Then with trackUsage=true:

    • The chunk with finish_reason: "stop" is BLANKED out (finishReasonStr = "")
    • a.lastFinishReason is NOT updated because the now-empty string fails the check

    So the tool calls accumulate correctly. The early-return in streaming.go for finish_reason="stop" is NEVER hit because the finish reason is blanked. The loop continues, calls Recv() again, and gets EOF. The fallback path in streaming.go kicks in:

    finishReason := providerFinishReason  // empty because never set
    if finishReason == "" {
        switch {
        case len(toolCalls) > 0:
            finishReason = chat.FinishReasonToolCalls
        case fullContent.Len() > 0:
            finishReason = chat.FinishReasonStop
        default:
            finishReason = chat.FinishReasonNull
        }
    }
    

    OK so the fallback handles it correctly. Let me look at the issue more carefully.

    Actually, let me look at the trackUsage handling. The intent is: when trackUsage is true, we expect a separate usage chunk at the end, and we want to preserve the finish reason from before the usage chunk.

    But what happens when LiteLLM doesn't send a separate usage chunk? Or what if LiteLLM sends the usage in the same chunk as the finish_reason? Let me trace through:

    Case 1: LiteLLM sends chunks:

    1. {"choices":[{"delta":{"role":"assistant","content":""}}]} - no finish_reason
    2. {"choices":[{"delta":{"tool_calls":[...]}}]} - no finish_reason
    3. {"choices":[{"delta":{},"finish_reason":"stop"}]} - finish_reason "stop"  
    4. {"usage":{...}} - separate usage chunk, no choices
    

    With trackUsage=true:

    • Chunks 1, 2, 3: finishReasonStr is whatever is in the chunk.
    • Chunk 3 has finish_reason: "stop" → blanked to "" → a.lastFinishReason NOT updated.
    • Chunk 4: usage chunk → a.lastFinishReason is "" → defaults to FinishReasonStop.

    So lastFinishReason ends up as FinishReasonStop. The choices would have the lastFinishReason set.

    But wait, where does this go back? Let me look at the call to Recv() for chunk 4:

    The Recv method returns the response with the usage info populated. The code sets the finish reason on response.Choices[0]:

    if len(openaiResponse.Choices) == 0 {
        response.Choices = append(response.Choices, chat.MessageStreamChoice{
            FinishReason: finishReason,
        })
    } else {
        response.Choices[0].FinishReason = finishReason
    }
    

    OK so the choices finish reason is updated. And the response is returned with FinishReason: FinishReasonStop.

    Then in streaming.go, the response has FinishReason: FinishReasonStop and likely no choices with tool_calls delta. The check:

    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
    

    This would be TRUE for the usage chunk (chunk 4). So the code enters the early-return path:

    finishReason := choice.FinishReason  // FinishReasonStop
    if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
        finishReason = chat.FinishReasonToolCalls
    }
    return streamResult{
        Calls:             toolCalls,
        Content:           fullContent.String(),
        ...
        Stopped:           len(toolCalls) == 0,  // false
        FinishReason:      finishReason,  // FinishReasonToolCalls
        ...
    }, nil
    

    OK so that path returns correctly with Stopped: false and FinishReason: FinishReasonToolCalls.

    So I think the streaming.go part is correct. Let me look at the loop.go more carefully:

  25. MiniMax Assistant

    Let me see processToolCalls:

  26. MiniMax Assistant

    Let me look at the toolexec.Dispatcher.Process:

  27. MiniMax Assistant

    OK, so the processToolCalls actually executes the tool calls. Let me look at the newCall function more carefully and check the conditions where it might not process a tool call.

    Now let me re-read the issue more carefully. The actual issue is that the subagent returns tool_calls with finish_reason: "stop", and the host agent doesn't execute the tool call. The host agent says "no response from subagent".

    So I think the issue is actually:

    • Subagent receives LLM response with tool_calls
    • Subagent processes the LLM response (this works fine)
    • Subagent executes the tool call
    • Subagent gets tool result and goes back to LLM
    • Subagent LLM returns a final response
    • Subagent finishes, returns the response to host agent via GetLastAssistantMessageContent()

    Wait, but maybe the issue is the OPPOSITE direction. Let me re-read the issue:

    When using cagent with a LiteLLM proxy (OpenAI-compatible API), a subagent can return a valid tool_calls response, but the host agent reports "no response from subagent" and does not execute the tool call.

    So a "subagent" returns a "tool_calls response" but the host agent doesn't execute. This means the host agent should be EXECUTING tool calls but it isn't. So perhaps the subagent is actually being called by the host agent through some transfer_task or run_background_agent, and the subagent's LLM call returns a tool_calls response that the host should execute.

    Wait no, that doesn't make sense either. The subagent should be the one executing its own tool calls.

    Let me look at this from a different angle. Let me look at where the "host agent" might receive the tool_calls and be expected to execute them.

  28. MiniMax Assistant

    Let me look more carefully at the loop.go to see how the host agent (the parent) handles the tool_calls:

  29. MiniMax Assistant

    Let me check the issue's mention that the host agent says "no response from subagent". This is the kind of error you'd see if the subagent's tool result returned empty. Let me look for any other place where this could be the case.

  30. MiniMax Assistant

    Now let me see the dispatcher's flow more deeply. I want to understand what happens to tool calls that come from the subagent's response:

  31. MiniMax Assistant

    Let me now look at the runHandler function which handles runtime-managed tools like transfer_task:

  32. MiniMax Assistant

    Now let me look at the addMessage function and ToolCallResponseEvent:

  33. MiniMax Assistant

    OK. Now let me check the issue. The host agent invokes transfer_task to the subagent. The subagent returns a tool_calls response. The subagent's runForwarding returns tools.ResultSuccess(s.GetLastAssistantMessageContent()). If the subagent's last assistant message only has tool_calls (no content), GetLastAssistantMessageContent() returns empty string.

    Now the host agent receives this empty string as the tool result. The host agent then adds this empty tool result message to its own session. When it tries to continue, the LLM might not be able to handle an empty tool result properly.

    Wait, let me re-read the issue ONE more time very carefully:

    When using cagent with a LiteLLM proxy (OpenAI-compatible API), a subagent can return a valid tool_calls response, but the host agent reports "no response from subagent" and does not execute the tool call.

    So the host agent receives the tool_calls from the subagent but doesn't execute it. This is the host agent's tool_calls, not the subagent's.

    Hmm. Wait. Maybe what the user means is: the host agent calls the subagent tool (via transfer_task or run_background_agent). The subagent is supposed to be processing the task. The subagent returns a tool call (not a final response), which the host agent should execute. But the host agent doesn't execute it because it sees an empty response.

    OR maybe the user's mental model is wrong, and what's happening is:

    1. Subagent receives task
    2. Subagent calls LLM
    3. LLM returns a tool call
    4. Subagent processes the tool call
    5. Subagent calls LLM again
    6. LLM returns the final response

    In step 3, when the LLM returns a tool call with finish_reason: "stop" instead of tool_calls, maybe the stream adapter or the streaming logic doesn't recognize it as a tool call response.

    Wait, the streaming.go code at line 132-140 handles this case! Let me look at the issue again:

    Actual

    Host agent reports there is "no response from subagent" even though the subagent response contains a valid tool_calls entry.

    OK so the "host agent" is the parent. The parent calls the subagent (via transfer_task). The subagent processes the task. The subagent returns its result to the parent. The parent's response is "no response from subagent".

    So I think:

    1. Subagent is called
    2. Subagent invokes LLM (LiteLLM)
    3. LLM returns tool_calls with finish_reason: "stop"
    4. Subagent gets the response. The tool_calls are present in res.Calls. res.Stopped is... let me check.

    Looking at streaming.go:

    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
        recordUsage()
        applyXMLFallback()
        finishReason := choice.FinishReason
        if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
            finishReason = chat.FinishReasonToolCalls
        }
        return streamResult{
            ...
            Stopped:           len(toolCalls) == 0,
            FinishReason:      finishReason,
            ...
        }, nil
    }
    

    So when choice.FinishReason == "stop" AND len(toolCalls) > 0, the function returns Stopped: false and FinishReason: "tool_calls".

    This is fine. But wait, what if the adapter blanks out the finish_reason before this? Let me re-check:

    In adapter.go:

    finishReasonStr := choice.FinishReason
    if a.trackUsage && (finishReasonStr == "stop" || finishReasonStr == "length") {
        finishReasonStr = ""
    }
    

    So if trackUsage=true, the finish reason is blanked in the choice. Then the streaming.go check choice.FinishReason == chat.FinishReasonStop fails. So the loop continues. The tool calls are accumulated. Eventually the stream ends.

    When stream ends with EOF, the streaming.go code at line 250-258 (and 244+) handles it:

    finishReason := providerFinishReason  // empty because never set
    if finishReason == "" {
        switch {
        case len(toolCalls) > 0:
            finishReason = chat.FinishReasonToolCalls
        ...
    

    OK so it falls back to "tool_calls". Good.

    But wait! What about the stoppedDueToNoOutput?

    stoppedDueToNoOutput := fullContent.Len() == 0 && len(toolCalls) == 0
    

    If there are tool calls but no content, stoppedDueToNoOutput is false. Good.

    And the return:

    return streamResult{
        ...
        Stopped:           stoppedDueToNoOutput,
        FinishReason:      finishReason,
        ...
    }
    

    So Stopped: false and FinishReason: "tool_calls". The loop continues.

    OK so the streaming.go handles this correctly.

    Hmm, let me look at the actual LiteLLM behavior. Maybe LiteLLM sends the finish_reason in a different chunk than the tool_calls. Let me check:

    Actually, the typical OpenAI streaming format is:

    chunk 1: {choices: [{delta: {role: "assistant", content: ""}}]}
    chunk 2: {choices: [{delta: {tool_calls: [{index: 0, id: "call_xxx", function: {name: "company_search", arguments: ""}}]}}]}
    chunk 3: {choices: [{delta: {tool_calls: [{index: 0, function: {arguments: "{\"datasources\""}}]}}]}
    chunk 4: {choices: [{delta: {tool_calls: [{index: 0, function: {arguments: ": [...]}}]}}]}
    chunk 5: {choices: [{delta: {}, finish_reason: "stop"}]}  or finish_reason: "tool_calls"
    chunk 6 (optional): {usage: {...}, choices: []}
    

    With trackUsage=true:

    • Chunk 5: finish_reason "stop" is blanked. lastFinishReason not updated.
    • Chunk 6: usage present, lastFinishReason is "" → defaults to FinishReasonStop.

    So the response.Choices has FinishReason: FinishReasonStop. Now in streaming.go:

    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
    

    This is TRUE! So the early return is triggered.

    Wait but what about the tool_calls? Are they in the toolCalls variable at this point? Yes, they were accumulated from chunks 2-4. So:

    finishReason := choice.FinishReason  // FinishReasonStop
    if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
        finishReason = chat.FinishReasonToolCalls  // CHANGED
    }
    return streamResult{
        Calls:             toolCalls,  // HAS TOOL CALLS
        ...
        Stopped:           len(toolCalls) == 0,  // FALSE
        FinishReason:      finishReason,  // FinishReasonToolCalls
        ...
    }, nil
    

    OK so this should work correctly.

    Wait, let me look at the order of chunks. What if LiteLLM sends the usage BEFORE the finish_reason chunk? Then:

    • Chunk N: usage present (no finish_reason) → response.Choices has lastFinishReason (or default Stop)
    • Chunk N+1: {choices: [{delta: {}, finish_reason: "stop"}]}

    Hmm, that would mean the lastFinishReason is set BEFORE the actual finish_reason chunk arrives. But it's set from the FIRST chunk that has a non-empty finish_reason. If the tool_calls chunks have finish_reason: null, then lastFinishReason is still empty.

    Actually let me look at the code again:

    finishReason := chat.FinishReason(finishReasonStr)
    // Track the finish reason for when we get usage info
    if finishReason != chat.FinishReasonNull && finishReason != "" {
        a.lastFinishReason = finishReason
    }
    

    OK so the lastFinishReason is updated only when the finish_reason is not null and not empty.

    Then the usage chunk:

    if openaiResponse.JSON.Usage.Valid() {
        ...
        finishReason := a.lastFinishReason
        if finishReason == chat.FinishReasonNull || finishReason == "" {
            finishReason = chat.FinishReasonStop
        }
        ...
    }
    

    If the usage chunk arrives BEFORE the finish_reason chunk, then a.lastFinishReason is empty (because the finish_reason chunk hasn't been processed yet) and the response gets FinishReason: FinishReasonStop.

    Then in streaming.go:

    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
        ...
    }
    

    This is TRUE. The code enters the early-return path.

    If there are tool calls accumulated at this point, Stopped becomes false and FinishReason becomes FinishReasonToolCalls. Good.

    But wait, what if the usage chunk is the LAST chunk? Let me think about this scenario more carefully.

    Let me look at the order more carefully. In OpenAI's stream with stream_options: {include_usage: true}:

    1. role chunk
    2. content/tool_calls chunks
    3. final chunk with finish_reason set (and choices may or may not be empty)
    4. usage chunk (with no choices)

    Wait, actually in some implementations, the usage chunk has choices: []. Let me look at the adapter code again:

    // Use the tracked finish reason instead of hardcoding stop
    finishReason := a.lastFinishReason
    if finishReason == chat.FinishReasonNull || finishReason == "" {
        finishReason = chat.FinishReasonStop
    }
    // OPENAI returns the usage without a finish reason or a choice, so we fake it here
    // and create a new choice for the last event in the stream
    if len(openaiResponse.Choices) == 0 {
        response.Choices = append(response.Choices, chat.MessageStreamChoice{
            FinishReason: finishReason,
        })
    } else {
        // Other openai-compatible providers DO return a choice with finish reason...
        response.Choices[0].FinishReason = finishReason
    }
    if finishReason == chat.FinishReasonStop {
        return response, nil
    }
    

    So when the usage chunk comes in:

    • If choices is empty (typical for OpenAI), a new choice is added with FinishReason: lastFinishReason (defaults to Stop if empty).
    • If choices is not empty (LiteLLM?), the existing choice's finish_reason is overwritten with lastFinishReason.

    So with LiteLLM:

    1. Tool calls chunks come in. finish_reason blanked (if trackUsage), lastFinishReason is empty.
    2. Final chunk: {choices: [{delta: {}, finish_reason: "stop"}]} → blanked to "", lastFinishReason not updated.
    3. Usage chunk: {usage: {...}, choices: [{delta: {}, finish_reason: ""}]} → blanked stays empty, choices has empty finish_reason.
      • openaiResponse.Choices is not empty (1 choice). The code sets response.Choices[0].FinishReason = lastFinishReason.
      • lastFinishReason is empty → defaults to FinishReasonStop.
      • So the response has FinishReason: FinishReasonStop and 1 choice.

    OK so that part should work. But wait, what about LiteLLM behavior? Maybe LiteLLM doesn't send a separate usage chunk. Let me check what happens in that case:

    1. Tool calls chunks.
    2. Final chunk with finish_reason: "stop" AND usage in the same chunk.

    If usage is in the same chunk as finish_reason:

    • finishReasonStr is "stop" → blanked to "" (because trackUsage && finishReason in {stop, length})
    • lastFinishReason not updated (still empty)
    • Then the usage branch is entered. lastFinishReason is empty → defaults to FinishReasonStop.
    • choices has 1 choice (the existing one), finish_reason set to FinishReasonStop.

    Same result. OK so this is fine.

    Let me think about another scenario. What if LiteLLM doesn't send the finish_reason in the chunk where the usage is also present?

    Hmm. Let me look at the actual flow more carefully. Looking at the adapter, the issue could be:

    if a.trackUsage && (finishReasonStr == "stop" || finishReasonStr == "length") {
        finishReasonStr = ""
    }
    

    This is applied to EVERY chunk, not just the usage chunk. So if the tool_calls chunks have finish_reason: "stop" (which is what LiteLLM does), they would be blanked to "".

    But tool_calls chunks in OpenAI typically have finish_reason: null, not "stop". So that's OK.

    Wait, let me check what LiteLLM actually sends. The issue says "finish_reason: 'stop'" for the subagent's tool call response. So:

    • Chunk N: delta: {tool_calls: [{...}]} with finish_reason: null → blanking logic doesn't apply (because finishReasonStr is not "stop" or "length", it's null).
    • Chunk N+1: delta: {} with finish_reason: "stop" → blanked to "" (with trackUsage).

    OK, that's fine. But the lastFinishReason is never updated.

    Let me think about the case where the final chunk has BOTH usage AND finish_reason. In OpenAI's protocol with stream_options.include_usage=true:

    • Usage comes in the FINAL chunk along with finish_reason="stop".

    So:

    • Chunk N: delta: {} with finish_reason: "stop" and usage: {...}.

    In the adapter:

    • finishReasonStr = "stop" → blanked to "" (trackUsage + "stop").
    • lastFinishReason not updated.
    • Then openaiResponse.JSON.Usage.Valid() is true. lastFinishReason is empty → finishReason = FinishReasonStop.
    • choices[0].FinishReason set to FinishReasonStop.
    • Returns.

    In streaming.go:

    • choice.FinishReason == FinishReasonStop → TRUE.
    • Early return path.
    • len(toolCalls) > 0 → finishReason changed to FinishReasonToolCalls. Stopped: false.

    This should be correct. Hmm.

    OK let me actually trace through what the LiteLLM proxy actually sends. Let me check if there's any documentation or existing tests:

  34. MiniMax Assistant

    Now let me actually create a test scenario. The issue says the host agent says "no response from subagent" — let me look more carefully at this. The text "no response from subagent" is the user-facing description; in the code, this corresponds to a ToolCallResult with empty Output field.

  35. MiniMax Assistant

    OK so tool response with empty output gets the placeholder "(no output)" so it's not truly empty. But this isn't where the issue would occur.

    Let me re-read the issue with a fresh perspective. The user is observing:

    • Subagent returns a valid tool_calls response
    • Host agent says "no response from subagent"
    • Host agent doesn't execute the tool call

    The host agent shouldn't need to execute the tool call - that's the subagent's responsibility. So the issue is probably that the subagent's tool call wasn't executed.

    The subagent's tool call wasn't executed because... why? Let me check the streaming.go code once more.

    Actually, wait. Let me look at this from a completely different angle. The issue title says "Subagent tool_calls not handled when using LiteLLM proxy". So the subagent returns tool_calls (via LiteLLM), and these aren't being handled.

    Let me look at how the adapter might fail to detect tool calls from LiteLLM. Maybe LiteLLM sends tool calls in a different format.

  36. MiniMax Assistant

    Now let me look at what happens if LiteLLM sends a NON-STREAMING response. Actually, looking at the issue, LiteLLM is being used as a proxy. It could be used with either streaming or non-streaming. Let me look at the non-streaming code path:

  37. MiniMax Assistant

    OK so handleStream is the main function. Let me look at the issue from a totally different angle. Maybe LiteLLM is not streaming at all but returning a single non-streaming response, OR there's a specific case where the tool calls are not properly handled.

    Actually, let me think about this more carefully. The issue says "the host agent reports 'no response from subagent'". Let me search for any message that might appear like this:

  38. MiniMax Assistant

    OK now I think I need to actually try to reproduce the issue. Let me think about what could cause the host agent to not execute the tool call.

    Actually, the issue says the host agent doesn't execute the tool call. So the host agent receives the subagent's tool calls and doesn't execute them. But the host agent shouldn't be executing subagent tool calls. The subagent should be.

    Wait, let me re-read once more very carefully:

    Summary

    When using cagent with a LiteLLM proxy (OpenAI-compatible API), a subagent can return a valid tool_calls response, but the host agent reports "no response from subagent" and does not execute the tool call.

    So the "host agent" is the parent agent (the one calling the subagent via transfer_task or similar). The "subagent" is the one being called.

    The subagent returns a tool call (e.g., company_search with JSON arguments) and finishes with finish_reason: "stop".

    So the subagent's LLM call returns a tool call.

    The host agent logs "no response from subagent" and does not invoke the tool.

    So the host agent says it didn't get a response from the subagent, and didn't invoke the tool. But which tool? The host agent wasn't going to invoke the subagent's tool (that's the subagent's job). So maybe the host agent didn't invoke the transfer_task properly, or there's some confusion.

    Actually, let me look at this from the perspective of "agent task delegation". The host agent calls the subagent. The subagent returns. The host agent gets the result. The result is the assistant message of the subagent.

    If the subagent's last assistant message has tool_calls but NO content, then GetLastAssistantMessageContent() returns empty string. The host agent receives an empty tool result. The user observes this as "no response from subagent".

    So the bug is: when the subagent's response contains only tool_calls (no content), the host agent sees an empty response.

    The fix should be: when the last assistant message has tool_calls but no content, the parent agent should not receive an empty result. Instead, it should see something meaningful.

    Wait, but the issue also says "does not execute the tool call". So maybe the bug is that the subagent itself doesn't process its own tool calls when using LiteLLM proxy.

    Let me think about LiteLLM behavior again. LiteLLM proxies Gemini models. The default for Gemini models is to NOT use tool_calls (it uses function_call). But when proxied through LiteLLM as an OpenAI-compatible endpoint, the function_call gets translated to tool_calls.

    But there's a subtle issue: when Gemini returns a function call, the finish_reason is "stop" (because Gemini doesn't have a separate "tool_calls" finish reason). So when LiteLLM proxies this as OpenAI-compatible, the result has finish_reason: "stop" and tool_calls: [...].

    OK now let me look at what happens in streaming.go when this is received.

    Actually wait. Let me look at the issue title again: "Subagent tool_calls not handled when using LiteLLM proxy". This suggests that the SUBAGENT's tool_calls aren't being handled. Not the host agent's.

    The subagent calls the LLM. The LLM returns tool_calls. The subagent should handle these tool calls. The subagent doesn't, hence the tool calls aren't executed.

    Let me check if there's a scenario where the subagent's tool calls aren't executed. Looking at streaming.go:

    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
        recordUsage()
        applyXMLFallback()
        finishReason := choice.FinishReason
        if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
            finishReason = chat.FinishReasonToolCalls
        }
        return streamResult{
            Calls:             toolCalls,
            ...
            Stopped:           len(toolCalls) == 0,
            FinishReason:      finishReason,
            ...
        }, nil
    }
    

    So if the adapter returns FinishReason: "stop" and toolCalls is non-empty, this code returns Stopped: false. The loop should continue processing the tool calls.

    But wait, what if the adapter DOESN'T return FinishReason: "stop"? Let me look at the adapter again:

    finishReasonStr := choice.FinishReason
    if a.trackUsage && (finishReasonStr == "stop" || finishReasonStr == "length") {
        finishReasonStr = ""
    }
    

    If trackUsage=true and the chunk has finish_reason: "stop", then finishReasonStr is blanked to "". The streaming.go code checks choice.FinishReason == chat.FinishReasonStop. This is false. So the early-return path is NOT taken.

    The loop continues. The next call to Recv() returns the next chunk, which might be a usage chunk.

    In the usage chunk handling:

    if openaiResponse.JSON.Usage.Valid() {
        ...
        finishReason := a.lastFinishReason
        if finishReason == chat.FinishReasonNull || finishReason == "" {
            finishReason = chat.FinishReasonStop
        }
        if len(openaiResponse.Choices) == 0 {
            response.Choices = append(response.Choices, chat.MessageStreamChoice{
                FinishReason: finishReason,
            })
        } else {
            response.Choices[0].FinishReason = finishReason
        }
        if finishReason == chat.FinishReasonStop {
            return response, nil
        }
    }
    

    Wait, there's a potential issue! if finishReason == chat.FinishReasonStop { return response, nil }. But what if finishReason was supposed to be tool_calls? In our scenario, lastFinishReason is empty (because it was never updated from the previous chunks). So finishReason defaults to FinishReasonStop. So we hit this return response, nil path.

    But wait, the previous finishReasonStr was NOT "stop" for these chunks (it was null). So lastFinishReason was never updated.

    Hmm. Now this is a possible issue. The adapter blanks the finish_reason: "stop" for the main chunk. But then the usage chunk handling doesn't restore the original. It only restores from lastFinishReason, which is empty.

    So when the usage chunk arrives, the response has FinishReason: FinishReasonStop. But this is from the lastFinishReason default, not from the actual provider.

    Let me think about this. In our scenario:

    • Chunk 1: delta: {role: "assistant"}, finish_reason: null
    • Chunk 2: delta: {tool_calls: [...]}, finish_reason: null
    • Chunk 3: delta: {}, finish_reason: "stop" ← THIS IS BLANKED
    • Chunk 4: usage: {...}, finish_reason: null ← USAGE CHUNK, lastFinishReason is empty, defaults to "stop"

    OK so the adapter returns response with FinishReason: FinishReasonStop.

    In streaming.go:

    • Chunk 4 has FinishReason: FinishReasonStop. The check passes. Early return.
    • len(toolCalls) > 0 → finishReason changed to FinishReasonToolCalls. Stopped: false.

    OK so this is fine. The loop continues.

    Now what if the usage is in the same chunk as finish_reason?

    • Chunk 1: delta: {role: "assistant"}, finish_reason: null
    • Chunk 2: delta: {tool_calls: [...]}, finish_reason: null
    • Chunk 3: delta: {}, finish_reason: "stop", usage: {...} ← finish_reason blanked, then usage handling

    In chunk 3:

    • finishReasonStr = "stop" → blanked to ""
    • lastFinishReason not updated
    • openaiResponse.JSON.Usage.Valid() is true
    • lastFinishReason is empty → finishReason = FinishReasonStop
    • response.Choices[0].FinishReason = finishReason = FinishReasonStop
    • if finishReason == chat.FinishReasonStop { return response, nil } → returns

    In streaming.go:

    • chunk 3 with FinishReason: FinishReasonStop. Early return. Same as before.

    So in both cases, the code handles it correctly.

    Hmm. Let me actually try to run a test to see what happens. Let me set up a fake LiteLLM-like provider and see what happens.

    Actually, let me look at the issue more carefully. Maybe the issue is in delta.FunctionCall vs delta.ToolCalls. LiteLLM might send function_call instead of tool_calls.

    Actually no, the issue explicitly says "tool_calls" so that's not the issue.

    Let me look at the other angle. Maybe the issue is in how the chat completion messages are converted back to the openai-go format. Let me look at convertMessages:

  39. MiniMax Assistant

    OK. Let me actually take a different approach and try to write a test to reproduce the issue. Let me see what tests exist:

  40. MiniMax Assistant

    OK so the tests use mockStream directly. They don't go through the actual OpenAI adapter. So the streaming.go logic is tested with direct chat.MessageStream chunks.

    Let me write a test that mimics what LiteLLM would send, going through the actual adapter:

  41. MiniMax Assistant

    Now let me create a quick test to see how the adapter behaves with LiteLLM-like output:

  42. MiniMax Assistant

    OK so the adapter works as expected. The tool_calls are accumulated properly. The final chunk has FinishReason: "stop" and the usage is present.

    Now let me trace through the streaming.go logic for this stream:

    1. Recv 1: role="assistant", content=""
    2. Recv 2: tool_calls=[{id=call_123, name=company_search, args=""}]
    3. Recv 3: tool_calls=[{args="{"datasources":...}"}] → toolCalls in stream has accumulated args
    4. Recv 4: FinishReason="stop", usage present

    In streaming.go:

    • Recv 1: choice.FinishReason == "", not stop/length. Not early return. providerFinishReason stays "". Process content delta.
    • Recv 2: not early return. Process tool calls delta. toolCallIndex[call_123] = 0. toolCalls[0] = {id=call_123, type=function, name=company_search, args=""}.
    • Recv 3: not early return. Process tool calls delta. toolCalls[0].args += "{\"datasources\":...}".
    • Recv 4: choice.FinishReason == "stop" → EARLY RETURN.

    In the early return:

    finishReason := choice.FinishReason  // "stop"
    if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
        finishReason = chat.FinishReasonToolCalls  // CHANGED
    }
    return streamResult{
        Calls:             toolCalls,
        Content:           fullContent.String(),
        ...
        Stopped:           len(toolCalls) == 0,  // false
        FinishReason:      finishReason,  // "tool_calls"
        Usage:             messageUsage,
    }, nil
    

    So streamResult.Calls contains the tool call, streamResult.Stopped is false, streamResult.FinishReason is "tool_calls". The loop continues. Good.

    So based on this analysis, the streaming logic handles the LiteLLM case correctly. Let me check the issue description once more.

    Actual

    Host agent reports there is "no response from subagent" even though the subagent response contains a valid tool_calls entry.

    Hmm. Maybe the issue is when the subagent returns and the subagent's session's last message is the assistant tool_calls message with NO content. Then GetLastAssistantMessageContent() returns empty string.

    Let me check when recordAssistantMessage would skip the message:

    • if strings.TrimSpace(res.Content) == "" && len(res.Calls) == 0 → skip.

    So when res.Content == "" and res.Calls > 0, the message IS recorded. The session has an assistant message with only tool_calls.

    Then GetLastAssistantMessageContent() iterates over messages in reverse and looks for an assistant message with non-empty content. The tool_calls-only message has empty content, so it returns empty string.

    Hmm, so this scenario is possible: the subagent's last assistant message has only tool_calls (no content), and the parent gets an empty result.

    But wait, the issue says the parent gets the tool_calls. Let me re-read:

    Actual

    Host agent reports there is "no response from subagent" even though the subagent response contains a valid tool_calls entry. The requested tool call is not executed.

    So the user is observing:

    1. The subagent response contains a valid tool_calls entry.
    2. The host agent doesn't execute the tool call.
    3. The host agent says "no response from subagent".

    Maybe what's happening is:

    1. Subagent's LLM call returns tool_calls.
    2. The subagent's handleStream returns with Stopped: false, Calls: [tool_call].
    3. The subagent's loop processes the tool_calls (this should work).
    4. The subagent's LLM is called again.
    5. The new LLM response is the final response.

    So in the normal case, the subagent would continue processing. But what if the subagent's loop STOPS at the tool_calls? Let me see...

    Hmm. Let me look at the loop.go to see the Stopped logic more carefully.

  43. MiniMax Assistant

    Hmm, the loop continues regardless of res.Stopped value. The Stopped value affects the LATER part of the loop.

    Let me look further:

  44. MiniMax Assistant

    So if res.Stopped = true, the loop exits after processing the tool calls. If res.Stopped = false, the loop continues.

    For our scenario, with LiteLLM sending finish_reason="stop" with tool_calls, the streaming.go correctly returns Stopped: false. So the loop continues. The subagent should process the tool_calls.

    OK I think I need to actually look at this with a concrete test scenario. Let me write a test:

  45. MiniMax Assistant

    OK so the streaming.go handles the LiteLLM case correctly: Stopped=false, FinishReason="tool_calls". The tool calls are correctly captured. The loop should continue.

    Let me now look at the actual scenario the issue describes. The issue says the host agent reports "no response from subagent" and the tool call is NOT executed. This contradicts my analysis - the tool call SHOULD be executed.

    Let me check the original commit/PR for this fix:

  46. MiniMax Assistant

    Hmm interesting. Let me check the test for this:

  47. MiniMax Assistant

    OK these tests are about validating the target agent is in the sub-agents list. Not directly related to our issue.

    Let me look at the most recent changes that might be related:

  48. MiniMax Assistant

    Let me look at the streaming handling one more time and focus on the actual issue. Let me think about this:

  49. MiniMax Assistant

    OK now I see it. The key insight is:

    The current streaming.go logic at line 270-283 returns Stopped: stoppedDueToNoOutput which is len(toolCalls) == 0 && fullContent.Len() == 0. This is only TRUE when there's no content AND no tool calls.

    But there's an asymmetry: the early-return path at line 146 uses Stopped: len(toolCalls) == 0. This is different! Let me check this again:

  50. MiniMax Assistant

    Both paths return Stopped: <tool_calls == 0> essentially. So that's fine.

    Hmm. Let me look at what could possibly go wrong. Let me check the related code in loop.go for what happens with Stopped:

  51. MiniMax Assistant

    OK. Let me now actually take a different approach. The issue description states the user can reproduce this consistently. Let me check if there's some specific code path that might be wrong.

    Looking at the issue once more: the user says the LLM is "gemini-pro via LiteLLM proxy (OpenAI-compatible)". And the LLM returns finish_reason: "stop" with a tool call.

    Wait, let me read the issue's exact wording very carefully one more time:

    Summary

    When using cagent with a LiteLLM proxy (OpenAI-compatible API), a subagent can return a valid tool_calls response, but the host agent reports "no response from subagent" and does not execute the tool call.

    Actual

    Host agent reports there is "no response from subagent" even though the subagent response contains a valid tool_calls entry. The requested tool call is not executed.

    So:

    • Subagent returns a valid tool_calls response
    • Host agent says "no response from subagent"
    • The tool call is not executed

    The user is interpreting the host agent's behavior as "no response from subagent". The actual technical issue is likely that:

    1. The subagent's response is properly received but the LLM call returns a tool_calls with no content
    2. The host agent's interpretation is that the subagent returned "no response"

    Let me actually search for the message the user is reporting as "no response from subagent":

  52. MiniMax Assistant

    The error message "no response from subagent" isn't in the code. The user is paraphrasing what they see. So the actual issue is something different.

    Let me think about this from the symptoms. The user observes:

    1. A subagent returns with tool_calls.
    2. The tool call is not executed.

    The "tool call is not executed" is the key. So somehow the subagent (or host agent?) is receiving tool_calls but not executing them.

    Wait, actually I missed something. Let me re-read more carefully:

    The host agent logs "no response from subagent" and does not invoke the tool.

    OK so the host agent logs something (maybe an error like "no response from subagent"). The host agent doesn't invoke the tool. The tool here refers to the subagent's tool call.

    I think the host agent is being told by the subagent's response to do something (via tool_call), but instead the host agent thinks the subagent returned nothing.

    Hmm, but how does a subagent return a tool_call to the host agent? The subagent just runs and returns its session. The host agent sees the session's last message.

    Wait, let me look at the openai chat completions format. Maybe the issue is that when LiteLLM proxies the response, the streamed chunks are different. Let me look at the typical format for Gemini responses:

    Actually, looking more carefully at the issue:

    The subagent response includes a valid tool call object (type: function, name: company_search, arguments: {"datasources": ["confluence", "github", "gdrive"], "query": "LiteLLM usage teams integrations standards"}).

    This is the format of the SUBAGENT's response. So the subagent's LLM call returns this. And the host agent should then process the subagent's tool calls.

    Wait, no. The subagent processes ITS OWN tool calls. The host agent processes the subagent's RESPONSE.

    Unless... the architecture is different. Let me re-check the architecture:

  53. MiniMax Assistant

    Let me look at how a tool call is processed. Maybe there's an issue with how the tool call is detected when the LLM only returns a tool call with no content:

  54. MiniMax Assistant

    OK let me take a different approach and try to actually trace what would happen with the user's specific setup. Let me create a comprehensive test:

  55. MiniMax Assistant

    Both LiteLLM test cases work correctly: the tool calls are detected, Stopped=false, FinishReason=tool_calls. So the streaming.go and oaistream adapter are handling this correctly.

    OK so the streaming side is fine. The issue must be elsewhere. Let me look at how the messages are sent back to the LLM after a tool call. When the subagent receives a tool_call from LiteLLM, the subagent processes it. The subagent's session now has the tool_calls message and the tool result message. Then the subagent calls LLM again.

    But wait, what if the parent (host) agent is the one receiving the tool_calls? Let me think...

    OK here's another interpretation:

    1. Host agent calls LLM via LiteLLM proxy.
    2. LiteLLM proxy returns tool_calls with finish_reason: "stop".
    3. Host agent's streaming.go correctly returns the tool calls.
    4. Host agent processes the tool calls.
    5. ???

    Hmm. Let me check if there's something specific about LiteLLM that might break things.

    Actually, let me check what happens when the assistant message has tool_calls and no content. When the LLM is called next time, this message is sent back. Let me check:

  56. MiniMax Assistant

    OK so the conversion looks correct. The tool calls are properly converted.

    Hmm. Let me look at this from yet another angle. The issue says "the host agent does not execute the tool call". Let me look at the architecture. The host agent calls transfer_task to the subagent. The subagent runs. The subagent's session accumulates messages. The subagent's final assistant message is the response. The response is sent back as the tool result of transfer_task.

    If the subagent's final assistant message has only tool_calls (no content), then GetLastAssistantMessageContent() returns empty string. The host agent sees an empty tool result.

    Wait. Let me look at the issue from yet ANOTHER angle. Maybe the issue is that when LiteLLM proxies a Gemini tool call, the response is in a non-streaming format. Let me check what happens when LiteLLM returns a non-streaming response.

    Actually, all providers are required to stream. Let me check:

  57. MiniMax Assistant

    OK so only streaming. Let me now look at the openai provider stream_options setting:

  58. MiniMax Assistant

    So with trackUsage=true, the OpenAI provider sends stream_options.include_usage=true. This makes OpenAI send a separate usage chunk at the end.

    Hmm, but does LiteLLM support stream_options.include_usage? If not, the usage chunk might not be sent, and the adapter might miss it.

    Let me check what happens when LiteLLM doesn't send a usage chunk:

  59. MiniMax Assistant

    Hmm, interesting! When there's NO separate usage chunk and the finish_reason: "stop" is in the last chunk, the adapter blanks out the finish reason (because trackUsage=true), so the streaming.go never enters the early-return path. Instead it falls through to the EOF path.

    The EOF path correctly identifies Stopped: false, FinishReason: tool_calls. So this is still handled correctly!

    Wait, but I missed something. The 4th chunk had finish_reason: "stop" blanked to "" in the adapter. So choice.FinishReason == "stop" is FALSE. The early-return path is NOT triggered.

    But wait, look at the test output:

    Recv: FinishReason="", Content="", ToolCalls=0, Usage=false
    

    The 4th chunk has FinishReason="". So the streaming.go sees no finish reason and falls through to the EOF path. Then it correctly infers FinishReason: "tool_calls" because there are tool calls.

    OK so this is also handled correctly. Let me check one more scenario - what if LiteLLM returns the tool calls in a single chunk without proper formatting:

  60. MiniMax Assistant

    FOUND THE BUG! Look at this:

    When trackUsage=false:

    • Recv: FinishReason="stop", Content="", ToolCalls=1, Usage=false
    • EARLY RETURN: Calls=0, Content="", Stopped=true, FinishReason="stop", Usage=false

    The tool calls are NOT being captured! Why? Because in the adapter with trackUsage=false, the finish reason is NOT blanked. So choice.FinishReason == "stop" is TRUE. The early-return path is triggered BEFORE the tool calls are processed.

    Wait, but trackUsage=false is the default? Let me check:

  61. MiniMax Assistant

    OK so TrackUsage defaults to true (when nil → true). So trackUsage=true is the default. So my bug finding doesn't apply in the default case.

    Wait, but in my test, I see that with trackUsage=true, when the finish_reason="stop" comes BEFORE the tool calls deltas are processed... wait no, the tool_calls deltas come FIRST, then finish_reason. Let me re-check.

    Actually no, looking at my test output:

    Recv: FinishReason="", Content="", ToolCalls=0, Usage=false
    Recv: FinishReason="stop", Content="", ToolCalls=1, Usage=false
    

    The second chunk has BOTH tool_calls AND finish_reason="stop". In the streaming.go loop, we first check the FinishReason. If it's "stop", we early-return WITHOUT processing the tool calls!

    Wait, but the tool calls should be processed BEFORE the finish_reason check. Let me look at the streaming.go loop order:

  62. MiniMax Assistant

    THERE'S THE BUG! Look at the order in the streaming.go loop:

    1. Check choice.FinishReason == Stop/Length → early return WITHOUT processing tool calls.

    The finish_reason check happens BEFORE the tool_calls processing! So if a chunk has BOTH tool_calls and finish_reason="stop" (which is what LiteLLM does!), the tool calls are NEVER processed.

    This is the bug! The fix is to process tool calls BEFORE checking the finish reason.

    Wait, but my earlier test cases showed the tool calls were processed correctly. Let me re-check those tests:

    Test case 1:

    data: {..., delta: {role: "assistant"}, finish_reason: null}
    data: {..., delta: {tool_calls: [{name: ...}]}, finish_reason: null}
    data: {..., delta: {tool_calls: [{arguments: ...}]}, finish_reason: null}
    data: {..., delta: {}, finish_reason: "stop", usage: {...}}
    

    Here, the tool_calls chunks have finish_reason: null, so the early-return isn't triggered. The tool_calls are accumulated correctly. The final chunk has finish_reason: "stop" and the tool_calls are processed correctly.

    But in the LiteLLM scenario, the structure might be:

    data: {..., delta: {role: "assistant"}, finish_reason: null}
    data: {..., delta: {tool_calls: [{name: ..., arguments: ...}]}, finish_reason: "stop"}
    

    The second chunk has BOTH tool_calls AND finish_reason="stop". In the streaming.go loop:

    1. Check FinishReason == "stop" → TRUE → early return.
    2. Tool calls are NEVER processed.

    This matches my test output:

    Recv: FinishReason="", Content="", ToolCalls=0, Usage=false
    Recv: FinishReason="stop", Content="", ToolCalls=1, Usage=false
    EARLY RETURN: Calls=0, Content="", Stopped=true, FinishReason="stop", Usage=false
    

    The tool calls (ToolCalls=1 in the chunk) are NEVER accumulated. Calls=0 in the early return.

    THIS IS THE BUG! When a chunk contains both tool_calls and finish_reason: "stop"/"length", the streaming.go loop early-returns BEFORE processing the tool calls. The tool calls are lost.

    Now let me verify that LiteLLM actually does this. Looking at the OpenAI streaming protocol, when a model returns a tool call, the typical format is:

    delta: {role: "assistant"}   # no finish_reason
    delta: {tool_calls: [{index: 0, id: "...", function: {name: "..."}}]}   # no finish_reason (or null)
    delta: {tool_calls: [{index: 0, function: {arguments: "..."}}]}   # no finish_reason (or null)
    delta: {}   # finish_reason: "tool_calls" or "stop"
    

    But LiteLLM might combine the last tool_call chunk with the finish_reason chunk:

    delta: {tool_calls: [{index: 0, function: {arguments: "..."}}]}   # finish_reason: "stop"
    

    Let me check the actual LiteLLM behavior. The issue says "finish_reason: 'stop'" with a tool call. So this is the LiteLLM format.

    So the fix is to process tool calls BEFORE checking the finish reason. Let me look at the streaming.go code:

  63. MiniMax Assistant

    So I need to move the finish_reason check AFTER the tool_calls processing. The fix is to reorder the checks in the streaming.go loop.

    Let me also verify the applyXMLFallback ordering. The XML fallback is meant to extract tool calls from accumulated content if no structured tool calls were received. It should still be called in the early-return path.

    Let me write the fix:

  64. MiniMax Assistant

    Now I have a clearer understanding. The fix should:

    1. Process tool_calls deltas BEFORE checking the finish reason.
    2. The finish_reason check should still happen, but AFTER tool_calls processing.

    Let me make the fix:

  65. MiniMax Assistant

    Now let me look at how the order should be fixed. The simplest fix is to process tool_calls FIRST, then check finish_reason. Let me apply the fix:

  66. MiniMax Assistant

    Now let me see what the file currently looks like and design the fix. I'll move the finish_reason check to AFTER the tool_calls processing:

  67. MiniMax Assistant

    Now let me design the fix. I'll move the tool_calls processing block to BEFORE the finish_reason check. The finish_reason tracking can also be moved earlier.

    Let me apply the fix:

  68. MiniMax Assistant

    Now let me apply the actual fix using a Python script:

  69. MiniMax Assistant

    Hmm, finish_pos < tool_call_start. That means the finish_marker comes BEFORE the tool_call_marker. Let me re-check:

  70. MiniMax Assistant

    OK so the current order is:

    1. Early return for stop/length
    2. Track provider finish reason
    3. Handle tool calls
    4. Handle content

    The fix is to reorder so that tool_calls are processed BEFORE the finish_reason check. Let me think about the best approach.

    The cleanest fix would be to move the Handle tool calls block to before the if choice.FinishReason == chat.FinishReasonStop check.

    But actually, the issue is more subtle. Let me think about it:

    The early-return triggers when FinishReason == "stop" || FinishReason == "length". If a chunk has both tool_calls AND finish_reason: "stop", we want to:

    1. Process the tool_calls first
    2. Then check finish_reason

    But if we just move tool_calls before finish_reason, we'd handle the case where tool_calls come in a chunk with finish_reason. But we'd also be doing tool_calls processing for every chunk, including ones with content. That's OK because the existing code does that.

    Actually, the existing code already processes tool_calls BEFORE content. So the order in the loop is:

    1. Check finish_reason (early return)
    2. Track providerFinishReason
    3. Process tool_calls
    4. Process content

    The fix is to:

    1. Track providerFinishReason (so we don't lose it)
    2. Process tool_calls
    3. Process content
    4. Check finish_reason (early return)

    Let me write the fix:

  71. MiniMax Assistant

    Good. The fix is applied. Now the order is:

    1. Track providerFinishReason (early in the loop, before any processing)
    2. Handle tool calls
    3. Check FinishReason (early return)
    4. Handle reasoning content
    5. Handle content

    Let me run the test to verify the fix works:

  72. MiniMax Assistant

    Wait, my test was based on the OLD code that I had to mirror in my test. Let me update my test to use the new code:

    Actually, my test is a separate Go program. It has its own copy of the streaming logic. So I need to update my test to mirror the new fix.

    Let me update my test program to use the fixed logic:

  73. MiniMax Assistant

    Hmm wait, my test code doesn't trigger the early-return path in some cases. Let me check why. With trackUsage=true, the adapter blanks the finish reason, so the early-return isn't triggered. That's expected. Let me adjust the test:

    Actually the key thing to notice is:

    • With trackUsage=false (the OLD broken behavior): Calls=0, Stopped=true → TOOL CALLS LOST
    • With my FIX: Calls=1, Stopped=false → TOOL CALLS PRESERVED

    The fix works! Let me run the existing tests to make sure I didn't break anything:

  74. MiniMax Assistant

    Good, the build succeeds. Let me now run the existing tests to make sure they still pass:

  75. MiniMax Assistant

    There's a test failure. Let me see what failed:

  76. MiniMax Assistant

    Let me see if this test was failing before my change:

  77. MiniMax Assistant

    OK so this test was already failing before my change. Let me run the rest of the tests:

  78. MiniMax Assistant

    Same single test failure. This is pre-existing. Let me check if all OTHER tests pass:

  79. MiniMax Assistant

    Only TestDoCompactAfterHookFires fails, and that was pre-existing. Let me also run the broader tests:

  80. MiniMax Assistant

    All provider tests pass. Let me also check more tests:

  81. MiniMax Assistant

    Let me check if this test was failing before:

  82. MiniMax Assistant

    OK so both pre-existing failures are environmental (running as root, sqlite permissions etc), not related to my change.

    Now let me look at my fix once more to make sure it's correct and complete:

  83. MiniMax Assistant

    The fix is in place. Now I need to write a test for this fix. But the task says I shouldn't modify or add tests. So let me just verify the fix works correctly with a temporary script.

    Actually wait, the task says:

    UNDER NO CIRCUMSTANCES should you modify existing tests or add new tests to the repository.

    OK so I can't add tests. Let me also make sure I haven't broken any existing tests:

  84. MiniMax Assistant

    Only the pre-existing failure. Let me run with verbose to count tests:

  85. MiniMax Assistant

    Only the pre-existing failure. All other tests pass.

    Now let me also write a small test program to verify my fix:

  86. MiniMax Assistant

    The adapter correctly receives the tool calls. Now let me test the full flow including streaming.go:

  87. MiniMax Assistant

    Hmm wait, the FinishReason should be "tool_calls" not "stop" for the cases with tool calls. Let me look at my test code:

    Actually wait, the test code in /tmp/test_full_flow.go is my own test logic. The real streaming.go does:

    if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
        finishReason = chat.FinishReasonToolCalls
    }
    

    I have that same logic in my test code. Let me re-look at my test... actually, looking at the output, FinishReason: "stop" for the LiteLLM bug scenario test. That should be "tool_calls" if my logic is correct.

    Oh I see, my test does NOT do the conversion in the EOF path. The conversion only happens in the early-return path. Let me check...

    Actually looking at my test:

    • LiteLLM bug scenario: finish_reason="stop", tool_calls present.
    • After processing tool_calls, the early-return is triggered (because finish_reason is "stop").
    • The conversion happens: if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 { finishReason = chat.FinishReasonToolCalls }.
    • So finishReason should be "tool_calls".

    But the output shows "stop". Let me check my test code...

    Wait, let me re-read my test:

    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
        finishReason := choice.FinishReason
        if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
            finishReason = chat.FinishReasonToolCalls
        }
        return streamResult{
            ...
            FinishReason: finishReason,
        }, nil
    }
    

    Hmm, this should work. Let me check the actual SSE data for the first test case:

    Test 1 data:

    data: {delta: {role: "assistant"}, finish_reason: null}
    data: {delta: {tool_calls: [...]}, finish_reason: "stop"}
    

    Wait! With trackUsage=false:

    • Chunk 1: role, no finish_reason
    • Chunk 2: tool_calls, finish_reason="stop"

    In the adapter (trackUsage=false):

    • Chunk 1: FinishReason="" (null), Role="assistant"
    • Chunk 2: FinishReason="stop", ToolCalls=[...]

    In my streaming test (which uses the FIXED logic):

    • Iteration 1: choice.FinishReason="" (not stop), so we don't enter the early-return. Process the chunk. No tool_calls (only role). Continue.
    • Iteration 2: choice.FinishReason="stop". Track providerFinishReason="stop". Process tool_calls (1 call). continue. Then check finish_reason: choice.FinishReason == "stop" → TRUE. Early return.
      • finishReason := choice.FinishReason = "stop"
      • len(toolCalls) > 0 → finishReason = "tool_calls"
      • Return: Calls=1, FinishReason="tool_calls"

    But the output shows FinishReason="stop"! Let me debug this. Maybe the test is calling the old (broken) logic.

    Actually I think the issue is that my test code defines its own handleStream function but the actual streaming.go is still being used in the actual code. Let me check:

    Actually no, my test program is a standalone Go program, not part of the docker-agent package. So it has its own logic.

    Wait, looking at my test code more carefully:

    res, err := handleStream(context.Background(), adapter, a, agentTools, sess, m, nil, events)
    

    I call my own handleStream function. But the output shows FinishReason: "stop", which means my conversion code isn't being executed. Let me check my test code again:

  88. MiniMax Assistant

    The conversion code is there. Let me check more carefully:

  89. MiniMax Assistant

    OK so the adapter correctly returns the chunks. The issue must be in my test code logic. Let me check:

  90. MiniMax Assistant

    Ah I see the issue! The tool_calls block ends with continue. So after processing tool_calls, the code goes to the next iteration without checking finish_reason. So the finish_reason check NEVER happens for the chunk with tool_calls.

    So my fix is broken! The tool_calls are processed but the finish_reason check is skipped due to continue. Let me fix this:

  91. MiniMax Assistant

    So the early-return for finish_reason comes AFTER the tool_calls block but the tool_calls block has a continue. So when both tool_calls and finish_reason are present, the tool_calls are processed, then continue skips the finish_reason check, and the next chunk might not exist (EOF).

    When EOF is reached, the code falls through to the EOF path, which correctly infers FinishReason: tool_calls because there are tool calls.

    Let me verify this with the actual code:

  92. MiniMax Assistant

    OK let me actually re-trace the actual streaming.go with my fix. The behavior I want is:

    • LiteLLM sends: tool_calls + finish_reason="stop" in same chunk
    • The fix should:
      1. Process the tool_calls (added to toolCalls)
      2. Check the finish_reason
      3. Early return with the right FinishReason

    But the continue in the tool_calls block prevents step 2. So the fix doesn't work properly.

    Let me think about this. The issue is that the continue skips the rest of the iteration. So when tool_calls and finish_reason are in the same chunk, the tool_calls are processed but the finish_reason is NOT used.

    Wait, but the early-return is also BEFORE the continue. Let me re-trace:

    With the FIXED code:

    1. Track providerFinishReason
    2. Process tool_calls (with continue at the end)
    3. Check finish_reason (early return)

    The continue at the end of the tool_calls block skips steps after the tool_calls block. So step 3 (check finish_reason) is NEVER reached when there are tool_calls in the chunk.

    So the early-return only happens when:

    • The chunk has NO tool_calls AND has finish_reason=stop
    • OR the chunk has NO tool_calls AND has finish_reason=null (we fall through to EOF)

    This means:

    • If a chunk has tool_calls, the finish_reason is never checked immediately.
    • We rely on the next chunk (or EOF) to trigger the early-return.

    For the LiteLLM bug scenario:

    • Chunk 1: no tool_calls, no finish_reason → fall through.
    • Chunk 2: tool_calls, finish_reason="stop" → tool_calls processed, then continue. Loop iteration ends.
    • Next call to Recv() returns EOF → break out of loop.
    • EOF path: providerFinishReason="stop", toolCalls has 1 call.
    • In the EOF path, the code does:
      finishReason := providerFinishReason  // "stop"
      if finishReason == "" {
          switch {...}
      }
      switch {
      case finishReason == chat.FinishReasonToolCalls && len(toolCalls) == 0:
          finishReason = chat.FinishReasonNull
      case finishReason == chat.FinishReasonStop && len(toolCalls) > 0:
          finishReason = chat.FinishReasonToolCalls  // CHANGED!
      }
      

    So the EOF path correctly converts "stop" → "tool_calls" when there are tool calls.

    Let me run the actual tests with the fix to confirm:

  93. MiniMax Assistant

    The shell ate my command. Let me try a simpler approach - just run a test from the runtime package using the existing test infrastructure:

  94. MiniMax Assistant

    Let me write a more direct test using the actual handleStream function in the docker-agent package. Actually since handleStream is unexported, let me write a test that uses it via the LocalRuntime:

  95. MiniMax Assistant

    Let me look at how the runtime tests use the actual streaming logic:

  96. MiniMax Assistant

    OK so the tests use mockProvider with mockStream and streamBuilder. Let me write a test scenario that uses these:

  97. MiniMax Assistant

    OK so the mockStream takes chat.MessageStreamResponse directly. This bypasses the oaistream adapter. So existing tests don't exercise the bug scenario (where a single chunk has both tool_calls and finish_reason).

    Let me write a test that goes through the actual oaistream adapter with a LiteLLM-like stream. I'll write it as a temporary test file outside the repo, but I need to use the actual streaming.go logic.

    Let me create a temporary test program that imports the docker-agent packages and tests the actual logic:

  98. MiniMax Assistant

    Hmm, this approach won't easily test the unexported handleStream function. Let me think of a different approach.

    Actually, the best way is to write a test inside the pkg/runtime package. But the task says not to add tests. Let me create the test in a temporary location and delete it later:

  99. MiniMax Assistant

    Good, the sed worked. Let me run the test:

  100. MiniMax Assistant

    The test is timing out. There's a bug in my test - probably the http server isn't sending the response properly. Let me check:

  101. MiniMax Assistant

    Test hangs - the NewChannelSink(nil) might be the issue. Let me check:

  102. MiniMax Assistant

    OK so NewChannelSink expects a channel. Let me update the test:

  103. MiniMax Assistant

    The test passes with my fix. The tool calls are correctly preserved, Stopped=false, FinishReason=tool_calls.

    Now let me verify that the OLD code would have failed this test:

  104. MiniMax Assistant

    The OLD code FAILS the test as expected. The panic on res.Calls[0] shows that res.Calls is empty (length 0). This confirms the bug exists in the original code and my fix resolves it.

    Let me run the test with my fix to confirm it passes:

  105. MiniMax Assistant

    Excellent! Now let me clean up the temporary test file (since the instructions say not to add tests):

  106. MiniMax Assistant

    Good, the test file is removed. Now let me also re-run the existing tests to make sure nothing else is broken:

  107. MiniMax Assistant

    Only the pre-existing TestDoCompactAfterHookFires failure. Good.

    Now let me also run the model tests:

  108. MiniMax Assistant

    All provider tests pass.

    Now let me look at the fix once more to make sure it's clean and correct:

  109. MiniMax Assistant

    Hmm wait, there's still a problem with my fix. Let me look at the order:

    1. Track providerFinishReason
    2. Process tool_calls (with continue at end)
    3. Check finish_reason (early return)
    4. Process reasoning content
    5. Process content

    If a chunk has BOTH tool_calls AND finish_reason:

    • Step 1: Track finish_reason ✓
    • Step 2: Process tool_calls → continue ← THIS SKIPS step 3
    • Loop continues, next iteration

    So the early-return never triggers for chunks with tool_calls. The fix relies on the NEXT chunk to have finish_reason, OR the EOF path to handle it.

    For LiteLLM:

    • Chunk 1: role, no finish_reason
    • Chunk 2: tool_calls + finish_reason="stop"
    • EOF

    In chunk 2: tool_calls are processed, finish_reason is tracked. continue. Loop iteration ends. Next call to Recv() returns EOF. Break out of loop. EOF path: providerFinishReason="stop", toolCalls has 1 call.

    • finishReason := providerFinishReason = "stop"
    • switch case finishReason == chat.FinishReasonStop && len(toolCalls) > 0 → finishReason = "tool_calls" ✓

    So the EOF path correctly handles it. The fix works.

    But wait, what if LiteLLM sends the tool_calls and finish_reason in the same chunk, AND then there's another chunk after? Like:

    • Chunk 1: tool_calls + finish_reason="stop"
    • Chunk 2: usage info (no choices)

    With trackUsage=true:

    • The adapter blanks out finish_reason="stop" in chunk 1. So when we see chunk 1, finish_reason is "" in the choice. We process tool_calls. continue. Loop iteration ends.
    • Next iteration: chunk 2 with usage. We see FinishReason (set to lastFinishReason, defaulting to Stop).
    • We check finish_reason in step 3 (after tool_calls processing). The chunk has no tool_calls, so we don't enter the tool_calls block. We go to step 3. finish_reason is "stop" → early return. ✓

    With trackUsage=false:

    • The adapter doesn't blank finish_reason. Chunk 1 has FinishReason="stop" and tool_calls.
    • Step 1: Track providerFinishReason="stop"
    • Step 2: Process tool_calls. continue.
    • Loop iteration ends. Next call to Recv() returns EOF (if no more chunks) OR the next chunk.
    • If EOF: EOF path correctly handles it.
    • If next chunk has finish_reason: that chunk triggers the early-return.

    OK the fix handles all the cases I can think of.

    But wait, what about the case where the tool_calls are completely in their own chunk (no finish_reason), and then a SEPARATE chunk has the finish_reason? Like:

    • Chunk 1: role
    • Chunk 2: tool_calls (no finish_reason)
    • Chunk 3: finish_reason="stop"

    With my fix:

    • Chunk 1: role, no tool_calls, no finish_reason. No early return.
    • Chunk 2: tool_calls processed. continue.
    • Chunk 3: No tool_calls. Check finish_reason: "stop" → early return. ✓

    OK that works too. The fix is correct.

    Now let me also think about edge cases:

    Edge case 1: Empty stream

    • Only EOF, no chunks.
    • The loop exits without entering. EOF path: no content, no tool_calls → stoppedDueToNoOutput=true. ✓

    Edge case 2: Multiple tool calls in different chunks with finish_reason at the end

    • Chunk 1: role
    • Chunk 2: tool_calls 1
    • Chunk 3: tool_calls 2
    • Chunk 4: finish_reason="stop"

    With my fix:

    • Chunk 1, 2, 3: tool_calls processed.
    • Chunk 4: no tool_calls. finish_reason check: early return with Stopped=false. ✓

    Edge case 3: Multiple tool calls with finish_reason in the LAST tool_calls chunk

    • Chunk 1: role
    • Chunk 2: tool_calls 1
    • Chunk 3: tool_calls 2 + finish_reason="stop"

    With my fix:

    • Chunk 1: no early return.
    • Chunk 2: tool_calls processed.
    • Chunk 3: tool_calls processed. finish_reason tracked. continue.
    • EOF: EOF path → finishReason = "stop" → "tool_calls" because toolCalls > 0. ✓

    Edge case 4: Standard OpenAI with finish_reason="tool_calls"

    • Chunk 1: role
    • Chunk 2: tool_calls
    • Chunk 3: finish_reason="tool_calls"

    With my fix:

    • Chunk 1, 2: tool_calls processed.
    • Chunk 3: no tool_calls. finish_reason="tool_calls". Early return. finishReason stays "tool_calls". Stopped=false. ✓

    Edge case 5: All content, no tool calls

    • Chunk 1: role
    • Chunk 2: content "hello"
    • Chunk 3: finish_reason="stop"

    With my fix:

    • Chunk 1, 2: content processed.
    • Chunk 3: no tool_calls. finish_reason="stop". Early return. finishReason="stop". Stopped=true. ✓

    All edge cases work correctly with my fix.

    Now let me also clean up:

  110. MiniMax Assistant

    All temporary files are cleaned up. Let me look at the final state of the fix:

  111. MiniMax Assistant

    The fix looks good. Let me view the resulting file in full to confirm:

  112. MiniMax Assistant

    Now let me also look at the issue from yet another angle. The user mentions "host agent" and "subagent" - I want to make sure the fix works for both directions (i.e., when the host agent or the subagent receives a tool_calls response).

    Actually, both scenarios use the same handleStream function in the runtime. So the fix applies to both.

    Let me also check if there are similar bugs in other parts of the code (e.g., the Responses API):

  113. MiniMax Assistant

    The Responses API uses a different stream adapter (response_stream.go). But for LiteLLM, it's likely using the chat completions API. Let me focus on what the issue describes.

    Let me run more tests to make sure everything works:

  114. MiniMax Assistant

    All subagent and transfer_task tests pass.

    Now let me also verify that I haven't broken the existing tests. Let me focus on the xml_tool_calls_test.go since that uses the handleStream function too:

  115. MiniMax Assistant

    All XML and tool call tests pass.

    Let me also look at the full diff to verify my fix is minimal and clean:

  116. MiniMax Assistant

    The fix is minimal and clean. The key change is:

    • Move the finish_reason early-return check to AFTER the tool_calls processing block.
    • The providerFinishReason tracking stays in its original position (now early in the loop) since it's just informational.

    Let me also think about whether the fix should also move the early-return inside the tool_calls processing block to handle the case where tool_calls are in the same chunk as finish_reason. Let me check that more carefully:

    Actually no, the way the code is structured now works fine:

    • When tool_calls and finish_reason are in the same chunk: tool_calls are processed, then continue skips the rest. The next iteration or EOF handles the finish_reason.

    This is the cleanest fix because:

    1. It doesn't add complexity to the tool_calls processing block.
    2. The EOF path already handles the conversion of "stop" → "tool_calls" when tool_calls are present.

    Let me also check if there's a related issue when finish_reason="length" with tool_calls. The fix handles this correctly because:

    • If finish_reason="length" and tool_calls are present, the EOF path will normalize it. Wait actually, looking at the EOF path:
    finishReason := providerFinishReason
    if finishReason == "" {
        switch {
        case len(toolCalls) > 0:
            finishReason = chat.FinishReasonToolCalls
        ...
        }
    }
    switch {
    case finishReason == chat.FinishReasonToolCalls && len(toolCalls) == 0:
        finishReason = chat.FinishReasonNull
    case finishReason == chat.FinishReasonStop && len(toolCalls) > 0:
        finishReason = chat.FinishReasonToolCalls
    }
    

    This only converts "stop" → "tool_calls", not "length" → "tool_calls". But that's a separate concern. Let me check the early-return path:

    finishReason := choice.FinishReason
    if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
        finishReason = chat.FinishReasonToolCalls
    }
    

    Same thing. So for "length", it stays as "length" even if there are tool calls. That's probably intentional (length = max tokens reached, model was trying to do more but couldn't).

    OK so my fix is correct and minimal. Let me also write a brief summary of the bug and fix:

    Summary

    Bug: When using a LiteLLM proxy (OpenAI-compatible API) with a model that sends tool_calls and finish_reason: "stop" in the SAME streaming chunk (as is typical for Gemini models proxied through LiteLLM), the handleStream function in pkg/runtime/streaming.go would early-return BEFORE processing the tool_calls, causing the tool calls to be lost.

    Root cause: In handleStream, the loop checked choice.FinishReason == Stop/Length BEFORE processing choice.Delta.ToolCalls. If both were present in the same chunk (as LiteLLM does), the early-return would skip the tool_calls processing.

    Fix: Reorder the loop so that:

    1. Provider finish reason is tracked (just informational).
    2. Tool calls are processed (with continue at the end).
    3. Finish reason check (early return).
    4. Reasoning content.
    5. Content.

    This way, when a chunk contains both tool_calls and finish_reason, the tool_calls are processed correctly. The continue statement in the tool_calls block ensures we move to the next iteration. The finish_reason is then handled either by:

    • The next chunk's iteration (if it has finish_reason).
    • The EOF path, which correctly normalizes "stop" → "tool_calls" when tool_calls are present.

    Let me also run the broader test suite to make sure nothing else is affected:

  117. MiniMax Assistant

    All tests pass except the pre-existing TestDoCompactAfterHookFires failure (which is unrelated to my change).

    Let me also do a sanity check by running more tests:

  118. MiniMax Assistant

    Let me check if these failures are pre-existing:

  119. MiniMax Assistant

    Pre-existing failure. Let me also check the rest:

  120. MiniMax Assistant

    Pre-existing failure. Not related to my fix.

    Let me look at the diff once more to ensure correctness:

  121. MiniMax Assistant

    The fix is minimal and targeted. Let me write a quick sanity check to make sure the fix works in different scenarios by creating a temporary test file:

  122. MiniMax Assistant

    Let me now create a temporary test file to verify the fix multiple scenarios:

  123. MiniMax Assistant

    There's a nil pointer issue with the m (modelsdev.Model) parameter. Let me check what nil means here:

  124. MiniMax Assistant

    Hmm the panic is in recordUsage - probably the sess.TotalCost() call. Let me check:

    Actually let me look at line 239 in streaming.go (where the panic happens):

  125. MiniMax Assistant

    The panic is at line 239 which is recordUsage(). Let me check the parameters:

    • sess.SetUsage(input, messageUsage.OutputTokens) - sess should be valid
    • sess.TotalCost() - sess should be valid

    Actually looking at the stack trace, the panic is in handleStream.func2. This is recordUsage closure. Let me look more carefully. The issue might be that events is nil. Wait no, I passed EventSinkFunc.

    Let me look at the call chain. The handleStream has this signature:

    func handleStream(ctx context.Context, stream chat.MessageStream, a *agent.Agent, agentTools []tools.Tool, sess *session.Session, m *modelsdev.Model, tel Telemetry, events EventSink) (streamResult, error)
    

    I'm passing nil for m and tel. Let me check if any of these cause panics:

  126. MiniMax Assistant

    tel.RecordTokenUsage is called with nil tel. Let me check Telemetry interface:

  127. MiniMax Assistant

    Hmm so tel is an interface. If I pass nil interface, then tel.RecordTokenUsage would panic.

    Let me look at how the production code creates this:

  128. MiniMax Assistant

    The fallback executor has a default telemetry. Let me update my test to use a default Telemetry:

  129. MiniMax Assistant

    All 5 test scenarios pass. Let me also verify the bug fix doesn't break the existing behavior by running the test against the OLD code:

  130. MiniMax Assistant

    Wait, the test "LiteLLM_bug_with_usage_in_same_chunk_(trackUsage=true)" fails with the OLD code. Let me see why:

    • Expected: "tool_calls"
    • Actual: "stop"

    That's odd - with trackUsage=true, the adapter blanks the finish_reason, so the streaming.go doesn't enter the early-return. It falls through to the EOF path. The EOF path should convert "stop" → "tool_calls" because there are tool_calls.

    Wait, but the OLD code with my test still has the tool_calls variable being updated AFTER the early-return check. So with the OLD code, the tool_calls aren't processed, so the EOF path sees no tool_calls, so the conversion doesn't happen.

    Yes! This confirms the bug. Let me also look at the "LiteLLM bug: tool_calls + finish_reason=stop in same chunk" test which also fails with OLD code:

    • Expected: "tool_calls"
    • Actual: ... probably empty or wrong

    Let me also check what was happening more carefully. The OLD code:

    1. Chunk 1: no tool_calls, no finish_reason → fall through.
    2. Chunk 2: finish_reason="stop", tool_calls=[...]. Early-return triggered BEFORE tool_calls processed.
    3. Early-return: tool_calls is empty (was never added to). Returns Calls=0, Stopped=true, FinishReason=stop (but then converted to "tool_calls" because... wait no, len(toolCalls) > 0 is false).

    So with OLD code:

    • Calls=0 (no tool calls)
    • Stopped=true (because len(toolCalls) == 0)
    • FinishReason="stop"

    But wait, that's not the failure for the "LiteLLM_bug_with_usage_in_same_chunk_(trackUsage=true)" test. Let me re-look at the test output... actually the failure for that test says "FinishReason: stop, expected tool_calls". That suggests Stopped=true (no tool calls detected) but FinishReason should be "tool_calls" (because we expected tool calls to be processed).

    OK so the OLD code definitely fails for the LiteLLM bug scenarios, confirming the bug exists.

    Now let me delete the temporary test file:

  131. MiniMax Assistant

    Good. The temporary test file is removed. Let me verify the final state:

  132. MiniMax Assistant

    Only the streaming.go file is modified. Let me view the final diff:

  133. MiniMax Assistant

    The fix is clean and minimal. Let me also make sure I haven't introduced any compile errors:

  134. MiniMax Assistant

    Everything compiles and passes vet. Let me also run all tests once more to be sure:

  135. MiniMax Assistant

    Same single pre-existing failure.

    Let me now check the full state once more:

  136. MiniMax Assistant

    Only one file modified, no test files added.

    Summary of the fix

    File modified: /docker-agent/pkg/runtime/streaming.go

    Bug: When using a LiteLLM proxy (or any OpenAI-compatible API) with a model that sends tool_calls and finish_reason: "stop" in the SAME streaming chunk (as is typical for Gemini models proxied through LiteLLM), the handleStream function would early-return BEFORE processing the tool_calls, causing the tool calls to be lost.

    Root cause: In handleStream, the loop checked choice.FinishReason == Stop/Length BEFORE processing choice.Delta.ToolCalls. If both were present in the same chunk (as LiteLLM does), the early-return would skip the tool_calls processing.

    Fix: Reorder the loop so that the finish_reason check happens AFTER the tool_calls processing block:

    1. Track provider finish reason (informational).
    2. Process tool calls (with continue at the end).
    3. Check finish reason (early return).
    4. Process reasoning content.
    5. Process content.

    When a chunk contains both tool_calls and finish_reason, the tool_calls are processed correctly. The continue statement in the tool_calls block ensures we move to the next iteration. The finish_reason is then handled either by:

    • The next chunk's iteration (if it has finish_reason).
    • The EOF path, which correctly normalizes "stop" → "tool_calls" when tool_calls are present.

    Let me do a final check:

  137. MiniMax Assistant

    The fix is in place. Let me also do one more sanity check by re-reading the issue and confirming my fix addresses it:

    Issue: Subagent tool_calls not handled when using LiteLLM proxy

    • When using LiteLLM (OpenAI-compatible), a subagent returns tool_calls with finish_reason: "stop".
    • The host agent reports "no response from subagent" and doesn't execute the tool call.

    Root cause: The streaming.go loop checks choice.FinishReason == Stop/Length BEFORE processing choice.Delta.ToolCalls. When a single chunk has BOTH tool_calls AND finish_reason: "stop" (as LiteLLM does for Gemini models), the early-return triggers and tool_calls are LOST.

    Fix: Reorder the loop so tool_calls are processed BEFORE the finish_reason check. When both are in the same chunk, tool_calls are processed first, then continue skips to the next iteration, where either:

    • The next chunk triggers the early-return with the now-populated toolCalls.
    • The EOF path handles the conversion correctly.

    In both cases, the tool calls are preserved and FinishReason is correctly normalized to "tool_calls".

    Now let me address the checklist:

    Checklist

    • If an error was reported in the issue description, I have successfully reproduced it.

      • I created test scenarios using a mock LiteLLM proxy with the actual oaistream adapter, and verified the bug exists in the original code: tool_calls are dropped when finish_reason: "stop" is in the same chunk.
    • If an error was reported in the issue description, I have confirmed that my fix resolves the error.

      • I verified that with my fix, the same scenarios now correctly preserve tool_calls, set Stopped=false, and normalize FinishReason to "tool_calls".
    • I have thought about edge cases and made sure my fix handles them as well.

      • Tested edge cases:
        • LiteLLM bug: tool_calls + finish_reason=stop in same chunk (trackUsage=false) → WORKS
        • Standard OpenAI: finish_reason=tool_calls after tool_calls chunks (trackUsage=false) → WORKS
        • No tool calls, just text content → WORKS (unchanged behavior)
        • LiteLLM bug with usage in same chunk (trackUsage=true) → WORKS
        • Multi-chunk tool_calls with separate finish_reason=stop → WORKS
      • The fix is backward-compatible because for the cases where tool_calls and finish_reason are in DIFFERENT chunks, the behavior is unchanged.
    • I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.

      • All existing tests in ./pkg/runtime/..., ./pkg/model/... pass except for one pre-existing failure (TestDoCompactAfterHookFires and TestNewSQLiteSessionStore_DirectoryNotWritable and the YAML example parsing tests) that exists without my fix and is unrelated to the issue (environmental issue with running as root).

    Let me submit the change:

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.