Add peer messaging with `Peers` in `pydantic-ai-harness`

Merged
DS
21d ago
+2124-34

No linked issue; maintainer David requested this feature.

#12450 (drops core's late-registration UserWarning) is on main, so this PR carries no test-only warning filters. The pause/resume test for a message queued while the run is paused is in; the case where the message arrives in the step that produces the deferred call waits on #11956 (thread), because on main that run does not pause.

Why we make these changes

Independent agent sessions have no way to find or message each other. Peers adds discovery and messaging over a host-provided network and inbox, so the same tools work in one process, across clai2 processes, or on a host that stores inboxes durably. Related PRs #10447 and #10481 are separate.

New public surface

  • pydantic_ai_harness.peers.Peers
  • Host protocols: PeerNetwork (peers(), send(recipient, text, *, key, reply_to=None)) and PeerInbox (take, acknowledge, release)
  • In-process implementations: InMemoryPeerNetwork, LocalPeerInbox (memory or JSON file, public accepting flag)
  • Data: PeerMessage, PeerSender, PeerInfo, PeerStatus, PeerDelivery, DeliveryStatus, read_peer_message
  • Limits: MAX_MESSAGE_BYTES, MAX_PENDING

User-visible behavior

The model gets list_peers and send_message. Peers takes new messages from the recipient's inbox before and after each model request: queued messages enter the first request, and a message that arrives mid-run adds one more request to that run. Each send carries the sending tool call's run_id:run_step:tool_call_id as its key, so a retried send delivers once. InMemoryPeerNetwork never starts an idle peer's run; a host network sets its own wake policy. Durable execution capabilities are rejected at construction, because the engine records neither inbox reads nor sends.

Verification

  • Peer tests pass, including a host-implemented inbox, keyed retries, mid-run delivery, abort redelivery and shared-inbox ownership.
  • Docs parity, doc snippet, skill example, history append-only (now with a peer message delivered between runs) and capability combine tests pass. Focused Pyright and pre-commit pass.

Choices made on takeover (2026-11-13)

  • Guardrail docs conflict: kept main's sanitize_messages sentence and this PR's peer-message skip wording.
  • Douwe's harness-neutral contract: the docs now specify TypeAdapter(PeerMessage) JSON as the wire format and say the LocalPeerInbox file is not a cross-process contract, because it does not coordinate concurrent writers. Cross-process transport stays with the host (#11673).
  • Douwe's provenance point: the docs show the model-facing <peer_message sender=... id=...> frame; peer text never reads as the user.
  • Peers makes the Harness table 90 rows, so the comparison pages, Harness index and README now say 90+.
  • Douwebot round on f2acd1492: added a THREAT_MODEL.md peer-messaging row, LocalPeerInbox.acknowledge now loads a file inbox first, and the append-only suite delivers a peer message between runs.
  • David's idle-wake heads-up: Peers keeps leaving wake to the host network; clai2 send in #11673 can wake a recipient.

What changes for existing users

Nothing unless they opt into Peers.

Approved design

Host-implemented network and inbox protocols with in-process implementations; persist inboxes and acknowledge messages once they enter history; preserve user-channel provenance; enforce message and queue limits. clai2 transport remains separate and out of scope.

PR decisions

2026-10-23 · Relation to #10447 and #10481 · iter -

  • Decision: Separate from both; share message frame, inbox ack semantics and send_message shape with #10447; #10481 lands as is and is superseded later by registry+socket live watch
  • Why: Different process boundary and authority model (peers are equals across processes; teams are owner-scoped children; #10481 is a polling web view)
  • Source: https://github.com/pydantic/pydantic-ai/pull/10447

2026-10-23 · Registry granularity per process · iter -

2026-10-23 · Attach at terminal level · iter -

2026-10-23 · Peer message part shape · iter -

2026-10-23 · No idle auto-start kept · iter -

  • Decision: Idle recipients queue in a persisted inbox and show a row; no case made for auto-start; receiver opt-in wake is a possible follow-up
  • Why: Authority, loop, and surprise costs outweigh request/reply convenience
  • Source: https://github.com/pydantic/pydantic-ai/pull/10447

2026-10-26 · Use the registered tool_result frame for peer text · iter -

2026-10-27 · pre-push review 1 of 3 at 90fd5302ae89dd162742d3419b743364b1e72aa5 · iter -

2026-10-27 · pre-push review 1 preflight failed at 90fd5302ae89dd162742d3419b743364b1e72aa5 · iter -

2026-10-27 · pre-push review 2 of 3 at 074855d6c6069afd163282c8c5872e48cfa139fe · iter -

2026-10-27 · pre-push review 2 could not inspect candidate · iter -

  • Decision: Review reported diff outside project root and no git-show tool; no verdict, no push
  • Why: Task b68e8c22d403431eb78b0e40027d346a. Move immutable candidate diff and source snapshot inside isolated policy checkout for final slot
  • Source: https://github.com/pydantic/pydantic-ai/tree/harness-peers

2026-10-27 · pre-push review 3 of 3 at 074855d6c6069afd163282c8c5872e48cfa139fe · iter -

2026-10-27 · pre-push review 3 remediated at 074855d6c6069afd163282c8c5872e48cfa139fe · iter -

2026-10-27 · Hosted-review remediation at 6579acf3c · iter -

  • Decision: Buffer peer data until the initial model-request handler passes guards; snapshot network membership across awaits; release send reservations on failure; use peer_message framing with shared lightweight provenance and cross-frame escaping; keep approved transport defaults public but remove the unused public make helper
  • Why: Reproduced guard bypass and concurrent join failure. 42 focused behavior/framing/guard tests, 16 docs parity cases, focused Pyright and precommit passed. Local review budget exhausted; hosted review repeats after push
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671

2026-10-27 · Live framing probes need provider credentials · iter -

  • Decision: Attempted OpenAI, Anthropic and Google framing probes; all failed at provider construction with UserError requiring API keys. Do not claim live provider verification
  • Why: No .env file or API keys in the lane environment; automated TestModel integration and framing tests pass
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671

2026-10-27 · Deliver queued context in the first guarded request · iter -

  • Decision: Attach the inbox in before_model_request, inside request wrappers after sequential guards, rather than buffering until the first response; also prioritize exact peer IDs over handles and check in-flight message keys
  • Why: Hosted feedback confirmed extra-call cost, ID/handle ambiguity and enqueue-ID collision. 30 peer tests now pass, including first-request context, blocked sequential/parallel guards and both collision reproductions. Local review budget remains exhausted
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#discussion_r4394622417
  • Supersedes: Hosted-review remediation at 6579acf3c

2026-10-27 · Pin model-facing peer requests and close CI branch gap · iter -

  • Decision: Added complete serialized request snapshots with volatile IDs/timestamps normalized; synchronized the parallel-guard test; documented mid-turn extra-request cost; added send-only enqueue composition case
  • Why: All CI tests passed on c7b3e2a, but one branch in peers/_capability.py lacked coverage. Focused run now covers all 104 statements and 28 branches at 100%, with 31 peer tests plus combine case passing; no production code changed
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#discussion_r4394732141

2026-10-27 · Live framing probes verified through env-run · iter -

  • Decision: Used env-run with the shared base .env; OpenAI gpt-6-astra, Anthropic claude-opus-5-5 and Google gemini-4-argon all returned SAFE for forged peer/system-tag payloads with supports_inline_system_prompts both true and false
  • Why: Six real provider requests completed; all inboxes acknowledged delivery (pending zero). Credentials were supplied only through the helper, not read or printed. This supersedes the missing-key limitation
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671
  • Supersedes: Live framing probes need provider credentials

2026-10-27 · In-memory peers without inboxes are send-only · iter -

  • Decision: A join with inbox=None now refuses incoming messages and advertises messages disabled; keep the approved PeerNetwork signatures unchanged. Expanded public API docs and renamed the prompt-selection flag to skip_harness_data
  • Why: Reproduced inaccessible default inbox accepting a message no agent could consume. 32 peer tests plus 8 docs parity cases, focused Pyright and precommit pass. Prior head CI passed fully
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#discussion_r4394886123

2026-10-27 · Use the newly merged public framing registry · iter -

  • Decision: Merged main, registered peer_message with pydantic_ai.framing.register_tag and used wrap; removed the manual shared Harness escaper and task-report changes; added a forged-peer tool-result request test and corrected docs parity/API wording
  • Why: The public framing API landed after this lane began. 33 peer tests and 8 docs parity cases, focused Pyright, precommit, and all six real provider/native-fallback probes pass with the public wrapper
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#discussion_r4395296029
  • Supersedes: Use the registered tool_result frame for peer text

2026-10-28 · Make receiver acceptance and durability boundaries explicit · iter -

  • Decision: Added optional accepting=True constructor configuration with documented mutable flag, unified the Peers API-reference identifier, and reject durability-capability composition at construction because live host state cannot replay
  • Why: The approved PeerNetwork method signatures remain unchanged. 37 peer/composition cases pass, including real Temporal/DBOS/Prefect constructors; docs and skill describe the boundary. Unsupported live state must fail before tool execution under Harness authoring rules
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#discussion_r4395466102

2026-10-28 · Keep static snippet import-warning policy across lazy exports · iter -

  • Decision: Applied the snippet checker existing import-warning suppression to lazy attribute resolution as well as import_module; no production warning suppression
  • Why: CI reproduced a late tag-registration warning from hasattr on the lazy Peers export. A focused lazy-module warning test fails before the fix and passes after; 948 snippet checks pass, 56 skip
  • Source: https://github.com/pydantic/pydantic-ai/actions/runs/40604175469

2026-10-28 · Keep the agreed separate transport and inbox contract · iter -

  • Decision: Declined the optional network-inbox inference/convenience API in this PR; preserve explicit double binding and send-only transports. Documented delivery observation through core events and inbox state rather than adding per-message spans
  • Why: The approved protocol has peers/send only. A convenience API is a separate design choice; receiving may happen outside an agent run and hosts own transport/inbox telemetry. Clarified the generic durability rule and verified docs parity
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#discussion_r4395691567

2026-10-28 · Treat independent skill examples as separate import programs · iter -

  • Decision: Filter only the late peer_message registration warning from the peers module inside skill-example tests; production diagnostics and other warnings remain unchanged
  • Why: The lowest-version shard executes the standalone Peers example after earlier examples rendered tags. Reproduced by rendering a core frame before pytest startup; 10 delegation/planning examples pass (2 skip) with the precise module/message filter
  • Source: https://github.com/pydantic/pydantic-ai/actions/runs/40607732334

2026-10-28 · Keep inbox run binding out of the host API · iter -

  • Decision: Privatized attach/detach/acknowledge, the enqueue event handler and stored inbox configuration; receiving/pending/accepting/running remain public. Tests now drive lifecycle through real Agent runs rather than internal helpers
  • Why: The approved host contract does not expose binding order. Added aborted-before-delivery replay, shared-owner and real enqueue-ID collision cases; removed impossible nullable callback branch. 38 peer tests, focused Pyright and precommit pass; protected-access-only suppressions document package-private integration
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#discussion_r4395924879

2026-10-28 · Isolate the standalone export smoke test import diagnostic · iter -

  • Decision: Applied the same precise peer-module late-registration warning filter to the standalone export import check; production diagnostics remain active
  • Why: CI found the third independent-program import boundary. Reproduced by escaping a core frame before pytest startup; all three export cases pass with the focused test filter. No production code changed after clean hosted approval of 368f3f013
  • Source: https://github.com/pydantic/pydantic-ai/actions/runs/40617266856

2026-10-29 · David holds Peers for a core-first registration fix · iter -

  • Decision: David selected Core-first fix: preserve opt-in scope and hold PR11671 until core settles lazy framing registration and prefix safety; do not eagerly register for all Harness users
  • Why: A real application repro emits the warning on late Peers import and re-renders prior peer_message-looking data differently. Moving registration into the Harness root changes non-Peers behavior/imports. Blocking thread remains open; test filters are not an application-level solution
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#discussion_r4396241787

2026-11-01 · One Peers surface over host-owned durable inboxes, staged · iter -

  • Decision: David chose to combine the split and a durable implementation: the server owns the durable inbox, Peers stays the agent-facing tools everywhere. In this PR: host-implementable inbox, pull delivery at each model request, idempotency key on PeerNetwork.send, wake-neutral wording. Keep the durability rejection until a durable inbox exists to test
  • Why: A host-specific send_message would give models a second tool with different framing, provenance and dedupe keys; public protocol shape is cheaper to settle before merge, lifting the rejection later only widens support
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#issuecomment-6499475704
  • Session: 43bbe16e-a650-4cb4-aa7d-2c389cf35dc0
  • Supersedes: Keep inbox run binding out of the host API

2026-11-01 · Push Peers code while the merge hold stands · iter -

  • Decision: David chose to merge main and push 9a4c1cbad; the merge hold for the core framing fix stays, the earlier no-pushes-while-held note is lifted
  • Why: The inbox protocol change does not touch tag registration, which is what the hold covers; unpushed work is invisible to reviewers
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671
  • Session: 43bbe16e-a650-4cb4-aa7d-2c389cf35dc0

2026-11-01 · Core framing fix via issue, then a core PR; Peers does not wait for CapabilityPart · iter -

  • Decision: Open a core issue to drop register_tag's late-registration UserWarning and state the registered-before-rendered contract, then a core PR; keep Peers on register_tag + wrap and migrate to CapabilityPart with the other Harness capabilities when #11935 lands
  • Why: #11813 removes the warning's re-render premise but keeps the warning; #11935 timing depends on #11813 and #11836
  • Source: https://github.com/pydantic/pydantic-ai/pull/11813
  • Session: 43bbe16e-a650-4cb4-aa7d-2c389cf35dc0

2026-11-01 · Filed core issue #12163 for the late-registration warning · iter -

  • Decision: Immediate-work route: assigned dsfaccini, labelled pydanty:skip and pkg:core; a separate core PR follows in its own worktree
  • Why: The #11671 framing blocker resolves in core, outside this harness PR
  • Source: https://github.com/pydantic/pydantic-ai/issues/12163
  • Session: 43bbe16e-a650-4cb4-aa7d-2c389cf35dc0

2026-11-01 · Push da27d4def under exhausted pre-push review budget · iter -

  • Decision: No local pre-push review: all three slots were used on 2026-10-27; hosted douwebot review covers the inbox protocol change
  • Why: Delta since the last reviewed tree is a public API change, not exempt; budget exhaustion is the recorded basis. Targeted peer, docs, snippet, skill, history and combine tests, focused Pyright and pre-commit pass
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671
  • Session: 43bbe16e-a650-4cb4-aa7d-2c389cf35dc0

2026-11-01 · Triaged 25 stale hosted-review threads at 018e35a02 · iter -

  • Decision: 24 were already fixed or superseded by the inbox protocol and were answered and resolved; the remaining substring checks were snapshotted in 018e35a02; the framing blocker stays open for #12163
  • Why: Each verdict was checked against head with the fixing commit cited; the bot also flagged that a host calling take on a bound LocalPeerInbox would hold it, now documented on the class
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671
  • Session: 43bbe16e-a650-4cb4-aa7d-2c389cf35dc0

2026-11-01 · LocalPeerInbox remembers acknowledged IDs · iter -

  • Decision: David chose to keep the send-key contract (a retry is never delivered twice) and make LocalPeerInbox save the IDs of its last max_pending acknowledged messages next to its messages
  • Why: Douwebot found the bundled inbox deduped only while the first copy was pending; Douwe asked that the inbox dedupe on the key
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#discussion_r4437220895
  • Session: 43bbe16e-a650-4cb4-aa7d-2c389cf35dc0

2026-11-01 · Douwe points 5 and 6 in docs; point 4 deferred to #11956 · iter -

  • Decision: Docs, README and skill say each peer message must be its own part and to gate side-effecting tools with approval; the pause-resume exactly-once test waits for #11956, tracked in the open douwebot thread
  • Why: #7537 is open on main, so the pause the test needs is still discarded; whichever of #11956 and this PR merges second adds the test. make_peer_message stays private, as decided in 6579acf3c
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#discussion_r4437220900
  • Session: 43bbe16e-a650-4cb4-aa7d-2c389cf35dc0

2026-11-13 · Merge holds re-pointed to #12450 and #11956 · iter -

2026-11-13 · Guardrail docs conflict keeps both changes · iter -

2026-11-13 · Douwe's harness-neutral contract: document the PeerMessage JSON, not the inbox file · iter -

  • Decision: Docs and README now show TypeAdapter(PeerMessage) JSON as the harness-neutral wire format and state the LocalPeerInbox file is not a cross-process contract; the model-facing peer_message frame is shown
  • Why: LocalPeerInbox does not coordinate concurrent writers, so a file contract would invite corruption; cross-process transport is the host's (#11673), out of scope per approved design
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#issuecomment-6499475704

2026-11-13 · Idle-recipient wake stays host policy · iter -

  • Decision: Keep Peers and InMemoryPeerNetwork from starting idle runs; a host network such as clai2 send in #11673 may wake a recipient
  • Why: Starting a run needs the host's model, deps and approvals, which a capability does not own; recommended option for David's heads-up
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671

2026-11-13 · Push 9d0c546b1 under exhausted pre-push review budget · iter -

  • Decision: No local pre-push review; all three slots were used on 2026-10-27; douwebot and Macroscope review the head
  • Why: Delta since last reviewed tree is a merge with conflict resolution and docs; budget exhaustion is the recorded basis
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671

2026-11-13 · Capability count 80+ to 90+ · iter -

2026-11-13 · Douwebot round at f2acd1492 · iter -

  • Decision: Added a THREAT_MODEL peer-messaging row and canonical link; LocalPeerInbox.acknowledge loads the file first (test fails without it); the append-only suite now runs Peers with a message delivered between runs
  • Why: All three findings reproduced or were documented requirements; the two standing holds remain open
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#discussion_r4564713689

2026-11-13 · Review state at 1c843c33e · iter -

  • Decision: CI green; douwebot REQUEST_CHANGES with no new findings, held only by #12450 and #11956; Macroscope correctness clean, approvability needs human approval
  • Why: Both holds are external PRs still open on 2026-11-13; nothing left to change in this PR until one lands
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671

2026-11-13 · Pause/resume exactly-once test split · iter -

  • Decision: Added the inbox-queued-while-paused test, which passes on main; the arrives-in-the-deferred-step variant still needs #11956, because on main that run does not pause (probe: str output, approval lost, peer message once)
  • Why: This tests point 4's exactly-once guarantee without waiting on core; the remaining variant is the #7537 bug
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#discussion_r4437220900

2026-11-13 · Stack on #12450 and drop the warning filters · iter -

  • Decision: Merged main into #12450 (conflicts in _framing.py imports and one test), retargeted this PR's base to framing-late-registration, and reverted all test-only peer_message warning filters
  • Why: Mike asked to iterate until douwebot approves; the only blocker was the warning #12450 removes. Stacking follows Mike's stacked-PR workflow; merge #12450 first, then retarget to main
  • Source: https://github.com/pydantic/pydantic-ai/pull/11671#discussion_r4396241787

2026-11-13 · Douwebot approved e202c4604 · iter -

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
  • PR title is fit for the release changelog.