Peers
Let an agent discover and message other agent sessions without controlling their runs. Use Peers when separately owned sessions need to exchange context, rather than delegate work to a child agent.
While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy.
InMemoryPeerNetwork connects sessions in one application. Give each recipient a LocalPeerInbox, and pass that same inbox both to join() and to its Peers capability. Joining without an inbox is send-only: incoming messages are refused.
from pydantic_ai import Agent
from pydantic_ai_harness import Peers
from pydantic_ai_harness.peers import InMemoryPeerNetwork, LocalPeerInbox
network = InMemoryPeerNetwork()
alice_inbox = LocalPeerInbox()
bob_inbox = LocalPeerInbox()
alice_view = network.join(handle='alice', inbox=alice_inbox)
bob_view = network.join(handle='bob', inbox=bob_inbox)
alice = Agent('anthropic:claude-opus-5-5', capabilities=[Peers(network=alice_view, inbox=alice_inbox)])
bob = Agent('anthropic:claude-opus-5-5', capabilities=[Peers(network=bob_view, inbox=bob_inbox)])
alice.run_sync('Use list_peers to find bob, then send_message with your findings about the migration.')
result = bob.run_sync('Review the migration findings sent by alice.')
print(result.output)
The model gets list_peers(query='') and send_message(to, text, reply_to=None). The list shows other reachable sessions, including their handle, ID, status, waiting_for, status_since, accepts_messages, pending-message count, title, workspace, and branch. The optional query filters by handle, title, workspace, or branch; the list is capped at max_listed (default 30). Send to a listed handle or ID. The send result says whether the message was delivered to a running peer, queued for a peer with no active run, or refused, and includes the message ID for accepted messages. reply_to can reference an earlier message ID; it does not wait for a reply.
Peers reads new messages before and after each model request. Messages waiting when a run starts are included in its first model request. A message that arrives during a run can cause an additional model request before that same run ends. InMemoryPeerNetwork never starts a run: a message to a peer with no active run waits until the application starts the peer’s next turn. Whether a message wakes an idle recipient is the host network’s policy. In sequential mode, InputGuardrail checks the user prompt before queued peer messages are added, so a blocked run sends no request and the messages stay in the inbox. With parallel=True, the request runs alongside the guard, so peer messages can enter history and leave the inbox even if the guard later blocks. Messages that have not entered conversation history remain in the inbox across runs; an agent may complete its run before receiving a reply.
InMemoryPeerNetwork is an in-process example, not a cross-process transport. Its members stay joined, and their handles taken, for the network’s lifetime; to retire a session, set its inbox’s accepting to False. For sessions across processes or machines, implement PeerNetwork.peers() and PeerNetwork.send() in the host. The host owns peer identity, routing, authentication, and any user-visible notifications; the model supplies the recipient, text, and optional reply_to ID. Peers also passes a key built from the sending tool call (run_id:run_step:tool_call_id); a retried send with the same key must not deliver a second message. InMemoryPeerNetwork derives the message ID from it, so LocalPeerInbox drops a repeat, both while the first copy is pending and after it was read: the inbox remembers the IDs of its last max_pending acknowledged messages. PeerNetwork.peers() returns other peers as PeerInfo objects. PeerNetwork.send() builds a PeerMessage whose sender is a PeerSender supplied by the host from its own authenticated identity, never from the model’s tool arguments. It delivers the message and returns a PeerDelivery with status delivered, queued, or refused; it raises LookupError for a peer that disappeared.
LocalPeerInbox(path=...) saves pending messages to an atomically replaced JSON file at a host-chosen per-recipient path. Use a private directory for that path. An inbox without path keeps messages only in memory. Use LocalPeerInbox(accepting=False) to refuse new messages, or change its accepting flag later; pending messages are retained. A file-backed inbox does not provide a network or coordinate simultaneous writers across processes. Pass the same inbox to the recipient’s transport endpoint and Peers(inbox=...); without an inbox bound to Peers, the capability provides sending tools but does not read a recipient inbox.
To hold messages in host storage instead, implement PeerInbox. Peers calls take(run_id) before and after each model request: the first call claims the inbox for that run, and each call returns the messages the run has not taken yet. It calls acknowledge(message_id) once a message has entered conversation history, and release(run_id) when the run ends; messages taken but not acknowledged stay held for the next run. While one run holds the inbox, take returns nothing to another. LocalPeerInbox is the in-process implementation.
TypeAdapter(PeerMessage) is the harness-neutral message format, so an adapter for an agent outside Pydantic AI can exchange messages with a host network:
{
"id": "msg-1",
"sender": {"id": "peer-alice", "handle": "alice", "workspace": "/work/api"},
"recipient": "peer-bob",
"text": "The migration is done.",
"sent_at": "2026-11-13T12:00:00Z",
"reply_to": null
}
text is limited to MAX_MESSAGE_BYTES UTF-8 bytes. The inbox file of LocalPeerInbox is not a cross-process contract: other processes reach a recipient through the host’s transport, which admits each message into the recipient’s inbox.
Incoming text is framed as untrusted peer data on the user channel, with typed provenance metadata. The model sees it as <peer_message sender="alice" id="msg-1">...</peer_message>, framed by core with the sender handle the host supplied, so it never reads as the user speaking. It is not an instruction from the receiving user and cannot grant approval. A host that delivers peer messages itself must send each one as its own message part: merged into a user prompt, peer text loses its provenance and reads as the user’s own words. A peer message that reaches a running agent can still steer it into any tool that does not require approval, so if peers can reach the agent, require approval for tools with side effects. read_peer_message(part) reads a PeerMessage from a tagged message part by its metadata, not by matching the displayed text. Native message serialization preserves that metadata; adapters that discard TextContent.metadata lose the provenance marker on round-trip.
MAX_MESSAGE_BYTES (16384 UTF-8 bytes) and MAX_PENDING (50) are public transport contract defaults. A host transport can use them to reject oversized wire messages and bound incoming queues before messages reach LocalPeerInbox.receive(). Peers also defaults to max_messages_per_run=10 and max_listed=30. Only delivered or queued messages count toward max_messages_per_run. Sending the same text to the same peer twice in one run, or exceeding the limit, tells the model without sending the message. All limits must be positive. See the peer API reference for the host-facing transport types and helpers.
Unlike Subagents, Peers does not create a child run, forward dependencies or usage, or wait for another agent’s result. Its tools use core’s tool-call spans. Delivered peer content is part of the conversation and follows core’s content-capture setting. Delivery is observable through EnqueuedMessagesEvent; the host can inspect LocalPeerInbox.pending() for outstanding messages. The capability adds no per-message or persistence spans, leaving transport admission and inbox telemetry to the host instead of duplicating message records.
Peers does not support durable execution yet: the engine records neither inbox reads nor sends, so a replay could deliver different messages. Combining it with any durable execution capability raises UserError when the agent is constructed.
Bases: AbstractCapability[AgentDepsT]
Let an agent list and message other sessions over a host-provided network.
Bind the recipient’s inbox to this capability to read its messages before and after each model request. Whether a message starts an idle recipient’s run is the host’s policy, not this capability’s.
@classmethod
def combine(
cls,
capabilities: Sequence[AbstractCapability[AgentDepsT]],
) -> AbstractCapability[AgentDepsT]
Two networks under one id must agree: merging recipients would widen the agent’s access.
AbstractCapability[AgentDepsT]
@classmethod
def get_serialization_name(cls) -> str | None
Not spec-serializable: the capability holds a live network and inbox.
def for_agent(
agent: AbstractAgent[AgentDepsT, object],
) -> AbstractCapability[AgentDepsT]
Reject durable execution: the engine records neither inbox reads nor sends, so a replay could diverge.
AbstractCapability[AgentDepsT]
@async
def for_run(ctx: RunContext[AgentDepsT]) -> Self
Start each run with its own send count, duplicate set and taken messages.
Join several agents in one process. The network does not run turns or own their lifetime.
Members stay joined, and their handles taken, for the network’s lifetime. To retire a session, set its
inbox’s accepting to False, or create a new network.
def join(
*,
handle: str,
inbox: LocalPeerInbox | None = None,
workspace: str = '',
title: str = '',
) -> PeerNetwork
Join as handle; return this peer’s network view.
Pass the same inbox to Peers(inbox=...) when constructing the receiving agent.
With no inbox, this peer can send but refuses incoming messages.
PeerNetwork
Bases: Protocol
One peer’s view of its neighbours. The host implements transport and authenticates senders.
@async
def peers() -> Sequence[PeerInfo]
Other reachable peers, never this one, most relevant first.
Sequence[PeerInfo]
@async
def send(
recipient: str,
text: str,
*,
key: str,
reply_to: str | None = None,
) -> PeerDelivery
Build a message from this peer to PeerInfo.id and deliver it.
key identifies this send: a retried send with the same key must not deliver a second message.
Peers passes run_id:run_step:tool_call_id of the tool call that sends it.
Return the recipient’s result. Raise LookupError if the recipient has disappeared.
PeerDelivery
A peer visible to the agent. id addresses it; handle is its short display name.
Address accepted by PeerNetwork.send, unique among reachable peers.
Type: str
Short host-assigned name, also accepted by the agent’s send_message tool.
Type: str
A human-readable description of the peer’s current work.
Type: str Default: ''
The directory the peer works in, if known.
Type: str Default: ''
Its Git branch, if known.
Type: str Default: ''
The peer’s current activity, independent of whether it accepts messages.
Type: PeerStatus Default: 'idle'
With status='waiting', what the peer is waiting for.
Type: str Default: ''
When the current status began, or None if unknown.
Type: datetime | None Default: None
Messages awaiting delivery acknowledgement in this peer’s inbox.
Type: int Default: 0
Whether the peer accepts messages, independently of its activity status.
Type: bool Default: True
Result reported by the receiving inbox.
The handled PeerMessage.id.
Type: str
Enqueued to an active run, held for the next run, or refused.
Type: DeliveryStatus
Explanation of a refusal or a note about queued delivery.
Type: str Default: ''
Messages awaiting acknowledgement in the recipient’s inbox after this operation.
Type: int Default: 0
Bases: Protocol
A recipient’s held messages, as Peers reads them during a run. The host stores and admits them.
One run reads an inbox at a time. Peers takes new messages before and after each model request,
and acknowledges each one once it has entered the conversation history.
@async
def take(run_id: str) -> Sequence[PeerMessage]
Messages held for the reading run that it has not taken yet, oldest first.
The first call claims the inbox for run_id. While another run holds it, return nothing.
Sequence[PeerMessage]
@async
def acknowledge(message_id: str) -> None
Stop holding a message: it entered the reading run’s conversation history.
@async
def release(run_id: str) -> None
End run_id’s claim. Messages it took without acknowledging are held for the next run.
Bases: PeerInbox
Incoming peer messages, in memory or in an atomically replaced JSON file.
Bind one inbox to one recipient. The application supplies a path scoped to that recipient;
its directory is private to the user. An idle inbox never starts an agent run. It remembers the
IDs of its last max_pending acknowledged messages, so a retried send of one of them is not
delivered again. Once the inbox
is bound to Peers, leave take, acknowledge and release to it: a run ID the host claims
with take holds the inbox until it is released.
Whether new messages are accepted. Changing this flag does not discard pending messages.
Type: bool Default: accepting
Whether a run is reading this inbox, so it reads new messages at its next model request.
Type: bool
@async
def receive(message: PeerMessage) -> PeerDelivery
Accept once by message id; refuse oversized messages or a full or disabled inbox.
PeerDelivery
@async
def pending() -> list[PeerMessage]
Undelivered messages, oldest first.
list[PeerMessage]
@async
def take(run_id: str) -> list[PeerMessage]
Claim the inbox for run_id if no run holds it; return its messages not yet taken, oldest first.
list[PeerMessage]
@async
def acknowledge(message_id: str) -> None
Remove a message once it entered the conversation history, and remember its ID.
@async
def release(run_id: str) -> None
End run_id’s claim; unacknowledged messages stay pending for the next run.
Identity supplied by the network, not the agent’s tool arguments.
The sender’s PeerInfo.id, assigned by the host.
Type: str
The sender’s short display name at send time.
Type: str
The sender’s working directory, if known.
Type: str Default: ''
One message; TypeAdapter(PeerMessage) is its JSON wire format.
Host-generated identifier, derived from the send’s key so a retried send keeps it.
Type: str
Recipient’s PeerInfo.id.
Type: str
Untrusted peer-authored content, bounded by its UTF-8 byte length.
Type: str
The sending host’s timestamp.
Type: datetime
Identifier of an earlier message this one answers, if any.
Type: str | None Default: None
def read_peer_message(part: ModelRequestPart) -> PeerMessage | None
Read a message from its tagged part, without relying on its model-facing text.
PeerMessage | None
Accepted by an active run, queued for the next run, or rejected without delivery.
Default: Literal['delivered', 'queued', 'refused']
Host-reported activity: no run, an active run, or a run waiting for user input or approval.
Default: Literal['idle', 'running', 'waiting']
Default UTF-8 text limit, shared with transports that reject oversized messages before inbox delivery.
Default: 16384
Default inbox capacity, shared with transports that bound their incoming queues.
Default: 50