Let `CodeMode` run code on a caller-built Monty pool with `monty_pool_factory`

DM
2d ago
+250-6

CodeMode can now run its sandbox on a pool you build, so it can connect to servers that need more than a URL, such as Logfire Agent Sandboxes, which require an Authorization header.

import logfire
from pydantic_ai import Agent
from pydantic_ai_harness import CodeMode

agent = Agent('openai:gpt-5.5', capabilities=[CodeMode(monty_pool_factory=logfire.agent_sandboxes)])
  • New CodeMode(monty_pool_factory=...): a zero-argument function that returns an unentered AsyncMonty or AsyncMontyWebsocket. CodeMode calls it once per agent run, enters the pool on the first run_code call, and closes it when the run ends. It takes a factory rather than a pool instance because one pool shared by concurrent runs would be closed under the other run.
  • Setting both monty_pool_factory and monty_sandbox_url raises UserError.
  • With a factory, the pool's own request_timeout applies.
  • Docs: a "Logfire Agent Sandboxes and custom pools" section in the Code Mode guide.

Tested end to end with a real model (gpt-5.5 through the gateway) against hosted Agent Sandboxes and a local Monty WebSocket relay. New tests cover per-run pools, the Authorization header reaching a loopback server, lazy connection, and the mutually exclusive options.

logfire.agent_sandboxes() is added in pydantic/logfire#2658, so the Logfire example needs that release.

  • No linked issue: small capability option needed for Logfire Agent Sandboxes.

Checklist

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

Drafted with Claude (Opus 5.5) and reviewed by me.