github/copilot-sdk · error · TypeError

agent_id must be a string

Error message

agent_id must be a string

What it means

The message dataclass (a ChatMessage-like record with an `agent_id: str` field) validates its fields in __post_init__ and raises this TypeError when agent_id is not a str. Because Python dataclasses do not enforce annotations at runtime, the library performs this explicit check to keep agent identity a string throughout the session API.

Solutions

  1. Convert the value to a string before construction: `Message(agent_id=str(agent_id), ...)`.
  2. Ensure the source of agent_id actually supplies a non-None string; fix upstream parsing if it yields None.
  3. If agent_id is genuinely optional in your flow, use a sentinel string or restructure rather than passing None.

Example fix

// before
msg = Message(agent_id=agent.id, content="hi")  # agent.id is int

// after
if not isinstance(agent.id, str):
    raise ValueError("agent id must be a string")
msg = Message(agent_id=str(agent.id), content="hi")
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(agent_id, str):
    raise ValueError(f"agent_id must be str, got {type(agent_id).__name__}")

Type guard

def is_agent_id(value: object) -> TypeGuard[str]:
    return isinstance(value, str) and len(value) > 0

Try / catch

try:
    msg = Message(agent_id=agent_id, content=content)
except TypeError as e:
    if "agent_id" in str(e):
        msg = Message(agent_id=str(agent_id), content=content)
    else:
        raise

Prevention

When it happens

Trigger: Constructing the message with agent_id as None, an int, an AgentId-like object, bytes, or a missing-then-defaulted value — e.g. `Message(agent_id=123, ...)` or passing an optional agent id that was None.

Common situations: Passing a typed ID wrapper object instead of str(agent_id); JSON payloads where agent_id was null; mixing agent IDs from an older API version where they were numeric.

Understand the failure class

Background: Type mismatch errors: IllegalArgumentException, TypeError and type guards across 150 open-source libraries — this error's family across 150 libraries.

Related errors


AI-assisted analysis of github/copilot-sdk@cd8cf15dc3 (2026-09-09). Data as JSON: /api/errors/82cfcda5efa01ddf. Report an issue: GitHub.

Appendix: source

Thrown at python/copilot/session.py:291

    """MIME type of the inline data"""
    displayName: NotRequired[str]


Attachment = FileAttachment | DirectoryAttachment | SelectionAttachment | BlobAttachment


@dataclass(frozen=True)
class AgentMessageSource:
    """Identify the agent that produced a message.

    The agent ID is opaque and is sent unchanged after the ``agent-`` prefix.
    """

    agent_id: str

    def __post_init__(self) -> None:
        if not isinstance(self.agent_id, str):
            raise TypeError("agent_id must be a string")


MessageSource = Literal["user", "system"] | AgentMessageSource
"""Message provenance, independent of delivery mode."""

# ============================================================================
# System Message Configuration
# ============================================================================


class SystemMessageAppendConfig(TypedDict, total=False):
    """
    Append mode: Use CLI foundation with optional appended content.
    """

    mode: NotRequired[Literal["append"]]
    content: NotRequired[str]

View on GitHub (pinned to cd8cf15dc3)