Add an IPython Code Mode (`IPythonCodeMode`) alongside the Monty-based `CodeMode`

Merged
MP
1mo ago
+3047-514

Fixes #11550

Why

Code Mode runs model-written code in Monty, which is the right default for production and web-facing agents but deliberately restrictive. Local agents (data analysis, coding assistants) want full CPython, installed packages, and state that lasts the whole run, like Prime Agent's ipython tool (#11550). This adds that as a separate capability with the same run_code surface, behind a new ipython extra, with docs that say it is not a sandbox and recommend Monty for anything web-facing.

New public surface

  • pydantic_ai_harness.IPythonCodeMode(tools='all', max_retries=3, *, max_tool_calls=100, timeout=60.0, kernel=None)
  • pydantic_ai_harness.ipython_code_mode.IPythonKernel(kernel_name='python3', *, cwd=None, startup_timeout=60.0) with start(), restart(), shutdown(), async with
  • pydantic_ai_harness.ipython_code_mode.IPythonCodeModeToolset
  • extra: pydantic-ai-harness[ipython] (ipykernel, jupyter-client)

User-visible behavior

- agent = Agent('anthropic:claude-sonnet-4-6', capabilities=[CodeMode()])  # Monty subset only, no third-party packages
+ agent = Agent('anthropic:claude-sonnet-4-6', capabilities=[IPythonCodeMode()])  # full CPython; local agents only

The model gets one run_code tool. Cells run in an ipykernel process started on first use and stopped when the run ends (or kept across runs via kernel=IPythonKernel()). Tools become synchronous kernel functions dispatched back through Pydantic AI (validation, hooks, approval handlers, tool_calls_limit, ToolReturn.content forwarding, nested-call metadata as in CodeMode). Return values follow CodeMode's shapes; images (displayed or returned) come back as images. Output is capped at 10 MiB; timeout interrupts a cell and keeps state, escalating to a kernel restart if the interrupt is ignored; crashes report a lost state; IPythonKernel.shutdown() is shielded and bounded. Durable execution is refused with UserError.

The Monty-free tool plumbing both modes share (eligibility, name sanitizing, nested-call dispatch and recording) moves from code_mode/_toolset.py into _code_tools.py, unchanged, so the ipython extra does not need pydantic-monty.

Verification

tests/harness/ipython_code_mode/test_ipython_code_mode.py: 47 tests against real kernels (most share one module-scoped kernel; process-lifecycle tests carry the subprocess marker), 100% line and branch coverage of ipython_code_mode/ locally. Existing tests/harness/code_mode passes unchanged apart from import paths.

What changes for existing users

Nothing: CodeMode behavior is unchanged.

Open questions from the issue: what I picked and why
  • Separate class or CodeMode(runtime=...)? Separate IPythonCodeMode. The safety difference is the point, most CodeMode options (mount, os_access, resource_limits, eager, speculate, repl_store) don't apply, and a separate extra keeps Monty out of the dependency.
  • Agent's environment or a managed one? %%bash? A separate ipykernel process, by default from the python3 kernelspec with the agent's own interpreter, so installed packages work; IPythonKernel(kernel_name=...) picks another kernelspec/environment. It talks over Unix sockets in the temp dir (TCP on Windows). Magics, !cmd and %%bash stay available as standard IPython: blocking them buys nothing when subprocess is importable; the Shell capability remains the option with an allowlist.
  • Run the kernel in a harness sandbox? Not in this PR. Tool calls ride the Jupyter stdin channel, so a remote kernel is possible later, but that needs its own design (connection files, ports, lifecycle per sandbox); I'd file it as a follow-up.
  • What carries over? tools selector, max_tool_calls, max_retries, restart, return shapes, nested-call metadata, ToolReturn.content. Not: eager and speculation (need a stoppable sandbox), durable execution (kernel state can't be replayed; refused with UserError), dynamic_catalog. Cross-run state is an explicit IPythonKernel instead of a repl_store, since a live kernel can't be serialized. Tool functions are synchronous: the stdin channel carries one request at a time, so async stubs would promise concurrency they can't deliver.
  • Refuse or warn inside a web app? Neither: detection would rely on heuristics (imported frameworks, running servers) that misfire both ways. The docs, README, docstring and skill carry the warning, and the docs compare both modes.
  • Telemetry: no spans of its own; core's tool spans cover run_code and every nested call, and timeouts/restarts/crashes are in the run_code retry the span records.
PR decisions
  • 2026-10-27 · pre-push review 1 of 3 at a27b3deea: remediated: refuse durable execution in for_run; shield kernel shutdown and lazy lock; warning above version blockquote; PID-gone, anyio-cancel, ToolSearch and approval tests
  • 2026-10-27 · pre-push review 2 of 3 at 535f7357e: remediated: bounded shutdown escalation (wait, interrupt, kill); async test tools; coverage tests
  • 2026-10-27 · pre-push review 3 of 3 at 9ca35a723: remediated: invalid image data falls back to text; shutdown returns after kill instead of a final unbounded lock wait. Budget exhausted; no fourth review
  • 2026-10-27 · hosted review and CI findings after push: fixed: timeout enforced on cells that keep printing or catch the interrupt; output buffer stops growing past the cap; a cancelled cell that ignores the interrupt gets its kernel stopped; zmq channels closed after a killed kernel; jupyter-client>=8.6.3; Windows TCP exposure documented
  • 2026-10-27 · uv.lock marker churn: kept uv's output; adding the extra rewrites some existing markers for the mcp-tasks conflict forks (adding only jupyter-client produces the same churn)

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.