Skip to content
TheChatArchiveThe Chat Archive
QwenQwen/Qwen3.6-27B· alibabaHugging 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.

    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. Qwen Assistant

    I'll start by exploring the repository structure to understand the codebase and locate the relevant files for handling subagent responses.

  3. Qwen Assistant

    Let me explore the repository structure more. This is a Go project, and I need to find where subagent responses are handled, particularly where tool_calls from subagents are processed.

  4. Qwen Assistant

    Let me look at the agent delegation file since that seems most relevant to subagent handling:

  5. Qwen Assistant

    Now let me search for the error message mentioned in the issue - "no response from subagent":

  6. Qwen Assistant

    Let me look at the GetLastAssistantMessageContent method since it's used in the subagent flow:

  7. Qwen Assistant

    Let me examine the session.go file to understand how GetLastAssistantMessageContent works:

  8. Qwen Assistant

    Let me search for the GetLastAssistantMessageContent method:

  9. Qwen Assistant

    Let me find the getLastMessageContentByRole method:

  10. Qwen Assistant

    Now I understand the issue! The getLastMessageContentByRole method only returns the Content field of the last assistant message. But when an assistant message contains tool_calls, the Content field might be empty. Let me verify this by looking at how tool calls are stored:

  11. Qwen Assistant

    Let me look at how the runtime processes agent responses and tool calls:

  12. Qwen Assistant

    Let me look at the loop.go file to understand how the runtime processes messages:

  13. Qwen Assistant

    Now let me look at line 716 more closely to see how the runtime checks for content:

  14. Qwen Assistant

    Let me look at the event.go file to understand what events are emitted when an assistant message is processed:

  15. Qwen Assistant

    Now let me look at how runCollecting uses the AgentChoiceEvent:

  16. Qwen Assistant

    Now I can see the key issue! In agent_delegation.go line 335, the runCollecting function checks for AgentChoiceEvent and only processes it if choice.Content != "":

    if choice, ok := event.(*AgentChoiceEvent); ok && choice.Content != "" {
    

    The problem is that when a subagent makes tool calls but doesn't have text content (e.g., the model returns tool_calls with an empty Content field), the choice.Content will be empty, so onContent is never called. Then at the end of runCollecting, it returns s.GetLastAssistantMessageContent() which also returns an empty string because GetLastAssistantMessageContent only looks at the Content field, ignoring ToolCalls.

    Let me look more closely at the runCollecting function:

  17. Qwen Assistant

    Now let me also look at the runForwarding function to understand the full picture:

  18. Qwen Assistant

    I can see both runForwarding and runCollecting use s.GetLastAssistantMessageContent() at the end to get the subagent's response. The problem is that GetLastAssistantMessageContent() only returns the Content field, not considering the case where the assistant message contains ToolCalls.

    Now let me search for where tool call results are emitted and how the flow works:

  19. Qwen Assistant

    Now let me look at how the runForwarding function handles this. The key insight is:

    1. In runForwarding, events are forwarded to the parent, so tool call events ARE emitted
    2. At the end, runForwarding returns tools.ResultSuccess(s.GetLastAssistantMessageContent())

    Let me understand the issue better. The problem is that when a subagent finishes and returns a tool call, the tool calls are processed by the subagent's own runtime loop (the child session). But when we return the result, we only look at the content, not the tool calls.

    Wait, let me re-read the issue description more carefully. The issue says "the host agent reports 'no response from subagent'". Let me search for this specific error message:

  20. Qwen Assistant

    Found it! Let me look at these files:

  21. Qwen Assistant

    The error message is "No response from agent" but the issue says "no response from subagent". Let me search more broadly:

  22. Qwen Assistant

    Let me check the TUI handlers to see if there's any message there:

  23. Qwen Assistant

    The error message might be slightly different. Let me focus on understanding the issue: when a subagent returns tool_calls, the GetLastAssistantMessageContent() returns an empty string because the Content field is empty when the model makes tool calls. Let me look at what happens after a tool call is made:

  24. Qwen Assistant

    Now I understand better. Let me trace through the flow more carefully. When a subagent runs, it goes through RunStream which processes the agent's loop. The agent makes tool calls, they get executed, and then the agent makes another response. The last assistant message might be empty if the agent only made tool calls and didn't provide a text response.

    Let me look at what happens after tool calls are processed - does the loop continue?

  25. Qwen Assistant

    Let me continue reading the loop to understand how it handles the continuation after tool calls:

  26. Qwen Assistant

    Now let me understand the flow better. When an assistant message has tool calls, the loop continues (returns turnContinue) after processing the tool calls. Then on the next iteration, the model gets the tool results and can make another response. The issue is that when GetLastAssistantMessageContent() is called at the end, it only looks at the Content field.

    But wait, if the subagent makes a tool call, the loop should continue, execute the tool, and then get another response from the model with the tool result. So the last assistant message should be the response after the tool execution. Unless... the model returns tool calls and finishes with finish_reason: "stop" without making another call.

    Let me check how the model providers handle responses. The issue mentions "LiteLLM proxy" - let me check the OpenAI provider:

  27. Qwen Assistant

    ...

  28. Qwen Assistant

    Now I need to understand how the streaming response is processed. Let me look at how the loop accumulates the response:

  29. Qwen Assistant

    Let me look at the streaming.go file:

  30. Qwen Assistant

    Let me understand the issue better. Looking at the code:

    1. In handleStream, when a response is received with finish_reason: "stop" (but the model also sent tool_calls), the code on line 130-138 checks:
    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
        ...
        finishReason := choice.FinishReason
        if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
            finishReason = chat.FinishReasonToolCalls
        }
        return streamResult{
            ...
            Stopped:           len(toolCalls) == 0, // stop only when there are no tool calls to execute
            ...
        }, nil
    }
    

    So when there are tool calls, Stopped is set to false, which means the loop should continue. But the issue says the subagent finishes with finish_reason: "stop" even when it has tool calls.

    Wait, let me re-read the issue. The issue is about the subagent returning a valid tool_calls response, but the host agent reports "no response from subagent".

    The problem is that when a subagent completes (via runForwarding or runCollecting), it returns s.GetLastAssistantMessageContent() which only returns the Content field of the last assistant message. If the last assistant message only has tool calls (empty content), it returns an empty string.

    But wait, if the subagent makes tool calls, the loop should continue, execute the tools, and then get another response. So the last assistant message should have content...

    Unless the issue is that when using LiteLLM proxy, the API returns finish_reason: "stop" even when tool calls are present. This would cause the stream to end early (with Stopped: true), so the tool calls are never executed!

    Let me check the oaistream/adapter.go more carefully. On line 125-135:

    // Use the tracked finish reason instead of hardcoding stop
    finishReason := a.lastFinishReason
    if finishReason == chat.FinishReasonNull || finishReason == "" {
        finishReason = chat.FinishReasonStop
    }
    

    Hmm, but that's for the usage message at the end. Let me check the messages.go file that parses non-streaming responses.

    <tool_call> <function=bash_terminal> <parameter=command> cat /docker-agent/pkg/model/provider/oaistream/messages.go </tool_call>

  31. Qwen Assistant

    <tool_call> <function=bash_terminal> <parameter=command> cat /docker-agent/pkg/model/provider/oaistream/messages.go </tool_call>

  32. Qwen Assistant

    Let me try the bash command again properly.

  33. Qwen Assistant

    Now I need to understand the actual issue better. Let me look at the test files to understand how subagent responses with tool calls are expected to work.

    The issue is:

    1. Subagent returns a valid tool_calls response with finish_reason: "stop"
    2. Host agent reports "no response from subagent"
    3. The tool call is not executed

    Looking at the code flow:

    1. handleStream processes the stream and returns a streamResult
    2. If finish_reason: "stop" is received but there are tool calls, the code at line 130-138 in streaming.go sets Stopped: len(toolCalls) == 0 which means Stopped: false when there are tool calls
    3. The loop in loop.go then processes tool calls and continues

    But wait, the issue says the subagent "finishes with finish_reason: stop". So the stream ends, the tool calls ARE captured in streamResult.Calls, but then...

    Actually, let me re-read the handleStream code more carefully. When finish_reason == "stop" is received (line 127), it immediately returns:

    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,
            Content:           fullContent.String(),
            ...
            Stopped:           len(toolCalls) == 0, // stop only when there are no tool calls to execute
            FinishReason:      finishReason,
            ...
        }, nil
    }
    

    So if finish_reason: "stop" but there ARE tool calls:

    • Stopped = false (because len(toolCalls) > 0)
    • finishReason = chat.FinishReasonToolCalls
    • The tool calls are returned in streamResult.Calls

    This should work correctly - the loop should continue and execute the tool calls.

    But wait, the issue is specifically about LiteLLM proxy. Let me think about what might be different...

    Oh! I think I see it now. The issue says "the subagent response contains a valid tool_calls entry" but the host agent doesn't execute it. This could mean:

    1. The subagent's stream returns correctly with tool calls
    2. The subagent's loop processes the tool calls and gets results
    3. But when the subagent session ends, GetLastAssistantMessageContent() is called
    4. This returns an empty string if the last assistant message had tool calls but no text content

    Wait, but if tool calls are processed, the loop should continue and the model should make another response with the tool results. So the last assistant message should be that response, not the one with tool calls...

    Unless the issue is that the subagent doesn't continue after making tool calls because of how LiteLLM responds. Some proxies might not properly handle the continuation after tool calls.

    Actually, let me re-read the issue more carefully:

    The subagent returns a tool call (e.g., company_search with JSON arguments) and finishes with finish_reason: "stop". The host agent logs "no response from subagent" and does not invoke the tool.

    So the host agent doesn't invoke the tool call from the subagent. This is the key insight!

    When using transfer_task or similar delegation, the subagent runs in its own session. The tool calls made by the subagent should be executed within that subagent's session. But if the host agent is trying to execute the tool calls from the subagent's response, that's a different flow.

    Wait, I think I misunderstood. Let me look at runForwarding again:

    func (r *LocalRuntime) runForwarding(...) (*tools.ToolCallResult, error) {
        ...
        s := newSubSession(parent, req.SubSessionConfig, child)
        
        ...
        
        childEvents := r.RunStream(ctx, s)
        for event := range childEvents {
            evts.Emit(event)  // Forward events to parent
            ...
        }
        
        ...
        return tools.ResultSuccess(s.GetLastAssistantMessageContent()), nil
    }
    

    The subagent runs its own RunStream which should handle tool calls within its own loop. The events are forwarded to the parent. At the end, it returns s.GetLastAssistantMessageContent().

    The issue is: if the subagent's last assistant message only has tool calls (no content), GetLastAssistantMessageContent() returns empty string.

    But wait, if the subagent makes tool calls, the loop should:

    1. Record the assistant message with tool calls
    2. Process the tool calls (execute them)
    3. Get another response from the model with the tool results
    4. That response should have content

    Unless... the issue is that when using LiteLLM, the stream returns finish_reason: "stop" even with tool calls, and the loop doesn't continue because of some issue.

    Let me check the loop.go code more carefully:

    Looking at loop.go around line 596:

    stopRun, stopMsg := r.processToolCalls(ctx, sess, res.Calls, agentTools, events)
    

    And then around line 650-655:

    if res.Stopped {
        slog.DebugContext(ctx, "Conversation stopped", "agent", a.Name())
        r.executeStopHooks(ctx, sess, a, res.Content, events)
        ...
        endReason = turnEndReasonNormal
        return turnExit
    }
    

    So if res.Stopped is true, the loop exits. And res.Stopped is set based on the stream result.

    From streaming.go:

    Stopped:           len(toolCalls) == 0, // stop only when there are no tool calls to execute
    

    So if there are tool calls, Stopped should be false and the loop should continue!

    But wait... let me check if there's another path. Looking at streaming.go line 213-214:

    // If the stream completed without producing any content or tool calls, likely because of a token limit, stop to avoid breaking the request loop
    stoppedDueToNoOutput := fullContent.Len() == 0 && len(toolCalls) == 0
    

    And then at the end of the function (around line 242):

    return streamResult{
        ...
        Stopped:           stoppedDueToNoOutput,
        ...
    }, nil
    

    So there are TWO places where Stopped is set:

    1. In the early return when finish_reason == "stop" (line 130-138): Stopped: len(toolCalls) == 0
    2. At the end of the function (EOF path): Stopped: stoppedDueToNoOutput which is fullContent.Len() == 0 && len(toolCalls) == 0

    The EOF path is problematic! If the stream ends with EOF (no explicit finish reason) and there ARE tool calls, stoppedDueToNoOutput would be false because len(toolCalls) > 0. So that's correct.

    Hmm, let me look at what happens when LiteLLM proxy returns finish_reason: "stop" with tool calls. The early return path should handle this correctly by setting Stopped: false when there are tool calls.

    Let me look at the oaistream adapter again. Actually, I think the issue might be in how the finish reason is processed. Let me check if there's a case where finish_reason: "tool_calls" is received...

    Actually, I think I found the issue! Let me look at the handleStream function again.

    When finish_reason == "stop" is received with tool calls, the code does:

    finishReason := choice.FinishReason  // "stop"
    if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
        finishReason = chat.FinishReasonToolCalls  // Changed to "tool_calls"
    }
    return streamResult{
        ...
        Stopped:           len(toolCalls) == 0,  // false if there are tool calls
        FinishReason:      finishReason,
        ...
    }, nil
    

    This looks correct. So if LiteLLM returns finish_reason: "stop" with tool calls, the code should handle it correctly.

    Wait, let me check if there's an issue with the condition. The condition is:

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

    What if the finish reason is something else? Let me check what values chat.FinishReason can have...

    Looking at chat.go:

    const (
        FinishReasonStop FinishReason = "stop"
        FinishReasonLength FinishReason = "length"  
        FinishReasonToolCalls FinishReason = "tool_calls"
        FinishReasonNull FinishReason = "null"
    )
    

    So if LiteLLM returns finish_reason: "tool_calls", the condition choice.FinishReason == chat.FinishReasonStop would be false, so it wouldn't take the early return path. Instead, it would continue processing the stream and eventually hit EOF.

    But that should still work... unless the tool calls delta comes AFTER the finish reason is received?

    Let me trace through more carefully. The stream processing loop in handleStream:

    1. Receives chunks with deltas
    2. Accumulates tool calls in toolCalls slice
    3. Accumulates content in fullContent
    4. When finish_reason is received, it checks if it's "stop" or "length"
    5. If so, it returns early

    The problem might be that some providers send the finish reason BEFORE the tool call deltas are fully received!

    Actually wait, I think the issue is different. Let me look at the streaming.go code again more carefully.

    Actually, I think I need to check if the issue is in the Stopped logic. Let me re-read the early return path:

    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,
            Content:           fullContent.String(),
            ReasoningContent:  fullReasoningContent.String(),
            ThinkingSignature: thinkingSignature,
            ThoughtSignature:  thoughtSignature,
            Stopped:           len(toolCalls) == 0, // stop only when there are no tool calls to execute
            FinishReason:      finishReason,
            Usage:             messageUsage,
        }, nil
    }
    

    This looks correct. If finish_reason: "stop" but there are tool calls, Stopped will be false.

    Hmm, let me think about this differently. The issue says "the host agent reports 'no response from subagent'". I found two places where "No response from agent" is used:

    1. /docker-agent/pkg/mcp/server.go
    2. /docker-agent/pkg/tools/a2a/a2a.go

    But these say "No response from agent" not "no response from subagent". Let me search for any other messages...

    Actually, I wonder if the "no response from subagent" message is a log message or a user-facing message that's not in the codebase. Let me focus on understanding the actual bug.

    The core issue seems to be:

    1. Subagent makes tool calls
    2. Tool calls are returned in streamResult.Calls
    3. streamResult.Stopped is set to false (because there are tool calls)
    4. The loop processes tool calls and continues
    5. But somehow the tool calls are not being executed or the response is empty

    Wait! I think I finally see it. Let me look at runForwarding again:

    childEvents := r.RunStream(ctx, s)
    for event := range childEvents {
        evts.Emit(event)
        if errEvent, ok := event.(*ErrorEvent); ok {
            ...
        }
    }
    
    parent.ToolsApproved = s.ToolsApproved
    parent.AddSubSession(s)
    evts.Emit(SubSessionCompleted(parent.ID, s, callerAgent.Name()))
    
    span.SetStatus(codes.Ok, "sub-session completed")
    return tools.ResultSuccess(s.GetLastAssistantMessageContent()), nil
    

    The function returns s.GetLastAssistantMessageContent(). If the subagent's last message only has tool calls (no text content), this returns an empty string!

    But wait, the subagent's loop should continue after processing tool calls. The tool calls should be executed, and then the model should get another chance to respond with the tool results.

    Unless... the issue is that the subagent session is NON-INTERACTIVE (like in runCollecting)?

    Looking at runCollecting:

    func (r *LocalRuntime) runCollecting(...) *agenttool.RunResult {
        ...
        s := newSubSession(parent, cfg, child)
        
        var errMsg string
        events := r.RunStream(ctx, s)
        for event := range events {
            if ctx.Err() != nil {
                break
            }
            if choice, ok := event.(*AgentChoiceEvent); ok && choice.Content != "" {
                if onContent != nil {
                    onContent(choice.Content)
                }
            }
            if errEvt, ok := event.(*ErrorEvent); ok {
                errMsg = errEvt.Error
                break
            }
        }
        ...
        
        result := s.GetLastAssistantMessageContent()
        parent.AddSubSession(s)
    
        return &agenttool.RunResult{Result: result}
    }
    

    Here, result := s.GetLastAssistantMessageContent() is called at the end. If the subagent made tool calls and the loop continues, but then the model doesn't produce any text content in its final response, result would be empty.

    Actually, let me think about this more. When a subagent makes tool calls:

    1. The assistant message with tool calls is recorded in the session
    2. The tool calls are executed and tool result messages are added
    3. The loop continues and the model is called again
    4. The model responds with text content (hopefully)

    So the last assistant message should be the one after tool results, which should have content.

    Unless... the subagent's session is marked as NonInteractive and has MaxIterations that causes it to stop before it can make another call?

    Hmm, let me look at what happens when NonInteractive is set:

    Looking at loop.go around line 236-248:

    if sess.NonInteractive && iter >= sess.MaxIterations && sess.MaxIterations > 0 {
        stopMsg := "Agent stopped after reaching max iterations in non-interactive mode"
        slog.DebugContext(ctx, stopMsg, "agent", a.Name(), "iterations", iter, "max_iterations", sess.MaxIterations)
        events.Emit(MaxIterationsEvent(sess.ID, a.Name()))
        ...
        endReason = turnEndReasonMaxIterations
        return turnExit
    }
    

    So in non-interactive mode, if max iterations is reached, the loop stops. But this should still leave the session with the last assistant message...

    OK let me take a step back and think about the actual bug scenario:

    Scenario: Subagent is asked to use tools, it returns a tool call and finish_reason: "stop". The host agent says "no response from subagent".

    What should happen:

    1. Subagent stream returns with finish_reason: "stop" and tool calls
    2. handleStream returns streamResult with Stopped: false (because there are tool calls)
    3. The loop processes the tool calls
    4. The loop continues and the model is called again
    5. The model responds with the result of the tool calls
    6. This response is the last assistant message

    What's happening: The host agent reports "no response from subagent". This suggests s.GetLastAssistantMessageContent() returns empty string.

    Wait, I think I need to look at what GetLastAssistantMessageContent actually does:

    func (s *Session) GetLastAssistantMessageContent() string {
        return s.getLastMessageContentByRole(chat.MessageRoleAssistant)
    }
    
    func (s *Session) getLastMessageContentByRole(role chat.MessageRole) string {
        messages := s.GetAllMessages()
        for _, message := range slices.Backward(messages) {
            if message.Message.Role == role {
                return strings.TrimSpace(message.Message.Content)
            }
        }
        return ""
    }
    

    This returns the Content field of the last assistant message. If the last assistant message has tool calls but no content, it returns empty string.

    But if the subagent's loop continues after processing tool calls, there should be another assistant message with content...

    Unless... the issue is that when NonInteractive: true, the subagent stops after processing tool calls without making another model call?

    Actually wait, let me check the loop logic more carefully. After processing tool calls:

    stopRun, stopMsg := r.processToolCalls(ctx, sess, res.Calls, agentTools, events)
    
    ...
    
    if res.Stopped {
        ...
        return turnExit
    }
    
    ...
    
    r.compactIfNeeded(ctx, sess, a, contextLimit, messageCountBeforeTools, events)
    endReason = turnEndReasonContinue
    return turnContinue
    

    So after processing tool calls, if res.Stopped is false, the loop returns turnContinue. Let me check what turnContinue does:

    Looking at the loop structure in loop.go:

    func (r *LocalRuntime) processTurn(...) turnExitKind {
        ...
    }
    

    And the main loop:

    for {
        exitKind := r.processTurn(ctx, sess, a, ls, contextLimit, sessionSpan, events)
        if exitKind == turnExit {
            break
        }
        // turnContinue: continue the loop
    }
    

    So turnContinue should continue the loop and call the model again. This should work...

    Unless there's something preventing the loop from continuing. Let me check if there are any early exit conditions...

    Looking at the loop, after tool calls are processed:

    // post_tool_use hook signalled run termination via a deny verdict
    if stopRun {
        ...
        return turnExit
    }
    
    // Drain steer messages that arrived during tool calls.
    if drained, _ := r.drainAndEmitSteered(ctx, sess, events); drained {
        ...
        return turnContinue
    }
    
    if res.Stopped {
        ...
        return turnExit
    }
    
    r.compactIfNeeded(...)
    endReason = turnEndReasonContinue
    return turnContinue
    

    So unless stopRun is true or res.Stopped is true, the loop should continue with turnContinue.

    Hmm, I wonder if the issue is that the res.Stopped check happens BEFORE the tool call processing in some code paths... No, looking at the code, processToolCalls is called first, then the check for res.Stopped.

    Wait, I just realized something! Let me check if res.Stopped is checked correctly. Looking at the code:

    stopRun, stopMsg := r.processToolCalls(ctx, sess, res.Calls, agentTools, events)
    
    ...
    
    // Check for degenerate tool call loops
    if ls.loopDetector.Record(res.Calls) {
        ...
        return turnExit
    }
    
    // post_tool_use hook signalled run termination
    if stopRun {
        ...
        return turnExit
    }
    
    ...
    
    if res.Stopped {
        ...
        return turnExit
    }
    

    So res.Stopped IS checked after processToolCalls. And res.Stopped should be false when there are tool calls. So the loop should continue!

    Let me now think about what else could cause the issue. Maybe the problem is that when LiteLLM returns finish_reason: "stop", the tool calls are NOT included in the response? Let me check how the adapter handles this...

    Actually, I think I should look at what "finish_reason: stop" means for OpenAI-compatible APIs. According to OpenAI's API docs:

    • stop: The model hit a natural stop point or a provided stop sequence.
    • tool_calls: The model called tools.
    • length: The model exceeded the max_tokens limit.

    If LiteLLM returns finish_reason: "stop" with tool calls, this is technically incorrect according to OpenAI's spec. But the cagent code should handle this gracefully by checking if there are tool calls and setting Stopped: false.

    Wait! I think I might have found the issue. Let me look at the condition again:

    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,
            Content:           fullContent.String(),
            ...
            Stopped:           len(toolCalls) == 0, // stop only when there are no tool calls to execute
            ...
        }, nil
    }
    

    This code looks correct. It checks len(toolCalls) == 0 to determine if it should stop.

    But wait, what if the issue is that the toolCalls variable is empty when this condition is hit? Maybe the tool call delta hasn't been processed yet when the finish reason is received?

    Let me check the order of operations in the stream processing loop:

    for {
        response, err := stream.Recv()
        ...
        choice := response.Choices[0]
    
        if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
            ...
            return streamResult{...}, nil
        }
    
        ...
    
        // Handle tool calls
        if len(choice.Delta.ToolCalls) > 0 {
            ...
            continue
        }
    
        ...
    
        if choice.Delta.Content != "" {
            ...
        }
    }
    

    So the loop first checks for finish reason, then processes tool calls. If the finish reason comes BEFORE the tool call deltas, toolCalls would still be empty at the time of the early return!

    But wait, the continue statement after tool call processing means that if a choice has tool call deltas, it won't check the finish reason for that chunk. So if a chunk has both finish_reason: "stop" and tool call deltas, the finish reason check comes first...

    Actually no, let me re-read. The code structure is:

    1. Get choice
    2. Check if FinishReason is "stop" or "length" → return early
    3. Track provider finish reason
    4. Handle tool call deltas → continue
    5. Handle reasoning content
    6. Handle content

    So if a chunk has BOTH finish_reason: "stop" AND tool call deltas, the finish reason check will trigger first and return early with potentially incomplete tool calls!

    But typically, the finish reason is only set on the last chunk, and tool call deltas should have been received before that. So this shouldn't be an issue in normal cases.

    Unless LiteLLM sends the finish reason on a chunk that also has the last part of the tool call arguments? Let me think...

    Actually, I think I need to look at this from a different angle. Let me check if there are any tests that cover this scenario.

    Looking at the test files, I see agent_delegation_test.go. Let me check if there are tests for subagents with tool calls.

    <tool_call> <function=bash_terminal> <parameter=command> cat /docker-agent/pkg/runtime/agent_delegation_test.go </tool_call>

  34. Qwen Assistant

    Let me continue investigating the issue. I need to look at the agent_delegation_test.go file to understand how subagent delegation is tested.

  35. Qwen Assistant

    After analyzing the code, I believe I found the issue. Let me examine the streaming.go file more closely to confirm my hypothesis:

  36. Qwen Assistant

    Looking at the code, I think I've identified the issue! In streaming.go, when processing the stream, the finish reason check comes before the tool call delta processing. If a chunk contains both finish_reason: "stop" and tool call deltas, the code returns early without processing the tool call deltas in that chunk.

    Let me verify this by looking at the streaming.go code:

  37. Qwen Assistant

    I've found the bug! Looking at the streaming.go code, the finish reason check happens before processing tool call deltas. If a chunk contains both finish_reason: "stop" AND tool call deltas, the code returns early without processing the tool calls in that chunk.

    The flow is:

    1. Chunk arrives with finish_reason: "stop" and delta.tool_calls
    2. Line 132: choice.FinishReason == "stop" is TRUE
    3. Line 137: len(toolCalls) == 0 is TRUE (because tool calls haven't been processed yet!)
    4. Early return with Stopped: true and empty Calls - tool calls are lost!

    Let me fix this by processing the deltas before checking for the finish reason:

  38. Qwen Assistant

    The user seems to have encountered an issue with the tool call format. Let me try again with the correct format. I need to open the streaming.go file to make the fix. The previous attempt failed because I used open as a tool call but it wasn't recognized. Let me use the bash_terminal command instead.

  39. Qwen Assistant

    Now I can clearly see the bug. When a chunk contains both finish_reason: "stop" AND tool call deltas, the code checks for the finish reason FIRST (line 132), BEFORE processing the tool call deltas (line 158-159). This means if a provider like LiteLLM sends the finish reason in the same chunk as the tool call delta, the tool call is never processed because the function returns early at line 139.

    The fix is to process tool call deltas BEFORE checking for the finish reason. Let me implement this:

  40. Qwen Assistant

    I need to provide the replacement text for the edit. Let me restructure the streaming.go code to process tool calls before checking the finish reason:

  41. Qwen Assistant

    The user wants me to edit the streaming.go file but I need to open it first. Let me use the open command with the correct syntax - it seems like I need to provide arguments differently.

  42. Qwen Assistant

    I apologize for the hasty edit. Let me carefully examine the current state of the file and make a proper fix.

  43. Qwen Assistant

    The script I ran made a mess of the file. Let me revert it and start fresh with a proper fix.

  44. Qwen Assistant

    The git diff command worked, so I can proceed with creating a proper sed script to make the changes correctly. I need to be very careful with the sed script to ensure it makes the exact changes needed.

    The key changes are:

    1. Move the finish reason check AFTER the tool call processing
    2. Update the comment about "stop/length are already handled by the early return above" since it's no longer accurate
    3. Add a comment explaining why tool calls are processed first

    Let me create a more careful sed script that:

    1. Removes the old finish reason check block (lines 132-149)
    2. Updates the comment at line 151-153
    3. Adds a new comment before the tool call processing
    4. Adds the finish reason check after the content processing (after line 240)

    Actually, let me think about this more carefully. The issue is that when LiteLLM sends finish_reason in the same chunk as tool call deltas, the current code returns early without processing the tool calls.

    The fix should be:

    1. Process tool call deltas FIRST
    2. THEN check for finish_reason and return early if needed

    This way, even if the finish reason is in the same chunk as the tool call deltas, the tool calls will be processed before the early return.

    Let me look at the exact structure again and create a precise sed script.

  45. Qwen Assistant

    I need to fix the streaming.go file. The issue is that the finish reason check happens BEFORE tool call delta processing. I need to:

    1. Remove the early finish reason check (lines 132-149)
    2. Move it to after the content processing (after line 240)

    Let me use sed to make this change properly. I'll:

    1. Delete lines 132-149 (the early finish reason check)
    2. Update the comment at lines 151-153 since it's no longer accurate
    3. Add the finish reason check after the content processing

    Let me look at lines 230-250 to see where to insert the finish reason check.

  46. Qwen Assistant

    Looking at the code structure, I need to:

    1. Remove the early finish reason check (lines 132-149)
    2. Process tool calls and content first
    3. Then check finish reason and return early

    Let me create the fix properly:

  47. Qwen Assistant

    Let me take a simpler, more direct approach. I'll use sed to make the precise changes needed to the streaming.go file. The fix is to move the finish reason check to AFTER processing tool call deltas.

  48. Qwen Assistant

    The user is providing feedback that my previous attempts to fix the code were incorrect. Let me carefully analyze what I need to do:

    1. The issue is that when using LiteLLM proxy, the subagent can return a valid tool_calls response with finish_reason: "stop", but the host agent reports "no response from subagent" and does not execute the tool call.

    2. I identified the bug in /docker-agent/pkg/runtime/streaming.go at lines 132-149, where the finish reason check happens BEFORE processing tool call deltas. If a chunk contains both finish_reason: "stop" AND tool call deltas, the code returns early without processing the tool calls.

    3. My previous attempts to fix this were messy and incorrect. I need to create a clean, proper fix.

    Let me now create a proper Python script that will:

    1. Read the file
    2. Remove the early finish reason check block (lines 132-149, which are indices 131-148)
    3. Update the comment at lines 151-153
    4. Add a comment before the tool call processing section
    5. Add the finish reason check AFTER all delta processing (after line 240)

    The key insight is:

    • Lines 132-149 contain the early return when finish_reason is "stop" or "length"
    • This check happens BEFORE the tool call delta processing (lines 158-212)
    • We need to move this check to AFTER all delta processing

    Let me create a clean fix.

  49. Qwen Assistant

    The user wants me to continue fixing the streaming.go file. I've already made a change using my Python script, but I need to verify it worked correctly. Let me check the diff to see what changes were made, and then verify the fix is correct by examining the modified file.

    Let me:

    1. Check the git diff to see what changed
    2. Verify the file is syntactically correct by trying to build it
    3. Look at the key sections to ensure the fix is correct
  50. Qwen Assistant

    I can see the diff shows my changes, but there's a problem! The finish reason check block was inserted outside the for loop (after line 238, which is the closing brace of the for loop). This is wrong - the finish reason check needs to be inside the for loop, after processing all deltas but before continuing to the next iteration.

    Let me fix this by reverting and making the correct change. The finish reason check should be:

    • AFTER processing tool calls, reasoning, and content deltas
    • BEFORE the end of the for loop iteration (so it can return early)
    • INSIDE the for loop (so it can check each chunk)
  51. Qwen Assistant

    Good, I've reverted the file. Now let me create a correct fix. The key insight is:

    The finish reason check must remain INSIDE the for loop, just moved to AFTER the delta processing. Currently the structure is:

    for {
        response, err := stream.Recv()
        ...
        choice := response.Choices[0]
        
        // 1. Check finish reason and return early (WRONG - happens before delta processing)
        if choice.FinishReason == "stop" || choice.FinishReason == "length" {
            return ...
        }
        
        // 2. Process tool call deltas
        if len(choice.Delta.ToolCalls) > 0 {
            ...
        }
        
        // 3. Process reasoning deltas
        if choice.Delta.ReasoningContent != "" {
            ...
        }
        
        // 4. Process content deltas
        if choice.Delta.Content != "" {
            ...
        }
    }
    

    The fix should be:

    for {
        response, err := stream.Recv()
        ...
        choice := response.Choices[0]
        
        // 1. Process tool call deltas
        if len(choice.Delta.ToolCalls) > 0 {
            ...
        }
        
        // 2. Process reasoning deltas
        if choice.Delta.ReasoningContent != "" {
            ...
        }
        
        // 3. Process content deltas
        if choice.Delta.Content != "" {
            ...
        }
        
        // 4. NOW check finish reason and return early (CORRECT - after all delta processing)
        if choice.FinishReason == "stop" || choice.FinishReason == "length" {
            return ...
        }
    }
    

    Let me look at the exact structure to understand where to insert the finish reason check.

  52. Qwen Assistant

    I can see the structure now. The for loop ends at line 238 with }. After that, there's the EOF handling code. The finish reason check needs to be inside the for loop, just before the closing brace at line 238.

    Looking at the structure:

    • Line 237: fullContent.WriteString(choice.Delta.Content)
    • Line 238: } - closes the if choice.Delta.Content != "" block
    • Line 239: } - closes the for loop

    Wait, that doesn't look right. Let me check more carefully:

  53. Qwen Assistant

    I can see the structure now. The for loop ends at line 239 (with 1 tab), and line 238 is the closing brace of the content processing if block (with 2 tabs). I need to insert the finish reason check between lines 238 and 239.

    Let me create a clean, correct fix:

  54. Qwen Assistant

    I see the issue - my assertion about the indentation was wrong. Let me re-examine the file structure more carefully to find the correct insertion point.

  55. Qwen Assistant

    Now I understand the structure:

    • Line 237: fullContent.WriteString(...) with 3 tabs
    • Line 238: } with 2 tabs - closes the if choice.Delta.Content != "" block
    • Line 239: } with 1 tab - closes the for loop

    I need to insert the finish reason check AFTER line 238 but BEFORE line 239 (inside the for loop). Let me fix my script:

  56. Qwen Assistant

    Let me verify the fix was applied correctly by checking the diff and ensuring the code is syntactically correct.

  57. Qwen Assistant

    I see the problem! The finish reason check block is still being inserted outside the for loop. Looking at the diff:

    		fullContent.WriteString(choice.Delta.Content)
    	}
    	}    <-- This is line 238 - closes the content if block
    }       <-- This is line 239 - closes the for loop (1 tab)
    
    +		// Check for finish reason AFTER processing all deltas...
    +		if choice.FinishReason == ...
    

    The problem is that line 239 (index 238) is the closing brace of the for loop. My script is inserting the code AFTER this closing brace, which puts it outside the loop!

    I need to insert the code BEFORE line 239 (the for loop's closing brace), not after. Let me look at the exact structure again:

  58. Qwen Assistant

    You're absolutely right - I made the same mistake again! The finish reason check was inserted AFTER the for loop's closing brace, meaning it's outside the loop and will never execute.

    Let me analyze the problem more carefully and create a correct fix:

  59. Qwen Assistant

    I can see the structure clearly now:

    • Line 205: } closes the if len(choice.Delta.ToolCalls) > 0 block
    • Line 206: continue (this is important - after processing tool calls, it continues to the next iteration!)
    • Line 207: } closes the tool calls if block... wait, that doesn't make sense

    Let me look at this more carefully with line numbers:

  60. Qwen Assistant

    I see the issue now! Looking at line 211, there's a continue statement after processing tool calls. This means when tool calls are present, the loop continues to the next iteration without checking the finish reason.

    The correct fix is to insert the finish reason check inside the for loop, after all delta processing (tool calls, reasoning, content). This way:

    1. If there are tool calls, they get processed first
    2. Then we check the finish reason and return early if needed
    3. The continue statement can stay as is (it will be reached before the finish reason check)

    Let me create a proper fix:

  61. Qwen Assistant

    The user wants me to continue working on fixing the streaming.go file. Let me check the current state of my changes by looking at the git diff to verify the fix was applied correctly.

  62. Qwen Assistant

    I see the problem! Looking at the diff, the finish reason check is still being inserted outside the for loop. The closing brace } of the for loop comes BEFORE my inserted code. Let me examine the exact line numbers again and fix this properly.

  63. Qwen Assistant

    You're absolutely right - I keep making the same mistake! The continue statement at line 211 means that even if I insert the finish reason check at the end of the loop body, it will NEVER be reached when there are tool calls.

    The correct fix is to:

    1. Remove the early finish reason check (lines 132-149)
    2. Remove the continue statement (line 211) so all code paths flow through
    3. Add the finish reason check at the end of the loop body (before the closing brace at line 239)
  64. Qwen Assistant

    The user is waiting for me to verify the fix. Let me check the git diff to see if the changes are correct this time. The key changes should be:

    1. Remove the early finish reason check (lines 132-149)
    2. Remove the 'continue' statement (line 211)
    3. Add the finish reason check at the end of the loop body, BEFORE the closing brace at line 239

    Let me verify this with git diff.

  65. Qwen Assistant

    Looking at the diff, I can see the finish reason check is still being placed outside the for loop. The } on line 221 closes the for loop, and then my inserted code comes after it. This is wrong!

    Let me examine the exact structure more carefully to understand what's happening:

  66. Qwen Assistant

    You're absolutely right - I keep making the same mistake. The finish reason check is being placed AFTER the for loop's closing brace, which means it's outside the loop and will never execute.

    Let me look at the exact structure of the for loop to understand where to insert the code:

  67. Qwen Assistant

    Now I understand the structure:

    • Line 238: } with 2 tabs - closes the if choice.Delta.Content != "" block
    • Line 239: } with 1 tab - closes the for loop
    • Line 240: blank line
    • Line 241: recordUsage() - outside the for loop

    I need to insert my finish reason check AFTER line 238 but BEFORE line 239 (so it's INSIDE the for loop). Let me create a correct fix:

  68. Qwen Assistant

    Now I can see the structure clearly:

    • Line 238: } (2 tabs) - closes the content if block
    • Line 239: empty line

    Let me look at more lines to find where the for loop closes:

  69. Qwen Assistant

    The user is still showing me the same content - my Python script already modified the file. Let me check if the modification was done correctly by examining the diff:

  70. Qwen Assistant

    Looking at the diff more carefully, I can see the issue! The finish reason check is being placed AFTER the for loop's closing brace (} on line 221 of the new file), which means it's OUTSIDE the for loop and will never execute.

    The problem is that my script includes lines[212:238], which includes index 237 (file line 238) - the for loop closing brace. I need to exclude that closing brace and insert my code BEFORE it.

    Let me revert and fix this properly:

  71. Qwen Assistant

    Now let me examine the exact structure of the for loop:

  72. Qwen Assistant

    Now I can see the structure more clearly:

    • Line 237: } with 2 tabs - closes if choice.Delta.Content != ""
    • Line 238: } with 1 tab - closes the for loop

    So the for loop's closing brace is at line 238 (index 237). I need to insert my code BEFORE line 238, not after.

    Let me create a correct fix:

  73. Qwen Assistant

    Now let me verify the fix was applied correctly by checking the git diff.

  74. Qwen Assistant

    Now I can see the fix is correctly applied. Looking at the diff:

    1. The early finish reason check (lines 132-149) has been removed ✓
    2. The comment has been updated ✓
    3. The continue statement has been removed ✓
    4. The finish reason check has been added INSIDE the for loop (before the closing }) ✓

    The finish reason check is now placed AFTER all delta processing but BEFORE the for loop's closing brace }. This is correct!

    Let me verify the file compiles correctly:

  75. Qwen Assistant

    I need to set up the Go environment properly before building. Let me fix that and verify the code compiles.

  76. Qwen Assistant

    There's a syntax error - the file is missing a closing brace. This is because I removed the continue statement and its closing brace, but I may have accidentally removed an extra brace. Let me check the structure of the modified file:

  77. Qwen Assistant

    I see the issue - when I removed the continue statement, I also accidentally removed the closing brace } of the if len(choice.Delta.ToolCalls) > 0 block. Let me revert and fix this properly.

  78. Qwen Assistant

    The user is pointing out that my last response didn't include a proper tool call. Looking at my previous message, I did use bash_terminal correctly, but the error says "No tool call was invoked". This might be a formatting issue.

    Let me continue fixing the streaming.go file. I need to:

    1. Remove the early finish reason check (lines 132-149)
    2. Remove ONLY the continue statement (line 211), NOT its closing brace
    3. Add the finish reason check at the end of the loop body

    Let me look at the exact structure around line 208-212 to make sure I understand what to remove.

  79. Qwen Assistant

    I need to remove ONLY the continue statement on line 211, not its closing brace on line 212. Let me create a corrected fix:

  80. Qwen Assistant

    The user is waiting for me to continue. Let me verify the fix was applied correctly and then test that the code compiles.

  81. Qwen Assistant

    The diff looks correct now. The key changes are:

    1. ✅ Early finish reason check removed (lines 132-149)
    2. ✅ continue statement removed (but closing brace } kept)
    3. ✅ Finish reason check added INSIDE the for loop (before the closing })

    Now let me verify the code compiles:

  82. Qwen Assistant

    The code compiles successfully. Let me run the existing tests to verify the fix doesn't break anything:

  83. Qwen Assistant

    Now let me run more comprehensive tests to make sure the fix is correct.

  84. Qwen Assistant

    The test suite failed. Let me investigate which specific test(s) failed and understand if my fix broke something.

  85. Qwen Assistant

    The test TestDoCompactAfterHookFires failed. Let me run this specific test to see the error details.

  86. Qwen Assistant

    This test failure is unrelated to my changes. The test is about compaction hooks, not about streaming or tool calls. Let me verify this by reverting my changes and running the same test to see if it was already failing.

  87. Qwen Assistant

    The test was already failing before my changes! This is a pre-existing test failure, not caused by my fix. Let me restore my changes and verify the fix is correct.

  88. Qwen Assistant

    Let me run tests excluding the pre-existing failing test to verify my fix doesn't break anything else.

  89. Qwen Assistant

    The test command with -run '!TestDoCompactAfterHookFires' didn't work as expected because the regex syntax is different. Let me run all tests except the one that was already failing, by running the full test suite and checking if there are any NEW failures beyond the pre-existing one.

  90. Qwen Assistant

    I see the tests are passing. Let me check for any FAIL lines to confirm only the pre-existing test is failing:

  91. Qwen Assistant

    The only failing test is TestDoCompactAfterHookFires, which was already failing before my changes (confirmed earlier). This is a pre-existing issue unrelated to my fix.

    Let me verify the final diff one more time:

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