claude-agent-sdk-python icon indicating copy to clipboard operation
claude-agent-sdk-python copied to clipboard

Agent Teams: Subagent SendMessage not delivered to team lead in SDK mode

Open barrcodes opened this issue 9 months ago • 9 comments

Summary

When using experimental Agent Teams with ClaudeSDKClient, teammate messages sent via SendMessage are never received by the lead because the SDK session terminates before the next turn.

Environment

  • Claude Code version: 2.1.42
  • Claude Agent SDK version: 0.1.36
  • CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1

Root Cause

In interactive mode, messages are delivered between turns as <teammate-message> blocks. In SDK mode, the session ends when receive_response() yields a ResultMessage—there is no "next turn" to receive messages.

Interactive mode timeline:

Lead turn 1: spawn teammate, send message → turn ends
Lead turn 2: <teammate-message> delivered → lead processes it

SDK mode timeline:

Lead turn 1: spawn teammate, send message → ResultMessage → session terminates
(no turn 2 exists to receive the message)

Reproduction Steps

Pseudocode:

async with ClaudeSDKClient(options=options) as client:
    await client.query("""
        1. Create a team
        2. Spawn a teammate to call an MCP tool
        3. Wait for teammate to send you the result via SendMessage
        4. Submit results
    """)
    async for message in client.receive_response():
        if isinstance(message, ResultMessage):
            break  # Session ends here, teammate message never arrives

Expected Behavior

Teammate messages should be delivered before the session terminates, or there should be a mechanism to poll/wait for pending messages.

Why This Matters

  • Agent Teams are designed for multi-agent coordination
  • SDK mode is required for programmatic orchestration (CI/CD, automation, pipelines)
  • Without this, Agent Teams cannot be used in any non-interactive context

Stopgap Solution

Simple cases: sleep to keep session alive

For basic coordination, the lead can sleep 5 after spawning a teammate. This keeps the session alive long enough for the teammate to complete work and write to a file:

# Lead instructions
"1. Spawn teammate to call MCP tool and write result to /tmp/result.txt
 2. Run 'sleep 5' to wait for teammate
 3. Read /tmp/result.txt"

Complex cases: secondary store with polling

For multi-step coordination or variable completion times, it is possible to use a secondary store (file, database, or in-memory) with a polling loop:

  1. Teammate writes output to store instead of SendMessage
  2. Lead polls store in a loop until result appears
  3. Lead processes result before session ends

Both workarounds defeat the purpose of the SendMessage abstraction.

Potential Fix

You could block until messages are delivered from one or more agents using a receive_responses() tool that has a max timeout. You could modify the system prompt to sleep loop until agents complete, or a critical error is discovered.

barrcodes avatar Feb 15 '26 13:02 barrcodes

Hi! I've been looking into this issue and wanted to share what I found. Here's the simple version:

The Problem

When using Agent Teams with ClaudeSDKClient, teammate messages never arrive because the session ends too early.

What I Discovered

  1. The SDK has a continue_conversation option (default: False)

    • When enabled, it keeps the session open for multiple turns
    • This might be what agent teams need to work properly
  2. The session closes immediately after ResultMessage

    • ResultMessage = "session complete" signal from the CLI
    • The SDK ends the session as soon as it receives this signal
    • Teammate messages arrive later, but the session is already closed
  3. The official examples use query() (not ClaudeSDKClient)

    • examples/agents.py works fine with the query() function
    • Your issue uses ClaudeSDKClient.receive_response()
    • These might handle agent teams differently

Questions

  1. Does setting continue_conversation=True fix this?

    • I haven't tested it yet, but it seems promising
    • If yes, this might just need better documentation
  2. Should the SDK auto-detect agent teams?

    • If options.agents is set, should it automatically enable multi-turn mode?
    • Or should users have to configure it manually?
  3. Where do teammate messages appear?

    • I don't see a special "teammate message" type in the code
    • They must be embedded in another message type

Quick Test

Would this work?

options = ClaudeAgentOptions(
    agents={...},
    continue_conversation=True  # Try adding this
)

If that fixes it, we just need to update the docs to tell users about it. If not, there's a deeper issue here.

Happy to help investigate further or submit a PR!

kumar-pankaj0 avatar Feb 20 '26 15:02 kumar-pankaj0

Message are written to each team mates inbox json file that can be found in ~/.claude/teams//Inbox/<team-member-name.json> from what I can tell. I am guessing each team member will monitor that file for messages and read them as the come in. It has a message read property.

tlewers01 avatar Feb 24 '26 02:02 tlewers01

+1, any update? team

grhaonan avatar Mar 02 '26 11:03 grhaonan

  1. Does setting continue_conversation=True fix this?

    • I haven't tested it yet, but it seems promising
    • If yes, this might just need better documentation

I will try to investigate. Sorry I've been pulled into other priorities and haven't had the cycles to experiment.

barrcodes avatar Mar 12 '26 18:03 barrcodes

I will try to test the continue conversation parameter later today.

tlewers01 avatar Mar 12 '26 18:03 tlewers01

SDK version: claude-agent-sdk==0.1.48

Setup

Lead + one teammate ("Reverser"). Two ClaudeSDKClient turns over the same session (continue_conversation=True):

  • Turn 1: lead creates team, spawns Reverser, sends SendMessage("HELLO"), waits for reply, returns structured output
  • Turn 2: lead reuses team, sends SendMessage("WORLD"), waits for reply, returns structured output
options = ClaudeAgentOptions(
    allowed_tools=["TeamCreate", "TeamDelete", "Task", "SendMessage",
                   "TaskCreate", "TaskUpdate", "TaskList", "TaskGet"],
    continue_conversation=True,
    system_prompt={"type": "preset", "preset": "claude_code", "append": SYSTEM_PROMPT},
    output_format={"type": "json_schema", "schema": TurnResult.model_json_schema()},
    env={"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"},
)

async with ClaudeSDKClient(options=options) as client:
    await client.query("Reverse this string and return the result: HELLO")
    async for msg in client.receive_response():
        if isinstance(msg, ResultMessage) and msg.structured_output:
            result1 = TurnResult.model_validate(msg.structured_output)
            break
    # turn 2 same pattern

Observed message trace

--- Turn 1 ---
  [T1] system/init
  [T1] tool_use: ToolSearch        input={"query": "select:TeamCreate,SendMessage,..."}
  [T1] text: "I'll create the team, spawn the Reverser teammate..."
  [T1] tool_use: TeamCreate        input={"team_name": "demo_team", ...}
  [T1] tool_use: Agent             input={"name": "Reverser", "prompt": "You are Reverser..."}
  [T1] system/task_started
  [T1] tool_use: SendMessage       input={"recipient": "Reverser", "content": "HELLO"}
  [T1] text: "Message sent to Reverser. Waiting for the reversed string response..."
  [T1] text: "I haven't received a response from Reverser yet, but the system is requiring structured output now."
  [T1] tool_use: StructuredOutput  input={"result": "No response received from Reverser teammate yet"}
  [T1] result: structured={'result': 'No response received from Reverser teammate yet'}

--- Turn 2 ---
  [T2] system/init
  [T2] tool_use: SendMessage       input={"recipient": "Reverser", "content": "WORLD"}
  [T2] text: "I'm seeing idle notifications from Reverser, but no actual message with the reversed string. This confirms the issue..."
  [T2] tool_use: StructuredOutput  input={"result": "No response received from Reverser teammate"}
  [T2] result: structured={'result': 'No response received from Reverser teammate'}

What failed

The lead's SendMessage to Reverser is delivered — Reverser is alive and persists across turns (Turn 2 reuses the team without recreating it). But Reverser's SendMessage reply back never arrives as readable content. In Turn 2 the lead explicitly notes it sees "idle notifications from Reverser" but no message body.

continue_conversation=True does keep the session open across client.query() calls, so that part holds. The gap: a teammate's SendMessage to the lead doesn't surface as a tool result or new user turn — it arrives as a background notification with no accessible content.

barrcodes avatar Mar 12 '26 18:03 barrcodes

This is a fundamental problem with request-response patterns for multi-agent work. The interactive mode has implicit message delivery between turns, but SDK mode has no "between turns."

We hit the same wall and went a different direction: instead of in-process message passing, agents communicate through shared rooms on GroupMind (https://groupmind.one). Each agent polls independently. Messages persist regardless of session lifecycle, so an agent that terminates and restarts picks up where it left off.

IDE Agent Kit (https://github.com/ThinkOffApp/ide-agent-kit) implements this as a lightweight Node.js process alongside the IDE. It handles room polling, webhook relay, and agent nudging via tmux keystrokes. No SDK dependency, works across Claude Code, Codex, and Cursor.

The tradeoff: slightly higher latency (seconds vs milliseconds) but no coupling to session lifecycle. For coordination tasks where agents work in parallel on different parts of a codebase, the latency is fine.

ThinkOffApp avatar Mar 13 '26 10:03 ThinkOffApp

Yeah, I created something similar regarding the polling mechanism. I may stick to that as the solution for now. But I think:

SDK mode has no "between turns."

Is the issue, and honestly I think needs to be addressed.

barrcodes avatar Mar 14 '26 15:03 barrcodes

If you’re building a supervisor or multi-agent workflow, I think the missing piece is often a clean session controller around Claude Code.

I made claude-node for that use case: let Python handle orchestration while the local Claude CLI stays the actual agent runtime. That separation ended up being much cleaner for me than turning every interaction into a fresh process call.

Sharing in case it helps: https://github.com/claw-army/claude-node

maliang-agent avatar Mar 22 '26 09:03 maliang-agent