Skip to content

FEAT: Sandbox interface for model tool calls, with a bounded tool loop and a check scorer - #4100

Closed
Richard Lundeen (richlundeen) wants to merge 5 commits into
microsoft:mainfrom
richlundeen:richlundeen-sandbox-interface
Closed

Richard Lundeen (richlundeen) wants to merge 5 commits into
microsoft:mainfrom
richlundeen:richlundeen-sandbox-interface

Conversation

@richlundeen

Copy link
Copy Markdown
Contributor

Description

To test models that act by running code, their tool calls must run somewhere isolated that can keep their work across a conversation, and something other than the model must say what that work did. This PR adds a Sandbox base class that any code-execution infrastructure can implement, tools that run a model's calls in a sandbox through OpenAIResponseTarget's tool loop, and a scorer that checks the effect in the same sandbox.

  • Sandbox (experimental, pyrit._code_execution): an adapter implements a few hooks (_execute_async, and for sandboxes that keep state, sessions, status and reset). The base class enforces the rules every sandbox follows: one shared session that callers take turns using, first come first served within one deadline; retries only when nothing ran (a busy open, a lost session); renewal before a session time limit; idle close; runs, closes and resets that finish even when their caller gives up, and runs that never start once it has; quarantine when a close or reset can't be confirmed, until an operator releases or resets; and evidence (warnings, partial runs, execution ids). It implements SandboxClient, so ProgramExecutionScorer works with any adapter.
  • DockerSandboxClient is now the example adapter: a call sandbox, with a fresh container per run and no sessions. Its isolation, cleanup and identity are unchanged. Invalid input now raises SandboxInputError (a ValueError) before anything runs, including arguments too long for a command line; unexpected failures surface as SandboxExecutionError.
  • SandboxToolProvider: a run_<runtime> tool per runtime (run_python, …), plus write_file, read_file and list_dir where files persist. Results are JSON with the exit code and bounded output. Arguments are checked against the sandbox's limits before anything runs, so a rejected call is never recorded as invoked. A sandbox failure raises the new ToolInfrastructureError, which also records whether anything may have run.
  • OpenAIResponseTarget: max_tool_rounds (default 10, matching the LiteLLM tool loop in FEAT: Add native Claude target and bounded tool execution #4021) bounds the previously unbounded tool loop. A tool raising ToolInfrastructureError ends the turn with an error response after every call in the round has a result, instead of asking the model to fix infrastructure. The model is told only that the tool's infrastructure failed; the error response, which is never replayed to the model, keeps the details and a ToolLoopStop reason in its metadata. Malformed-argument results now include the validation message, so the model can correct its call.
  • SandboxCheckScorer: runs a fixed check program in the sandbox after a turn and scores the judged response true or false by what it finds, or undetermined when the sandbox fails or the check doesn't finish. The response's own text never runs, stored verdicts are never reused (the sandbox can change), and the check's program and output are stored as an observation linked to the score.
  • SandboxRegistry (targets, scorers and operators share one Sandbox per sandbox, by name; re-applying the configuration closes the registered sandboxes first), FakeSandbox for tests, and a contract-test kit, check_sandbox_contract_async, that adapter authors run against a live sandbox to check declared limits, error mapping, state, status, reset and closing twice.
  • Docs: doc/code/targets/12_sandboxed_tool_calls.md, and the Code Execution, Targets and Scorers sections of doc/code/framework.md.

Demonstration, with scripted model replies and a local test sandbox: the model calls run_python with open('flag.txt', 'w').write('x'), and the check program is print('present' if os.path.exists('flag.txt') else 'absent'), expecting present.

Scored Score Rationale
Before the turn false Check program: The program did not produce the expected result under python: case 0 output did not match.
After the turn true Check program: All 1 case(s) produced the expected result under python.

The model's tool result: {"exit_code": 0, "stdout": "wrote it\r\n", "stderr": "", "stdout_truncated": false, "stderr_truncated": false, "timed_out": false, "resource_limit_exceeded": false, "duration_ms": 218} (the program also printed wrote it; the sandbox ran on Windows).

Behavior changes:

  • OpenAIResponseTarget targets that run tools now stop after 10 tool rounds per send by default; pass a larger max_tool_rounds for longer agentic loops.
  • DockerSandboxClient accepts at most 16 KiB of arguments per run (they go on a command line), so a ProgramExecutionScorer case with longer arguments now scores undetermined instead of running; pass long data through standard input.

Related: #4021 (native Claude target with a bounded tool loop, which can adopt ToolInfrastructureError and ToolLoopStop), #3218 (program execution scorer).

🤖 Generated with Claude Code

…p and a check scorer

Add a Sandbox base class that any code-execution infrastructure can implement,
tools that run a model's calls in a sandbox through OpenAIResponseTarget's tool
loop, and a scorer that checks the effect in the same sandbox.

- Sandbox (experimental, pyrit._code_execution): adapters implement a few hooks;
  the base class enforces shared sessions, deadlines, retries only when nothing
  ran, renewal, idle close, cancellation, reset, quarantine and evidence.
- DockerSandboxClient becomes the example adapter (a call sandbox).
- SandboxToolProvider: run_<runtime> tools, plus file tools where state persists.
- OpenAIResponseTarget: max_tool_rounds, ToolInfrastructureError ends the turn,
  and stop reasons (ToolLoopStop) on the error response.
- SandboxCheckScorer, SandboxRegistry, FakeSandbox and a contract-test kit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Wait for the lock with asyncio.timeout: on Python 3.11, wait_for can drop a
  caller's cancellation at handover, so a caller that gave up would run.
- A refused reset keeps a quarantine; release clears it only when the retried
  close succeeds. Reset and release do nothing more once a sandbox is closed.
- Idle close compares a use counter, not timestamps, which collide within one
  Windows clock tick on Python 3.11 and 3.12.
- Unconfirmed cleanup in an environment sandbox quarantines it, so nothing
  starts beside processes that may still run.
- Adapter results are validated inside the uncertain-failure path, so an
  invalid result closes the session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A model request that fails after a tool round raises again, as before, so
  scenario retries still apply; the continuation stop reason is gone.
- The model sees only that a tool's infrastructure failed; the details stay in
  the error response, which history replay skips.
- Release and close retry a close that could not be confirmed, also after
  close_async, so a closed sandbox doesn't keep a session forever.
- The contract kit checks that an adapter's identifier is static, and waits
  less after its timeout probe.
- Tests: the end-to-end check runs real programs, so its verdict depends on
  what the model's call did; vacuous identity test removed; registry isolated.
- Docs: check isolation (one attempt at a time, no automatic retries, reset
  between attempts), quarantine causes, and release after close.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From the last lifecycle reviews:
- A hook that raises CancelledError by itself, while its task is not being
  cancelled, is an uncertain failure instead of looking like the caller's
  own cancellation.
- Every session whose close was not confirmed stays listed until a close is
  confirmed: a successful reset no longer forgets one, and a second no
  longer overwrites the first. Release and close retry them all.
- A run whose caller gave up never starts: the owned task checks the
  caller's shield before each invocation and open attempt and after an
  open, wakes from a busy backoff at once, and yields before starting so
  eager task factories behave the same.
- Abandoned work is always logged, including a failure that lands as the
  caller gives up and a partial run that stopped early.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings November 9, 2026 07:12

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Reinitialization can discard the old registry and its quarantine before shutdown is confirmed, allowing old and new sandbox objects to access the same environment concurrently.

3 open issues
What changed in this PR

Adds experimental sandbox-backed tool execution to PyRIT, connecting model tool calls with fixed-program checks of their effects. This extends the program-execution scoring work in #3218 and aligns the Responses target’s tool-loop limit with #4021.

Changes:

  • Adds sandbox adapters, shared registration, lifecycle contracts, and adapter-testing utilities.
  • Introduces sandbox tools and bounded Responses tool execution with structured stop reasons.
  • Adds SandboxCheckScorer, execution evidence tracking, documentation, and regression coverage.
File Description
tests/​unit/​setup/​test_reinitialization.py Tests sandbox shutdown during reinitialization.
tests/​unit/​score/​test_sandbox_check_scorer.py Covers check verdicts, evidence, and failures.
tests/​unit/​prompt_target/​target/​test_tool.py Checks validation messages in tool results.
tests/​unit/​prompt_target/​target/​test_sandbox_tool_provider.py Tests sandbox tools and scoring integration.
tests/​unit/​prompt_target/​target/​test_openai_response_target_function_chaining.py Covers round limits and infrastructure stops.
tests/​unit/​common/​test_lazy_package_imports.py Extends execution-layer import checks.
tests/​unit/​_code_execution/​test_sandbox.py Tests sandbox lifecycle and concurrency contracts.
tests/​unit/​_code_execution/​test_sandbox_registry.py Covers registration, identity, and shutdown.
tests/​unit/​_code_execution/​test_sandbox_contract.py Tests adapter contract checks.
tests/​unit/​_code_execution/​test_docker_client.py Covers Docker adaptation and input limits.
tests/​unit/​_code_execution/​local_python_sandbox.py Provides a test-only local execution adapter.
tests/​integration/​score/​test_program_execution_scorer_integration.py Updates cancellation-test timeout configuration.
pyrit/​setup/​initialization.py Includes sandboxes in registry resets.
pyrit/​setup/​configuration_loader.py Closes registered sandboxes before reinitialization.
pyrit/​score/​true_false/​sandbox_check_scorer.py Adds fixed-program sandbox checks.
pyrit/​score/​observation/​program_execution_source.py Records rejected inputs and execution identifiers.
pyrit/​score/​__init__.py Exports the sandbox check scorer lazily.
pyrit/​prompt_target/​openai/​openai_response_target.py Bounds tool rounds and handles infrastructure failures.
pyrit/​prompt_target/​common/​tool_provider.py Defines tool infrastructure errors.
pyrit/​prompt_target/​common/​sandbox_tool_provider.py Provides runtime and persistent-file tools.
pyrit/​prompt_target/​__init__.py Exports sandbox tools and infrastructure errors.
pyrit/​models/​target/​tool_execution_metadata.py Adds structured tool-loop stop metadata.
pyrit/​models/​code_execution.py Adds execution identifiers to sandbox results.
pyrit/​models/​__init__.py Exports tool-loop stop models.
pyrit/​_code_execution/​sandbox_registry.py Shares named sandbox instances across consumers.
pyrit/​_code_execution/​sandbox_contract.py Adds live adapter contract checks.
pyrit/​_code_execution/​fake_sandbox.py Provides a configurable in-memory test adapter.
pyrit/​_code_execution/​docker_client.py Adapts Docker execution to the sandbox interface.
pyrit/​_code_execution/​client.py Defines sandbox errors and stateful-client semantics.
pyrit/​_code_execution/​__init__.py Exports experimental sandbox APIs lazily.
doc/​myst.yml Adds the sandbox guide to navigation.
doc/​code/​targets/​12_sandboxed_tool_calls.md Documents tools, checks, and adapter contracts.
doc/​code/​scoring/​7_program_execution_scorer.py Adds guidance linking to sandbox checks.
doc/​code/​scoring/​7_program_execution_scorer.ipynb Adds matching notebook guidance.
doc/​code/​framework.md Defines sandbox and consumer responsibilities.

Review effort: Balanced

if memory is None:
raise RuntimeError("Live reinitialization requires initialized memory.")
# Initializers register new objects for the same sandboxes, so the old ones must not keep sessions.
await SandboxRegistry.get_registry_singleton().close_all_async()
Comment on lines +242 to +243
except SandboxInputError as error:
return {"error": "SandboxInputError", "message": str(error)}
Comment on lines +118 to +119
self.prepare_expectation(expectation=expectation)
return []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants