Keep the `run_code` REPL with the `clai2` session, through a new `CodeMode` `repl_store`

Merged
MP
2mo ago
+1211-23

No linked issue: requested directly, porting behaviour Code Puppy already ships (its commit 7275868f).

Why we make these changes

clai2 runs each prompt as a new agent run, and harness CodeMode gives every run a fresh Monty REPL. A variable set with run_code in one prompt was gone in the next, although the run_code description tells the model state is preserved. Only the harness can let the REPL outlive a run, so CodeMode gains an opt-in store, and clai2 implements it per saved session.

New public surface

  • pydantic_ai_harness.code_mode.CodeModeReplStore: a protocol with async load(ctx) -> bytes | None and save(ctx, state: bytes | None).
  • CodeMode(repl_store=...) and CodeModeToolset(repl_store=...): keyword-only, default None.

User-visible behavior

prompt 1: run_code("x = 41")    ->  {}
prompt 2: run_code("x + 1")     ->  before: Type error: `x` used when not defined
                                    after:  42, also after /resume or clai2 --resume
  • clai2 keeps the session's REPL in sessions.repl/<id>.bin beside sessions.db. --fork-session, /fork, and resuming a busy session give the copy its own state. Deleting a session in /resume removes it. Sub-agents keep run-scoped REPLs. States over 32 MiB are not saved, and the model guidance says state persists only for runs whose state is kept.
  • The harness restores before a run's first snippet and saves when the run ends. It skips the first-snippet type check for restored names. restart: true replaces the state, and a state Monty cannot load, or one saved under other resource_limits, starts a fresh REPL. The save is shielded and time-bounded, store errors are logged, nothing is saved while an eager statement is still running, and the store is not used under durable execution.

Verification

  • tests/harness/code_mode/test_repl_store.py: carry-over (plain and eager), restart, unloadable, foreign and other-limits states, cancellation, failing and hanging stores, stuck eager pump, durable execution.
  • tests/clai2/test_repl_state.py: headless prompts in separate shells, resume, --fork-session, /fork, busy-resume fork, browser deletion, stale IDs, oversized states, file errors.

What changes for existing users

Nothing for harness users who do not pass repl_store; in clai2, run_code state now carries across prompts in a session.

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.