|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +import pytest |
| 7 | +from pydantic import ValidationError |
| 8 | + |
| 9 | +from agents import Agent, RunConfig, Runner, UserError |
| 10 | +from agents.sandbox import Manifest |
| 11 | +from agents.sandbox.capabilities.tools import ( |
| 12 | + ExecCommandArgs, |
| 13 | + ExecCommandTool, |
| 14 | + ViewImageTool, |
| 15 | + WriteStdinTool, |
| 16 | +) |
| 17 | +from agents.sandbox.errors import InvalidManifestPathError |
| 18 | +from agents.testing import ScriptedModel, assistant_message, function_call, scripted_sandbox_session |
| 19 | +from tests.testing_processor import SPAN_PROCESSOR_TESTING |
| 20 | + |
| 21 | + |
| 22 | +@pytest.mark.asyncio |
| 23 | +@pytest.mark.parametrize("streamed", [False, True]) |
| 24 | +@pytest.mark.parametrize( |
| 25 | + "tool_type, arguments, expected", |
| 26 | + [ |
| 27 | + ( |
| 28 | + ExecCommandTool, |
| 29 | + {"cmd": "pwd", "workdir": "/outside/private-sentinel"}, |
| 30 | + "Invalid workdir.", |
| 31 | + ), |
| 32 | + (ExecCommandTool, {"cmd": ""}, "Invalid tool arguments for cmd."), |
| 33 | + ( |
| 34 | + ExecCommandTool, |
| 35 | + {"cmd": "private-sentinel", "max_output_tokens": 0}, |
| 36 | + "Invalid tool arguments for max_output_tokens.", |
| 37 | + ), |
| 38 | + (ExecCommandTool, '{"cmd": "private-sentinel"', "Invalid tool arguments."), |
| 39 | + (ViewImageTool, {"path": "/outside/private-sentinel"}, "Invalid path."), |
| 40 | + ( |
| 41 | + ViewImageTool, |
| 42 | + {"path": {"private-sentinel": "value"}}, |
| 43 | + "Invalid tool arguments for path.", |
| 44 | + ), |
| 45 | + (WriteStdinTool, {"chars": "private-sentinel"}, "Invalid tool arguments for session_id."), |
| 46 | + ], |
| 47 | +) |
| 48 | +async def test_invalid_model_input_returns_safe_feedback_without_backend_calls( |
| 49 | + tool_type: type[ExecCommandTool] | type[ViewImageTool] | type[WriteStdinTool], |
| 50 | + arguments: Any, |
| 51 | + expected: str, |
| 52 | + streamed: bool, |
| 53 | + caplog: pytest.LogCaptureFixture, |
| 54 | +) -> None: |
| 55 | + session = scripted_sandbox_session(manifest=Manifest(root="/workspace")) |
| 56 | + tool = tool_type(session=session) |
| 57 | + model = ScriptedModel( |
| 58 | + [ |
| 59 | + [function_call(tool.name, arguments, call_id="bad-input")], |
| 60 | + [assistant_message("recovered")], |
| 61 | + ] |
| 62 | + ) |
| 63 | + agent = Agent(name="test", model=model, tools=[tool]) |
| 64 | + config = RunConfig(trace_include_sensitive_data=False) |
| 65 | + if streamed: |
| 66 | + result = Runner.run_streamed(agent, "go", run_config=config) |
| 67 | + async for _ in result.stream_events(): |
| 68 | + pass |
| 69 | + else: |
| 70 | + result = await Runner.run(agent, "go", run_config=config) |
| 71 | + |
| 72 | + assert result.final_output == "recovered" |
| 73 | + outputs = [item.output for item in result.new_items if item.type == "tool_call_output_item"] |
| 74 | + assert len(outputs) == 1 |
| 75 | + assert str(outputs[0]).startswith(expected) |
| 76 | + assert "private-sentinel" not in str(outputs[0]) |
| 77 | + assert model.calls[1].input[-1]["output"] == outputs[0] |
| 78 | + assert session.calls == () |
| 79 | + model.assert_complete() |
| 80 | + assert "private-sentinel" not in caplog.text |
| 81 | + assert "private-sentinel" not in repr( |
| 82 | + [span.export() for span in SPAN_PROCESSOR_TESTING.get_ordered_spans()] |
| 83 | + ) |
| 84 | + |
| 85 | + |
| 86 | +@pytest.mark.asyncio |
| 87 | +@pytest.mark.parametrize("failure_kind", ["runtime", "path", "validation", "cancel"]) |
| 88 | +async def test_exec_backend_failures_are_not_converted_to_argument_feedback( |
| 89 | + failure_kind: str, |
| 90 | +) -> None: |
| 91 | + failure: BaseException |
| 92 | + if failure_kind == "path": |
| 93 | + failure = InvalidManifestPathError(rel="backend-private", reason="escape_root") |
| 94 | + elif failure_kind == "validation": |
| 95 | + with pytest.raises(ValidationError) as captured: |
| 96 | + ExecCommandArgs(cmd="") |
| 97 | + failure = captured.value |
| 98 | + elif failure_kind == "cancel": |
| 99 | + failure = asyncio.CancelledError() |
| 100 | + else: |
| 101 | + failure = RuntimeError("backend failure") |
| 102 | + |
| 103 | + def fail(_call: Any) -> None: |
| 104 | + raise failure |
| 105 | + |
| 106 | + session = scripted_sandbox_session([{"method": "exec", "responder": fail}]) |
| 107 | + tool = ExecCommandTool(session=session) |
| 108 | + model = ScriptedModel( |
| 109 | + [ |
| 110 | + [function_call(tool.name, {"cmd": "pwd"}, call_id="exec")], |
| 111 | + [assistant_message("done")], |
| 112 | + ] |
| 113 | + ) |
| 114 | + agent = Agent(name="test", model=model, tools=[tool]) |
| 115 | + # Tool-local cancellation is converted by the existing runner, not by input handling. |
| 116 | + if failure_kind == "cancel": |
| 117 | + result = await Runner.run(agent, "go") |
| 118 | + outputs = [item.output for item in result.new_items if item.type == "tool_call_output_item"] |
| 119 | + assert outputs == ["An error occurred while running the tool. Please try again."] |
| 120 | + assert result.final_output == "done" |
| 121 | + else: |
| 122 | + with pytest.raises(UserError) as raised: |
| 123 | + await Runner.run(agent, "go") |
| 124 | + assert raised.value.__cause__ is failure |
| 125 | + assert len(session.calls) == 1 |
| 126 | + session.assert_complete() |
| 127 | + |
| 128 | + |
| 129 | +@pytest.mark.asyncio |
| 130 | +async def test_direct_exec_run_still_raises_for_invalid_workdir() -> None: |
| 131 | + session = scripted_sandbox_session(manifest=Manifest(root="/workspace")) |
| 132 | + with pytest.raises(InvalidManifestPathError): |
| 133 | + await ExecCommandTool(session=session).run(ExecCommandArgs(cmd="pwd", workdir="/outside")) |
| 134 | + assert session.calls == () |
0 commit comments