From 797cc542afef98eeca2175d5ae6d01b0171335db Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Mon, 23 Nov 2026 22:56:07 -0800 Subject: [PATCH 1/6] Choose the model before each Runner request --- .../model_providers/turn_model_selection.py | 58 +++ src/agents/__init__.py | 4 + src/agents/models/multi_provider.py | 49 +- src/agents/run.py | 4 + src/agents/run_config.py | 44 +- src/agents/run_internal/run_loop.py | 15 +- src/agents/run_internal/turn_preparation.py | 68 ++- src/agents/sandbox/runtime.py | 11 + tests/models/test_codex_model_selection.py | 147 ++++++ tests/test_turn_model_selection.py | 445 ++++++++++++++++++ 10 files changed, 802 insertions(+), 43 deletions(-) create mode 100644 examples/model_providers/turn_model_selection.py create mode 100644 tests/models/test_codex_model_selection.py create mode 100644 tests/test_turn_model_selection.py diff --git a/examples/model_providers/turn_model_selection.py b/examples/model_providers/turn_model_selection.py new file mode 100644 index 0000000000..3cfecbefbd --- /dev/null +++ b/examples/model_providers/turn_model_selection.py @@ -0,0 +1,58 @@ +"""Switch models after an SDK tool reports a failed test. + +Run with --base-model NAME --review-model NAME. Add --codex to use an installed +Codex wheel. Both names must be available through the same provider. +""" + +import argparse +import asyncio +from dataclasses import dataclass + +from agents import Agent, ModelSelectionData, RunConfig, RunContextWrapper, Runner +from agents.decorators import tool +from agents.models.codex import CodexProvider + + +@dataclass +class TestJob: + failed: bool = False + + +@tool +def run_tests(ctx: RunContextWrapper[TestJob]) -> str: + """Return a simulated test result for this example.""" + ctx.context.failed = True + return "FAILED test_total: expected 42, got 41" + + +async def main(base_model: str, review_model: str, use_codex: bool) -> None: + def select_model(turn: ModelSelectionData[TestJob]) -> str | None: + if turn.context is not None and turn.context.failed: + return review_model + return None + + agent = Agent[TestJob]( + name="Test reviewer", + model=base_model, + instructions="Call run_tests once. Then explain the reported failure without editing files.", + tools=[run_tests], + ) + config = ( + RunConfig(model_provider=CodexProvider(), model_selector=select_model) + if use_codex + else RunConfig(model_selector=select_model) + ) + try: + result = await Runner.run(agent, "Check the tests.", context=TestJob(), run_config=config) + print(result.final_output) + finally: + await config.model_provider.aclose() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base-model", required=True) + parser.add_argument("--review-model", required=True) + parser.add_argument("--codex", action="store_true") + args = parser.parse_args() + asyncio.run(main(args.base_model, args.review_model, args.codex)) diff --git a/src/agents/__init__.py b/src/agents/__init__.py index ae226a9f56..767b189f4d 100644 --- a/src/agents/__init__.py +++ b/src/agents/__init__.py @@ -115,6 +115,8 @@ retry_policies, ) from .run import ( + ModelSelectionData, + ModelSelector, OutputGuardrailBlockedMessageArgs, OutputGuardrailBlockedMessageFormatter, ReasoningItemIdPolicy, @@ -496,6 +498,8 @@ def enable_verbose_stdout_logging() -> None: "RunResult", "RunResultStreaming", "ResponsesWebSocketSession", + "ModelSelectionData", + "ModelSelector", "RunBudget", "RunBudgetError", "RunConfig", diff --git a/src/agents/models/multi_provider.py b/src/agents/models/multi_provider.py index 9ec55c6dfa..c867b1fc1a 100644 --- a/src/agents/models/multi_provider.py +++ b/src/agents/models/multi_provider.py @@ -187,22 +187,21 @@ def _validate_unknown_prefix_mode(mode: str) -> MultiProviderUnknownPrefixMode: ) return cast(MultiProviderUnknownPrefixMode, mode) - def _get_fallback_provider(self, prefix: str | None) -> ModelProvider: - if prefix is None or prefix == "openai": - return self.openai_provider - elif prefix in self._fallback_providers: + def _get_fallback_provider(self, prefix: str) -> ModelProvider: + if prefix in self._fallback_providers: return self._fallback_providers[prefix] else: self._fallback_providers[prefix] = self._create_fallback_provider(prefix) return self._fallback_providers[prefix] - def _resolve_prefixed_model( - self, - *, - original_model_name: str, - prefix: str, - stripped_model_name: str | None, - ) -> tuple[ModelProvider, str | None]: + def _model_route( + self, original_model_name: str | None + ) -> tuple[ModelProvider | str, str | None]: + """Resolve routing without constructing an optional fallback provider.""" + prefix, stripped_model_name = self._get_prefix_and_model_name(original_model_name) + if prefix is None: + return self.openai_provider, stripped_model_name + # Explicit provider_map entries are the least surprising routing mechanism, so they always # win over the built-in OpenAI alias and unknown-prefix fallback behavior. if ( @@ -212,7 +211,7 @@ def _resolve_prefixed_model( return provider, stripped_model_name if prefix in {"litellm", "any-llm"}: - return self._get_fallback_provider(prefix), stripped_model_name + return prefix, stripped_model_name if prefix == "openai": if self._openai_prefix_mode == "alias": @@ -224,6 +223,15 @@ def _resolve_prefixed_model( raise UserError(f"Unknown prefix: {prefix}") + def _validate_model_selection(self, configured: str | None, selected: str) -> None: + original, _ = self._model_route(configured) + target, _ = self._model_route(selected) + if target is original or (isinstance(target, str) and target == original): + return + raise UserError( + "model_selector cannot switch providers. Choose a model on the same provider." + ) + def get_model(self, model_name: str | None) -> Model: """Returns a Model based on the model name. The model name can have a prefix, ending with a "/", which will be used to look up the ModelProvider. If there is no prefix, we will use @@ -235,20 +243,9 @@ def get_model(self, model_name: str | None) -> Model: Returns: A Model. """ - # Bare model names are always delegated directly to the OpenAI provider. That provider can - # still point at an OpenAI-compatible endpoint via ``base_url``. - if model_name is None: - return self.openai_provider.get_model(None) - - prefix, stripped_model_name = self._get_prefix_and_model_name(model_name) - if prefix is None: - return self.openai_provider.get_model(stripped_model_name) - - provider, resolved_model_name = self._resolve_prefixed_model( - original_model_name=model_name, - prefix=prefix, - stripped_model_name=stripped_model_name, - ) + provider, resolved_model_name = self._model_route(model_name) + if isinstance(provider, str): + provider = self._get_fallback_provider(provider) return provider.get_model(resolved_model_name) async def aclose(self) -> None: diff --git a/src/agents/run.py b/src/agents/run.py index 5c35a7a50a..ea63532d9a 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -60,6 +60,8 @@ CallModelData, CallModelInputFilter, ModelInputData, + ModelSelectionData, + ModelSelector, OutputGuardrailBlockedMessageArgs, OutputGuardrailBlockedMessageFormatter, ReasoningItemIdPolicy, @@ -212,6 +214,8 @@ __all__ = [ "AgentRunner", "Runner", + "ModelSelectionData", + "ModelSelector", "RunConfig", "RunOptions", "RunState", diff --git a/src/agents/run_config.py b/src/agents/run_config.py index b95367ce8b..cbffe72466 100644 --- a/src/agents/run_config.py +++ b/src/agents/run_config.py @@ -68,6 +68,26 @@ class ModelInputData: instructions: str | None +@dataclass(frozen=True) +class ModelSelectionData(Generic[TContext]): + """Information available when choosing the model for one Runner turn.""" + + agent_name: str + """The name of the current agent, including after a handoff.""" + + model_name: str | None + """The agent's configured name, or None for the provider default.""" + + turn_number: int + """The one-based Runner turn. Retries of a request do not start a new turn.""" + + context: TContext | None + """The application's context object for this run.""" + + +ModelSelector = Callable[[ModelSelectionData[Any]], MaybeAwaitable[str | None]] + + @dataclass class CallModelData(Generic[TContext]): """Data passed to `RunConfig.call_model_input_filter` prior to model call.""" @@ -675,6 +695,17 @@ class RunConfig: budget: RunBudget | None = None """Optional limits on root model calls and observed tokens.""" + model_selector: ModelSelector | None = None + """Choose a model by name before each new Runner request, before the input filter. + + Return a name on the same provider route, or None to use the current agent's + configured model for this turn. The callback may be async. It runs once per + request, including after tools and handoffs. Retries reuse that choice. + RunConfig.model and agents with a Model instance bypass selection. + SandboxAgent requires a fixed model. With CodexProvider, selection applies + to the whole request, including any internal Codex calls. + """ + if TYPE_CHECKING: def __init__( @@ -708,17 +739,20 @@ def __init__( ) = None, redact_text: Callable[[str], str] | None = None, budget: RunBudget | dict[str, Any] | None = None, + model_selector: ModelSelector | None = None, ) -> None: ... def __post_init__(self) -> None: - if self.redact_text is not None and ( - not callable(self.redact_text) or inspect.iscoroutinefunction(self.redact_text) - ): - raise TypeError("redact_text must be a synchronous callable or None") if self.budget is not None: self.budget = coerce_dataclass_config( self.budget, RunBudget, parameter_name="run_config.budget" ) + if self.model_selector is not None and not callable(self.model_selector): + raise TypeError("model_selector must be callable or None") + if self.redact_text is not None and ( + not callable(self.redact_text) or inspect.iscoroutinefunction(self.redact_text) + ): + raise TypeError("redact_text must be a synchronous callable or None") if self.tool_name_collision_policy not in ("warn", "error"): raise ValueError("tool_name_collision_policy must be either 'warn' or 'error'") blocked_message = self.output_guardrail_blocked_message @@ -807,6 +841,8 @@ def _coerce_run_config(value: RunConfig | dict[str, Any]) -> RunConfig: "OutputGuardrailBlockedMessageArgs", "OutputGuardrailBlockedMessageFormatter", "ReasoningItemIdPolicy", + "ModelSelectionData", + "ModelSelector", "RunConfig", "RunOptions", "SandboxArchiveLimits", diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index 273dab3c8f..9e5a1c5d2e 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -241,6 +241,7 @@ get_model_settings, get_output_schema, maybe_filter_model_input, + select_model_name, validate_run_hooks, ) from .turn_resolution import ( @@ -2532,10 +2533,13 @@ async def raise_if_input_guardrail_tripwire_known() -> None: if (tool_name := get_tool_trace_name_for_tool(tool)) is not None ] + selected_model_name = await select_model_name( + public_agent, run_config, context_wrapper, streamed_result.current_turn + ) model = ( bindings.resolved_model if bindings.resolved_model is not None - else get_model(execution_agent, run_config) + else get_model(execution_agent, run_config, selected_model_name=selected_model_name) ) if server_conversation_tracker is not None: server_conversation_tracker.validate_model(model) @@ -2544,6 +2548,7 @@ async def raise_if_input_guardrail_tripwire_known() -> None: public_agent, run_config, model, + selected_model_name=selected_model_name, prepared_overrides=bindings.model_settings_overrides, prompt=prompt_config, has_tools=bool(all_tools or handoffs), @@ -2973,6 +2978,9 @@ async def run_single_turn( if (tool_name := get_tool_trace_name_for_tool(tool)) is not None ] + selected_model_name = await select_model_name( + public_agent, run_config, context_wrapper, current_turn + ) output_schema = get_output_schema(execution_agent) if server_conversation_tracker is not None: input = server_conversation_tracker.prepare_input(original_input, generated_items) @@ -2996,6 +3004,7 @@ async def run_single_turn( session_items_to_rewind=session_items_to_rewind, prompt_cache_key_resolver=prompt_cache_key_resolver, defer_llm_end_hooks=True, + selected_model_name=selected_model_name, omitted=omitted, reasoning_item_id_policy=reasoning_item_id_policy, ) @@ -3066,6 +3075,7 @@ async def get_new_response( reasoning_item_id_policy: ReasoningItemIdPolicy | None = None, *, omitted: set[str] | None = None, + selected_model_name: str | None = None, ) -> ModelResponse: """Call the model and return the raw response, handling retries and hooks.""" public_agent = bindings.public_agent @@ -3084,7 +3094,7 @@ async def get_new_response( model = ( bindings.resolved_model if bindings.resolved_model is not None - else get_model(execution_agent, run_config) + else get_model(execution_agent, run_config, selected_model_name=selected_model_name) ) if server_conversation_tracker is not None: server_conversation_tracker.validate_model(model) @@ -3093,6 +3103,7 @@ async def get_new_response( public_agent, run_config, model, + selected_model_name=selected_model_name, prepared_overrides=bindings.model_settings_overrides, prompt=prompt_config, has_tools=bool(all_tools or handoffs), diff --git a/src/agents/run_internal/turn_preparation.py b/src/agents/run_internal/turn_preparation.py index 4fa4fca880..efe13b1a35 100644 --- a/src/agents/run_internal/turn_preparation.py +++ b/src/agents/run_internal/turn_preparation.py @@ -5,6 +5,7 @@ from openai.types.responses.response_prompt_param import ResponsePromptParam +from .._redaction import require_clean from ..agent import Agent from ..agent_output import AgentOutputSchema, AgentOutputSchemaBase from ..exceptions import UserError @@ -14,7 +15,8 @@ from ..model_settings import ModelSettings from ..models.default_models import get_default_model_settings from ..models.interface import Model -from ..run_config import CallModelData, ModelInputData, RunConfig +from ..models.multi_provider import MultiProvider +from ..run_config import CallModelData, ModelInputData, ModelSelectionData, RunConfig from ..run_context import RunContextWrapper, TContext from ..tool import Tool from ..tracing import SpanError @@ -27,6 +29,7 @@ "get_output_schema", "get_handoffs", "get_all_tools", + "select_model_name", "get_model", "get_model_settings", ] @@ -133,22 +136,63 @@ def get_output_schema(agent: Agent[Any]) -> AgentOutputSchemaBase | None: return AgentOutputSchema(agent.output_type) -def get_model(agent: Agent[Any], run_config: RunConfig) -> Model: - """Resolve the model instance for this run.""" - if isinstance(run_config.model, Model): +async def select_model_name( + agent: Agent[TContext], + run_config: RunConfig, + context_wrapper: RunContextWrapper[TContext], + turn_number: int, +) -> str | None: + """Ask only for a new Runner request, never for a retry or approval recovery.""" + selector = run_config.model_selector + if selector is None or run_config.model is not None or isinstance(agent.model, Model): + return None + choice = selector( + ModelSelectionData( + agent_name=agent.name, + model_name=agent.model, + turn_number=turn_number, + context=context_wrapper.context, + ) + ) + name = await choice if inspect.isawaitable(choice) else choice + if name is not None: + if not isinstance(name, str) or not name.strip(): + raise UserError("model_selector must return a non-empty model name or None") + require_clean(name) + return name + + +def _effective_model( + agent: Agent[Any], run_config: RunConfig, selected_model_name: str | None +) -> Model | str | None: + """Use the same selection for provider lookup and implicit model settings.""" + if run_config.model is not None: return run_config.model - elif isinstance(run_config.model, str): - return run_config.model_provider.get_model(run_config.model) - elif isinstance(agent.model, Model): + if isinstance(agent.model, Model) or selected_model_name is None: return agent.model + return selected_model_name - return run_config.model_provider.get_model(agent.model) + +def get_model( + agent: Agent[Any], run_config: RunConfig, *, selected_model_name: str | None = None +) -> Model: + """Resolve the model instance for this request.""" + selection = _effective_model(agent, run_config, selected_model_name) + if isinstance(selection, Model): + return selection + provider = run_config.model_provider + if ( + selected_model_name is not None + and isinstance(provider, MultiProvider) + and not isinstance(agent.model, Model) + ): + provider._validate_model_selection(agent.model, selected_model_name) + return provider.get_model(selection) def _model_settings_for_resolved_name( - agent: Agent[Any], run_config: RunConfig, model: Model + agent: Agent[Any], selection: Model | str | None, model: Model ) -> ModelSettings: - selection = run_config.model if run_config.model is not None else agent.model if getattr(model, "_sandbox_model_capabilities", {}).get("use_provider_defaults"): return model.get_default_model_settings() or ModelSettings() if isinstance(selection, Model): @@ -168,6 +212,7 @@ def get_model_settings( run_config: RunConfig, model: Model, *, + selected_model_name: str | None = None, prepared_overrides: ModelSettings | None = None, prompt: ResponsePromptParam | None = None, has_tools: bool = False, @@ -175,7 +220,8 @@ def get_model_settings( """Resolve model settings, keeping implicit defaults aligned with the resolved model name.""" settings = agent.model_settings if agent._uses_implicit_model_settings(): - settings = _model_settings_for_resolved_name(agent, run_config, model) + selection = _effective_model(agent, run_config, selected_model_name) + settings = _model_settings_for_resolved_name(agent, selection, model) implicit_fields = agent._implicit_request_fields() for override in (prepared_overrides, run_config.model_settings): diff --git a/src/agents/sandbox/runtime.py b/src/agents/sandbox/runtime.py index 128501203b..0676dde7ef 100644 --- a/src/agents/sandbox/runtime.py +++ b/src/agents/sandbox/runtime.py @@ -153,6 +153,17 @@ async def _cleanup_and_store() -> None: def assert_agent_supported(self, agent: Agent[TContext]) -> None: if isinstance(agent, SandboxAgent) and self._sandbox_config is None: raise UserError("SandboxAgent execution requires `RunConfig(sandbox=...)`") + if ( + isinstance(agent, SandboxAgent) + and self._run_config is not None + and self._run_config.model_selector is not None + and self._run_config.model is None + and not isinstance(agent.model, Model) + ): + raise UserError( + "SandboxAgent requires a fixed model for tool preparation. " + "Set RunConfig.model or omit model_selector." + ) async def enqueue_memory_result( self, diff --git a/tests/models/test_codex_model_selection.py b/tests/models/test_codex_model_selection.py new file mode 100644 index 0000000000..157a32e083 --- /dev/null +++ b/tests/models/test_codex_model_selection.py @@ -0,0 +1,147 @@ +import json + +import pytest + +from agents import Agent, ResumableSession, RunConfig, Runner, function_tool +from agents.models._codex_items import native_approval_checkpoint +from agents.models.codex import CodexProvider +from tests.memory.test_resumable_session import MemoryStore + +from .test_codex_pending_approval import ApprovalThread, approval, raw +from .test_codex_provider import FakeThread, native_pair, threads as threads + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True], ids=["run", "streamed"]) +async def test_codex_selects_model_after_failed_sdk_tool(tmp_path, threads, streamed): + queue, _ = threads + context = {"tests_failed": False} + selections = [] + + @function_tool + def run_tests() -> str: + context["tests_failed"] = True + return "Test failed: expected 1, got 2." + + def choose_model(turn): + assert turn.context is context + selections.append((turn.agent_name, turn.model_name, turn.turn_number)) + return "model-b" if turn.context["tests_failed"] else None + + first = FakeThread(call={"callId": "tests", "tool": "run_tests", "arguments": {}}) + second = FakeThread(text="The failing assertion compares 1 with 2.") + queue.extend([first, second]) + agent = Agent(name="test worker", model="model-a", tools=[run_tests]) + provider = CodexProvider(cwd=tmp_path) + config = RunConfig(model_provider=provider, model_selector=choose_model, tracing_disabled=True) + + if streamed: + result = Runner.run_streamed(agent, "Run the tests.", context=context, run_config=config) + async for _ in result.stream_events(): + pass + else: + result = await Runner.run(agent, "Run the tests.", context=context, run_config=config) + + assert result.final_output == "The failing assertion compares 1 with 2." + assert [first.settings["model"], second.settings["model"]] == ["model-a", "model-b"] + assert selections == [("test worker", "model-a", 1), ("test worker", "model-a", 2)] + assert agent.model == "model-a" and config.model is None + assert any( + item.get("type") == "function_call_output" + and item.get("call_id") == "tests" + and "expected 1, got 2" in item["output"] + for item in second.history + ) + assert first.interrupted and first.closed and second.closed + assert not queue + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True], ids=["run", "streamed"]) +@pytest.mark.parametrize("approved", [False, True], ids=["deny", "approve"]) +async def test_codex_approval_restore_keeps_selected_model_until_next_request( + tmp_path, threads, streamed, approved +): + queue, _ = threads + selections = [] + effects = [] + call, _ = native_pair(call_id="pending") + pending_thread = ApprovalThread( + events=[raw(call), approval(), {"type": "raw_response_completed"}] + ) + + def choose_model(turn): + selections.append((turn.agent_name, turn.model_name, turn.turn_number)) + return "model-b" if turn.turn_number == 1 else None + + class RestoredThread(FakeThread): + async def resolve_approval(self, call_json, request_json, preconditions_json): + # Recovery executes the reviewed request before any new selection. + assert selections == [("test worker", "model-a", 1)] + assert self.settings["model"] == "model-b" + effects.append( + ( + json.loads(call_json), + json.loads(request_json), + json.loads(preconditions_json), + ) + ) + return "reviewed command completed" + + recovered_thread = RestoredThread() + final_thread = FakeThread(text="Finished.") + queue.append(pending_thread) + agent = Agent(name="test worker", model="model-a") + store = MemoryStore() + session = await ResumableSession.create(store) + config = RunConfig( + model_provider=CodexProvider(cwd=tmp_path), + model_selector=choose_model, + tracing_disabled=True, + ) + if streamed: + paused = Runner.run_streamed(agent, "Start.", session=session, run_config=config) + async for _ in paused.stream_events(): + pass + else: + paused = await Runner.run(agent, "Start.", session=session, run_config=config) + assert len(paused.interruptions) == 1 + assert pending_thread.settings["model"] == "model-b" + checkpoint = native_approval_checkpoint(paused.interruptions[0].raw_item) + assert checkpoint is not None and checkpoint["model"] == "model-b" + assert selections == [("test worker", "model-a", 1)] + + recovered = await ResumableSession.resume(store, session.session_id) + state = await recovered.load_state(agent) + interruption = state.get_interruptions()[0] + if approved: + state.approve(interruption) + queue.append(recovered_thread) + else: + state.reject(interruption) + queue.append(final_thread) + fresh_config = RunConfig( + model_provider=CodexProvider(cwd=tmp_path), + model_selector=choose_model, + tracing_disabled=True, + ) + if streamed: + result = Runner.run_streamed(agent, state, run_config=fresh_config) + async for _ in result.stream_events(): + pass + else: + result = await Runner.run(agent, state, run_config=fresh_config) + + assert result.final_output == "Finished." + assert selections == [("test worker", "model-a", 1), ("test worker", "model-a", 2)] + assert final_thread.settings["model"] == "model-a" + assert len(effects) == int(approved) + if approved: + assert effects[0] == ( + checkpoint["call"], + checkpoint["request"], + checkpoint["preconditions"], + ) + assert recovered_thread.closed + assert pending_thread.closed and final_thread.closed + assert agent.model == "model-a" and not queue diff --git a/tests/test_turn_model_selection.py b/tests/test_turn_model_selection.py new file mode 100644 index 0000000000..f0c5a69ac7 --- /dev/null +++ b/tests/test_turn_model_selection.py @@ -0,0 +1,445 @@ +from __future__ import annotations + +import asyncio +from typing import Any + +import pytest + +from agents import ( + Agent, + ModelSelectionData, + ModelSettings, + RunBudget, + RunConfig, + Runner, + UserError, + function_tool, +) +from agents.models.interface import Model, ModelProvider +from agents.models.multi_provider import MultiProvider, MultiProviderMap +from agents.retry import ModelRetrySettings +from agents.sandbox import SandboxAgent +from agents.testing import ScriptedModel, assistant_message, function_call, scripted_sandbox_session + + +def test_existing_positional_budget_still_binds_to_budget() -> None: + defaults = RunConfig() + # The original constructor takes the budget immediately after redact_text. + fields = RunConfig.__match_args__ + args: list[Any] = [ + getattr(defaults, name) for name in fields[: fields.index("redact_text") + 1] + ] + budget = RunBudget(max_model_calls=1) + args.append(budget) + config = RunConfig(*args) + assert config.budget is budget + assert config.model_selector is None + + +class RecordingProvider(ModelProvider): + def __init__(self, models: dict[str | None, Model]): + self.models = models + self.selections: list[str | None] = [] + + def get_model(self, model_name: str | None) -> Model: + self.selections.append(model_name) + return self.models[model_name] + + +async def run_agent(streamed: bool, agent: Agent[Any], **kwargs: Any) -> Any: + if streamed: + result = Runner.run_streamed(agent, "start", **kwargs) + async for _ in result.stream_events(): + pass + return result + return await Runner.run(agent, "start", **kwargs) + + +@pytest.mark.parametrize("streamed", [False, True], ids=["awaited", "streamed"]) +async def test_selects_model_after_failed_tool(streamed: bool) -> None: + context = {"failed": False} + + @function_tool + def run_tests() -> str: + context["failed"] = True + return "tests failed" + + model_a = ScriptedModel([[function_call("run_tests", "{}", call_id="tests-1")]]) + model_b = ScriptedModel([[assistant_message("fixed")]]) + provider = RecordingProvider({"A": model_a, "B": model_b}) + agent = Agent(name="worker", model="A", tools=[run_tests]) + seen = [] + + def select(data): + assert isinstance(data, ModelSelectionData) + assert data.context is not None + seen.append((data.agent_name, data.model_name, data.turn_number, data.context)) + return "B" if data.context["failed"] else None + + config = RunConfig(model_provider=provider, model_selector=select, tracing_disabled=True) + result = await run_agent(streamed, agent, context=context, run_config=config) + assert result.final_output == "fixed" + assert provider.selections == ["A", "B"] + assert agent.model == "A" and config.model is None + assert [(name, model, turn) for name, model, turn, _ in seen] == [ + ("worker", "A", 1), + ("worker", "A", 2), + ] + assert all(raw_context is context for _, _, _, raw_context in seen) + assert len(model_a.calls) == len(model_b.calls) == 1 + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_none_restores_agent_name_on_next_turn(streamed: bool) -> None: + @function_tool + def advance() -> str: + return "next" + + model_a = ScriptedModel( + [[function_call("advance", "{}", call_id="first")], [assistant_message("done")]] + ) + model_b = ScriptedModel([[function_call("advance", "{}", call_id="second")]]) + provider = RecordingProvider({"A": model_a, "B": model_b}) + turns = [] + + async def select(data): + turns.append(data.turn_number) + return "B" if data.turn_number == 2 else None + + agent = Agent(name="worker", model="A", tools=[advance]) + result = await run_agent( + streamed, + agent, + run_config=RunConfig(model_provider=provider, model_selector=select, tracing_disabled=True), + ) + assert result.final_output == "done" + assert provider.selections == ["A", "B", "A"] + assert turns == [1, 2, 3] and agent.model == "A" + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("pin", ["run-name", "run-instance", "agent-instance"]) +async def test_explicit_model_bindings_bypass_selector(streamed: bool, pin: str) -> None: + model = ScriptedModel([[assistant_message("pinned")]]) + provider = RecordingProvider({"pinned": model}) + + def select(data): + pytest.fail("An explicit model binding must bypass selection.") + + agent = Agent(name="worker", model=model if pin == "agent-instance" else "A") + config = RunConfig( + model="pinned" if pin == "run-name" else model if pin == "run-instance" else None, + model_provider=provider, + model_selector=select, + tracing_disabled=True, + ) + result = await run_agent(streamed, agent, run_config=config) + assert result.final_output == "pinned" + assert provider.selections == (["pinned"] if pin == "run-name" else []) + assert len(model.calls) == 1 + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("explicit_settings", [False, True]) +async def test_selected_name_controls_defaults_without_overriding_settings( + streamed: bool, explicit_settings: bool +) -> None: + model = ScriptedModel([[assistant_message("done")]]) + provider = RecordingProvider({"gpt-5": model}) + agent = Agent( + name="worker", + model="gpt-4.1", + **({"model_settings": ModelSettings(temperature=0.4)} if explicit_settings else {}), + ) + config = RunConfig( + model_provider=provider, + model_selector=lambda data: "gpt-5", + model_settings=ModelSettings(max_tokens=123), + tracing_disabled=True, + ) + result = await run_agent(streamed, agent, run_config=config) + assert result.final_output == "done" and provider.selections == ["gpt-5"] + settings = model.calls[0].model_settings + assert settings.max_tokens == 123 + if explicit_settings: + assert settings.temperature == 0.4 and settings.reasoning is None + else: + assert settings.reasoning is not None and settings.reasoning.effort == "low" + assert agent.model == "gpt-4.1" + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_retry_reuses_selection_and_request(streamed: bool) -> None: + model = ScriptedModel([RuntimeError("transient"), [assistant_message("retried")]]) + provider = RecordingProvider({"B": model}) + turns = [] + + def select(data): + turns.append(data.turn_number) + return "B" + + result = await run_agent( + streamed, + Agent(name="worker", model="A"), + run_config=RunConfig( + model_provider=provider, + model_selector=select, + model_settings=ModelSettings( + retry=ModelRetrySettings( + max_retries=1, backoff={"initial_delay": 0}, policy=lambda ctx: True + ) + ), + tracing_disabled=True, + ), + ) + assert result.final_output == "retried" + assert turns == [1] and provider.selections == ["B"] + assert len(model.calls) == 2 + assert model.calls[0].input == model.calls[1].input + assert model.calls[0].model_settings == model.calls[1].model_settings + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_handoff_selects_for_receiving_agent(streamed: bool) -> None: + first = ScriptedModel([[function_call("transfer_to_destination", "{}", call_id="handoff")]]) + second = ScriptedModel([[assistant_message("destination answer")]]) + provider = RecordingProvider({"A": first, "B": second}) + destination = Agent(name="destination", model="destination-base") + agent = Agent(name="source", model="A", handoffs=[destination]) + seen = [] + + def select(data): + seen.append((data.agent_name, data.model_name, data.turn_number)) + return "B" if data.agent_name == "destination" else None + + result = await run_agent( + streamed, + agent, + run_config=RunConfig(model_provider=provider, model_selector=select, tracing_disabled=True), + ) + assert result.final_output == "destination answer" + assert provider.selections == ["A", "B"] + assert seen == [("source", "A", 1), ("destination", "destination-base", 2)] + assert destination.model == "destination-base" + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_shared_agent_keeps_concurrent_selections_local(streamed: bool) -> None: + agent = Agent(name="shared", model="A") + models = {name: ScriptedModel([[assistant_message(name)]]) for name in ("B", "C")} + provider = RecordingProvider(models) + entered = {name: asyncio.Event() for name in models} + release = {name: asyncio.Event() for name in models} + + async def select(data): + name = data.context["selected"] + assert data.model_name == "A" and data.turn_number == 1 + entered[name].set() + await release[name].wait() + return name + + config = RunConfig(model_provider=provider, model_selector=select, tracing_disabled=True) + tasks = { + name: asyncio.create_task( + run_agent(streamed, agent, context={"selected": name}, run_config=config) + ) + for name in models + } + try: + await asyncio.wait_for(asyncio.gather(*(event.wait() for event in entered.values())), 2) + release["C"].set() + result_c = await asyncio.wait_for(tasks["C"], 2) + assert result_c.final_output == "C" and not tasks["B"].done() + release["B"].set() + assert (await asyncio.wait_for(tasks["B"], 2)).final_output == "B" + finally: + for task in tasks.values(): + task.cancel() + await asyncio.gather(*tasks.values(), return_exceptions=True) + assert provider.selections == ["C", "B"] + assert agent.model == "A" and config.model is None + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("invalid", ["", 42]) +async def test_invalid_selection_fails_before_provider_lookup(streamed: bool, invalid: Any) -> None: + provider = RecordingProvider({}) + with pytest.raises(UserError, match="model_selector|model name|model selection"): + await run_agent( + streamed, + Agent(name="worker", model="A"), + run_config=RunConfig( + model_provider=provider, + model_selector=lambda data: invalid, + tracing_disabled=True, + ), + ) + assert provider.selections == [] + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_selector_failure_never_falls_back(streamed: bool) -> None: + provider = RecordingProvider({}) + failure = RuntimeError("selection failed") + + async def select(data): + raise failure + + with pytest.raises(RuntimeError) as caught: + await run_agent( + streamed, + Agent(name="worker", model="A"), + run_config=RunConfig( + model_provider=provider, model_selector=select, tracing_disabled=True + ), + ) + assert caught.value is failure and provider.selections == [] + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("with_selector", [False, True]) +async def test_selection_precedes_filter_without_reordering_existing_callbacks( + streamed: bool, with_selector: bool +) -> None: + events = [] + model = ScriptedModel([[assistant_message("done")]]) + + class Provider(ModelProvider): + def get_model(self, model_name: str | None) -> Model: + events.append("provider") + return model + + def filter_input(data): + events.append("filter") + return data.model_data + + def select(data): + events.append("selector") + return "B" + + result = await run_agent( + streamed, + Agent(name="worker", model="A"), + run_config=RunConfig( + model_provider=Provider(), + model_selector=select if with_selector else None, + call_model_input_filter=filter_input, + tracing_disabled=True, + ), + ) + assert result.final_output == "done" + existing_order = ["provider", "filter"] if streamed else ["filter", "provider"] + assert events == (["selector"] if with_selector else []) + existing_order + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_dictionary_config_accepts_selector(streamed: bool) -> None: + model = ScriptedModel([[assistant_message("selected")]]) + provider = RecordingProvider({"B": model}) + result = await run_agent( + streamed, + Agent(name="worker", model="A"), + run_config={ + "model_provider": provider, + "model_selector": lambda data: "B", + "tracing_disabled": True, + }, + ) + assert result.final_output == "selected" and provider.selections == ["B"] + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_same_provider_alias_keeps_original_route(streamed: bool) -> None: + model = ScriptedModel([[assistant_message("same provider")]]) + inner = RecordingProvider({"B": model}) + mapping = MultiProviderMap() + mapping.add_provider("primary", inner) + mapping.add_provider("alias", inner) + provider = MultiProvider(provider_map=mapping) + result = await run_agent( + streamed, + Agent(name="worker", model="primary/A"), + run_config=RunConfig( + model_provider=provider, + model_selector=lambda data: "alias/B", + tracing_disabled=True, + ), + ) + assert result.final_output == "same provider" + assert inner.selections == ["B"] and len(model.calls) == 1 + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_provider_switch_fails_before_fallback_construction(streamed: bool) -> None: + # The double detects optional-provider construction before any model can receive data. + class Provider(MultiProvider): + def _create_fallback_provider(self, prefix: str) -> ModelProvider: + pytest.fail("Rejected selection must not construct a fallback provider.") + + with pytest.raises(UserError, match="provider|route"): + await run_agent( + streamed, + Agent(name="worker", model="openai/gpt-4.1"), + run_config=RunConfig( + model_provider=Provider(), + model_selector=lambda data: "litellm/other-model", + tracing_disabled=True, + ), + ) + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("handoff", [False, True]) +async def test_sandbox_selection_fails_before_session_start( + streamed: bool, handoff: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + session = scripted_sandbox_session([]) + + async def unexpected_start(): + pytest.fail("Unsupported model selection must not start the sandbox session.") + + monkeypatch.setattr(session, "start", unexpected_start) + target = SandboxAgent(name="workspace", model="sandbox-base", capabilities=[]) + source = ScriptedModel( + [[function_call("transfer_to_workspace", "{}", call_id="sandbox-handoff")]] + ) + provider = RecordingProvider({"source": source}) + seen = [] + + def select(data): + seen.append(data.agent_name) + return None + + agent = Agent(name="source", model="source", handoffs=[target]) if handoff else target + with pytest.raises(UserError, match="SandboxAgent|sandbox"): + await run_agent( + streamed, + agent, + run_config=RunConfig( + model_provider=provider, + model_selector=select, + sandbox={"session": session}, + tracing_disabled=True, + ), + ) + assert seen == (["source"] if handoff else []) + assert provider.selections == (["source"] if handoff else []) + assert not session.calls and not await session.running() + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_redacted_model_identity_never_reaches_provider(streamed: bool) -> None: + provider = RecordingProvider({}) + with pytest.raises(UserError) as caught: + await run_agent( + streamed, + Agent(name="worker", model="A"), + run_config=RunConfig( + model_provider=provider, + model_selector=lambda _: "private-name", + redact_text=lambda text: text.replace("private-name", "[removed]"), + tracing_disabled=True, + ), + ) + assert provider.selections == [] + assert "private-name" not in str(caught.value) From ee09aa5a4173c8f89a11bd5d16e4caca931d73d6 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Mon, 23 Nov 2026 22:57:00 -0800 Subject: [PATCH 2/6] Send steering input to the next Runner request --- examples/model_providers/mid_run_steering.py | 59 ++ src/agents/__init__.py | 4 + src/agents/run.py | 69 +- src/agents/run_config.py | 12 +- src/agents/run_control.py | 209 +++++ src/agents/run_internal/run_loop.py | 55 +- tests/test_run_control.py | 890 +++++++++++++++++++ 7 files changed, 1279 insertions(+), 19 deletions(-) create mode 100644 examples/model_providers/mid_run_steering.py create mode 100644 src/agents/run_control.py create mode 100644 tests/test_run_control.py diff --git a/examples/model_providers/mid_run_steering.py b/examples/model_providers/mid_run_steering.py new file mode 100644 index 0000000000..c56d1dd28e --- /dev/null +++ b/examples/model_providers/mid_run_steering.py @@ -0,0 +1,59 @@ +"""Send a correction while an SDK tool runs, with either Python or CodexProvider. + +The tool signals when it starts so this example can simulate a user sending a +message from the UI. A real UI can call control.send from its event handler. +""" + +import argparse +import asyncio + +from agents import Agent, RunConfig, RunControl, Runner +from agents.decorators import tool +from agents.models.codex import CodexProvider + + +async def main(use_codex: bool) -> None: + started = asyncio.Event() + release = asyncio.Event() + + @tool + async def run_tests() -> str: + """Return a simulated test result after the user has had time to respond.""" + started.set() + await release.wait() + return "FAILED test_total: expected 42, got 41" + + agent = Agent( + name="Test reviewer", + instructions="Call run_tests once, then respond to the user. Do not edit files.", + tools=[run_tests], + ) + config = RunConfig(model_provider=CodexProvider()) if use_codex else RunConfig() + control = RunControl() + run = asyncio.create_task( + Runner.run(agent, "Run the tests.", run_config=config, control=control) + ) + tool_started = asyncio.create_task(started.wait()) + try: + done, _ = await asyncio.wait((run, tool_started), return_when=asyncio.FIRST_COMPLETED) + if run in done: + print((await run).final_output) + return + receipt = control.send("Explain the failure before proposing a fix.") + release.set() + result = await run + outcome = await receipt.wait() + print(f"Correction: {outcome.status} ({outcome.reason})") + print(result.final_output) + finally: + release.set() + for task in (tool_started, run): + task.cancel() + await asyncio.gather(tool_started, run, return_exceptions=True) + await config.model_provider.aclose() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--codex", action="store_true") + asyncio.run(main(parser.parse_args().codex)) diff --git a/src/agents/__init__.py b/src/agents/__init__.py index 767b189f4d..03f07bd8c5 100644 --- a/src/agents/__init__.py +++ b/src/agents/__init__.py @@ -132,6 +132,7 @@ ) from .run_budget import RunBudget, RunBudgetError from .run_context import AgentHookContext, RunContextWrapper, TContext +from .run_control import RunControl, SteeringOutcome, SteeringReceipt from .run_error_handlers import ( RunErrorData, RunErrorHandler, @@ -503,6 +504,9 @@ def enable_verbose_stdout_logging() -> None: "RunBudget", "RunBudgetError", "RunConfig", + "RunControl", + "SteeringOutcome", + "SteeringReceipt", "OutputGuardrailBlockedMessageArgs", "OutputGuardrailBlockedMessageFormatter", "ToolNameCollisionPolicy", diff --git a/src/agents/run.py b/src/agents/run.py index ea63532d9a..69ca620066 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -3,6 +3,7 @@ import asyncio import contextlib import warnings +from copy import deepcopy from typing import TYPE_CHECKING, Any, cast from uuid import uuid4 @@ -76,6 +77,7 @@ ToolNotFoundBehavior, ) from .run_context import RunContextWrapper, TContext +from .run_control import RunControl, control_scope, current_control from .run_error_handlers import RunErrorHandlers from .run_internal.agent_bindings import bind_public_agent from .run_internal.agent_runner_helpers import ( @@ -314,6 +316,7 @@ async def run( hooks: RunHooks[TContext] | None = None, run_config: RunConfig | dict[str, Any] | None = None, error_handlers: RunErrorHandlers[TContext] | None = None, + control: RunControl | None = None, previous_response_id: str | None = None, auto_previous_response_id: bool = False, conversation_id: str | None = None, @@ -340,6 +343,7 @@ async def run( Only the first agent's input guardrails are run. Args: + control: A fresh input handle for corrections during this run. starting_agent: The starting agent to run. input: The initial input to the agent. You can pass a single string for a user message, or a list of input items. @@ -365,6 +369,7 @@ async def run( other model providers don't write to the Conversation object, so you'll end up having partial conversations stored. session: A session for automatic conversation history management. + control: A fresh handle for sending user text to the next scheduled request. Returns: A run result containing all the inputs, guardrail results and the output of @@ -375,9 +380,7 @@ async def run( runner = DEFAULT_AGENT_RUNNER redacted_error: BaseException | None = None try: - return await runner.run( - starting_agent, - input, + options: RunOptions[TContext] = RunOptions( context=context, max_turns=max_turns, hooks=hooks, @@ -388,6 +391,9 @@ async def run( conversation_id=conversation_id, session=session, ) + if control is not None: + options["control"] = control + return await runner.run(starting_agent, input, **options) except BaseException as error: if not _is_error_data_redacted(error): raise @@ -404,6 +410,8 @@ async def run( auto_previous_response_id = cast(Any, None) conversation_id = None session = cast(Any, None) + options = RunOptions() + control = None runner = cast(Any, None) assert redacted_error is not None _raise_data_redacted_error(redacted_error) @@ -527,6 +535,7 @@ def run_streamed( session: Session | ResumableSession | None = None, *, error_handlers: RunErrorHandlers[TContext] | None = None, + control: RunControl | None = None, ) -> RunResultStreaming: """ Run a workflow starting at the given agent in streaming mode. @@ -552,6 +561,7 @@ def run_streamed( Only the first agent's input guardrails are run. Args: + control: A fresh input handle for corrections during this run. starting_agent: The starting agent to run. input: The initial input to the agent. You can pass a single string for a user message, or a list of input items. @@ -570,6 +580,7 @@ def run_streamed( ``previous_response_id`` is supplied yet. conversation_id: The ID of the stored conversation, if any. session: A session for automatic conversation history management. + control: A fresh handle for sending user text to the next scheduled request. Returns: A result object that contains data about the run, as well as a method to @@ -577,9 +588,7 @@ def run_streamed( """ runner = DEFAULT_AGENT_RUNNER - return runner.run_streamed( - starting_agent, - input, + options: RunOptions[TContext] = RunOptions( context=context, max_turns=max_turns, hooks=hooks, @@ -590,6 +599,9 @@ def run_streamed( conversation_id=conversation_id, session=session, ) + if control is not None: + options["control"] = control + return runner.run_streamed(starting_agent, input, **options) def _prepare_private_input( @@ -650,6 +662,9 @@ async def run( input: str | list[TResponseInputItem] | RunState[TContext], **kwargs: Unpack[RunOptions[TContext]], ) -> RunResult: + control = kwargs.get("control") + if control is not None: + control._reserve() session = prepare_run_session(kwargs.get("session"), input) kwargs["session"] = session run_config, owns_model_provider = _normalize_run_config_for_runner(kwargs.get("run_config")) @@ -657,6 +672,7 @@ async def run( redacted_error: BaseException | None = None # Mask caller tracing before any run-owned preparation or cleanup can execute. with contextlib.ExitStack() as trace_stack: + trace_stack.enter_context(control_scope(control)) trace_stack.enter_context(redaction_scope(run_config.redact_text)) trace_stack.enter_context( operation_tracing_scope(run_config.tracing, run_config.trace_include_sensitive_data) @@ -693,11 +709,15 @@ async def run( ) if isinstance(session, ResumableRun): await session.finish(result) + if control is not None and result.interruptions: + control._end_reason = "approval_pause" return result except BaseException as error: if not _is_error_data_redacted(error): raise _detach_data_redacted_error_traceback(error) + if control is not None: + control._end_reason = "run_failed" redacted_error = error finally: if owns_model_provider: @@ -963,6 +983,10 @@ async def _run_impl( if isinstance(session, ResumableRun): session.bind_state(run_state) + control = current_control() + if control is not None and is_resumed_state: + control._accepting = True + use_task_and_turn_spans = include_task_and_turn_spans(run_config.tracing) current_task_span: Span[TaskSpanData] | None = ( task_span(name=trace_workflow_name) if use_task_and_turn_spans else None @@ -1672,7 +1696,13 @@ def _mark_response_hooks_started() -> None: if run_state._current_step is None: run_state._current_step = NextStepRunAgain() - pending_input = run_state.pending_input + live_input = ( + control._take(current_turn + 1) + if control is not None + and (max_turns is None or current_turn < max_turns) + else [] + ) + pending_input = run_state.pending_input + deepcopy(live_input) if pending_input: pending_guardrails = current_agent.input_guardrails + ( run_config.input_guardrails or [] @@ -1688,6 +1718,9 @@ def _mark_response_hooks_started() -> None: finally: run_state._input_guardrail_results = list(input_guardrail_results) + if live_input and control is not None: + run_state._pending_input.extend(live_input) + control._retained = True admission_items = await admit_pending_input( run_state=run_state, agent=current_agent, @@ -1703,6 +1736,8 @@ def _mark_response_hooks_started() -> None: pending_input_admission_items = [ item for item in admission_items if isinstance(item, InputItem) ] + if control is not None: + control._admitted(pending_input_admission_items) if not run_state._pending_input: run_state._generated_items = list(generated_items) run_state._session_items = list(session_items) @@ -2135,6 +2170,10 @@ def on_tool_error_selected() -> None: run_state._last_processed_response = turn_result.processed_response run_state._current_turn = current_turn run_state._mark_generated_items_merged_with_last_processed() + # The temporary server-acceptance checkpoint protects unfinished + # processing. Once tools finish, replaying it would repeat their work. + if isinstance(turn_result.next_step, (NextStepRunAgain, NextStepHandoff)): + run_state._current_step = NextStepRunAgain() pending_input_admission_items = [] if run_state is not None and turn_result.nested_history_owned_items is not None: run_state._nested_history_owned_session_item_refs = ( @@ -2780,6 +2819,9 @@ def run_streamed( previous_response_id = kwargs.get("previous_response_id") auto_previous_response_id = kwargs.get("auto_previous_response_id", False) conversation_id = kwargs.get("conversation_id") + control = kwargs.get("control") + if control is not None: + control._reserve() session = prepare_run_session(kwargs.get("session"), input) run_config, owns_model_provider = _normalize_run_config_for_runner(run_config) @@ -3035,6 +3077,7 @@ def run_streamed( # Kick off the actual agent loop in the background and return the streamed result object. async def run_loop() -> None: with ( + control_scope(control), redaction_scope(run_config.redact_text), operation_tracing_scope( run_config.tracing, run_config.trace_include_sensitive_data @@ -3085,6 +3128,18 @@ async def run_loop() -> None: sandbox_runtime=sandbox_runtime, ) + if control is not None: + if streamed_result.interruptions: + control._end_reason = "approval_pause" + elif isinstance( + streamed_result._stored_exception, InputGuardrailTripwireTriggered + ): + control._end_reason = "guardrail" + elif streamed_result._stored_exception is not None: + control._end_reason = "run_failed" + elif streamed_result._cancel_mode != "none": + control._end_reason = "cancelled" + # Keep the outer task frame inside the boundary so it cannot retain run payloads. streamed_result.run_loop_task = asyncio.create_task( _await_data_redacted_error_boundary(run_loop) diff --git a/src/agents/run_config.py b/src/agents/run_config.py index cbffe72466..5e2d9bb7df 100644 --- a/src/agents/run_config.py +++ b/src/agents/run_config.py @@ -31,6 +31,7 @@ from .models.multi_provider import MultiProvider from .run_budget import RunBudget from .run_context import TContext +from .run_control import RunControl from .run_error_handlers import RunErrorHandlers from .tracing import TracingConfig from .util._types import MaybeAwaitable @@ -743,16 +744,16 @@ def __init__( ) -> None: ... def __post_init__(self) -> None: - if self.budget is not None: - self.budget = coerce_dataclass_config( - self.budget, RunBudget, parameter_name="run_config.budget" - ) if self.model_selector is not None and not callable(self.model_selector): raise TypeError("model_selector must be callable or None") if self.redact_text is not None and ( not callable(self.redact_text) or inspect.iscoroutinefunction(self.redact_text) ): raise TypeError("redact_text must be a synchronous callable or None") + if self.budget is not None: + self.budget = coerce_dataclass_config( + self.budget, RunBudget, parameter_name="run_config.budget" + ) if self.tool_name_collision_policy not in ("warn", "error"): raise ValueError("tool_name_collision_policy must be either 'warn' or 'error'") blocked_message = self.output_guardrail_blocked_message @@ -799,6 +800,9 @@ def __post_init__(self) -> None: class RunOptions(TypedDict, Generic[TContext]): """Arguments for ``AgentRunner`` methods.""" + control: NotRequired[RunControl | None] + """Optional input handle for one asynchronous run.""" + context: NotRequired[TContext | None] """The context for the run.""" diff --git a/src/agents/run_control.py b/src/agents/run_control.py new file mode 100644 index 0000000000..2ef4fed78b --- /dev/null +++ b/src/agents/run_control.py @@ -0,0 +1,209 @@ +"""Run-local input for an already active asynchronous Runner invocation.""" + +from __future__ import annotations + +import asyncio +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass +from typing import TYPE_CHECKING, Literal +from uuid import uuid4 + +from .exceptions import InputGuardrailTripwireTriggered, UserError + +if TYPE_CHECKING: + from collections.abc import Iterator + + from .items import InputItem, TResponseInputItem + from .run_internal.oai_conversation import OpenAIServerConversationTracker + +__all__ = ["RunControl", "SteeringReceipt", "SteeringOutcome"] + + +@dataclass(frozen=True) +class SteeringOutcome: + """What the SDK could establish about a correction at its target request.""" + + status: Literal["submitted", "not_submitted", "unknown"] + reason: str + turn_number: int | None + retained: bool + """Whether the run admitted or staged the item. It may already be in recoverable history.""" + + +class SteeringReceipt: + """Observe one correction without exposing its text or cancelling the run.""" + + def __init__(self) -> None: + self.id = uuid4().hex + self._future: asyncio.Future[SteeringOutcome] = asyncio.get_running_loop().create_future() + + @property + def status(self) -> Literal["queued", "submitted", "not_submitted", "unknown"]: + return self._future.result().status if self._future.done() else "queued" + + async def wait(self) -> SteeringOutcome: + """Wait for dispatch or the end of the opportunity to dispatch this message.""" + return await asyncio.shield(self._future) + + +class RunControl: + """Send user text to the next scheduled request in one asynchronous run. + + Pass a fresh handle to Runner.run or Runner.run_streamed. Call send on the + run's event loop after the first request starts, or during resumed tool work. + Sending never interrupts a tool, approves an action or starts an extra turn. + The queue is in memory. After an approval pause, use RunState.add_input on + an eligible paused state and a fresh handle for the resumed invocation. + """ + + def __init__(self, *, max_pending: int = 100) -> None: + if max_pending < 1: + raise ValueError("max_pending must be positive") + self._limit = max_pending + self._loop: asyncio.AbstractEventLoop | None = None + self._used = False + self._end_reason = "run_ended" + self._accepting = False + self._pending: list[tuple[str, SteeringReceipt]] = [] + self._batch: list[SteeringReceipt] = [] + self._turn: int | None = None + self._retained = False + self._items: list[InputItem] = [] + self._before: list[TResponseInputItem] = [] + self._targets: list[TResponseInputItem | None] = [] + + def send(self, text: str) -> SteeringReceipt: + """Queue a nonempty user message. Never wait inside the tool that must finish first.""" + if not self._accepting: + raise UserError("RunControl is not accepting input for an active run") + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = None + if loop is not self._loop: + raise UserError("Send input on the run's event loop") + if not isinstance(text, str) or not text.strip(): + raise UserError("RunControl.send requires non-empty user text") + if len(self._pending) >= self._limit: + raise UserError("RunControl input queue is full") + receipt = SteeringReceipt() + self._pending.append((text, receipt)) + return receipt + + def _reserve(self) -> None: + if self._used: + raise UserError("RunControl belongs to a single run. Use a fresh handle.") + self._used = True + + def _take(self, turn: int) -> list[TResponseInputItem]: + from ._redaction import redact_items + from .items import ItemHelpers + + if not self._pending: + return [] + pending, self._pending = self._pending, [] + self._batch = [receipt for _, receipt in pending] + self._turn = turn + items = [item for text, _ in pending for item in ItemHelpers.input_to_new_input_list(text)] + return redact_items(items) + + def _admitted(self, items: list[InputItem]) -> None: + if self._batch: + self._items = items[-len(self._batch) :] + + def _before_filter( + self, + items: list[TResponseInputItem], + tracker: OpenAIServerConversationTracker | None, + ) -> None: + if not self._batch: + return + self._before = list(items) + if tracker is not None: + by_id = { + entry[2]: item + for item in items + if (entry := tracker.prepared_item_sources.get(id(item))) is not None + and entry[0] is item + and entry[2] is not None + } + self._targets = [by_id.get(item.input_id) for item in self._items] + else: + # Live items form the final, ordered suffix of the local conversation. + tail = items[-len(self._items) :] + self._targets = [ + tail[i] if len(tail) == len(self._items) and tail[i] == item.raw_item else None + for i, item in enumerate(self._items) + ] + + def _dispatch(self, items: list[TResponseInputItem]) -> None: + if self._loop is None: + return + self._accepting = True + if not self._batch: + return + original_ids = {id(item) for item in self._before} + final_ids = {id(item) for item in items} + for receipt, target, admitted in zip(self._batch, self._targets, self._items, strict=True): + outcome: SteeringOutcome + if target is not None and id(target) in final_ids and target == admitted.raw_item: + outcome = SteeringOutcome("submitted", "adapter_dispatch", self._turn, True) + elif target is not None and id(target) not in final_ids and final_ids <= original_ids: + outcome = SteeringOutcome("not_submitted", "filtered", self._turn, True) + else: + outcome = SteeringOutcome("unknown", "input_transformed", self._turn, True) + receipt._future.set_result(outcome) + self._clear_batch() + + def _clear_batch(self) -> None: + self._batch.clear() + self._items.clear() + self._before.clear() + self._targets.clear() + self._turn = None + self._retained = False + + def _close(self, reason: str) -> None: + self._accepting = False + for receipt in self._batch: + if not receipt._future.done(): + receipt._future.set_result( + SteeringOutcome("not_submitted", reason, self._turn, self._retained) + ) + for _, receipt in self._pending: + receipt._future.set_result(SteeringOutcome("not_submitted", reason, None, False)) + self._pending.clear() + self._clear_batch() + self._loop = None + + +_current: ContextVar[RunControl | None] = ContextVar("agents_run_control", default=None) + + +def current_control() -> RunControl | None: + return _current.get() + + +@contextmanager +def control_scope(control: RunControl | None) -> Iterator[None]: + # Always mask the parent handle, including when Agent.as_tool starts a nested run. + if control is not None: + control._loop = asyncio.get_running_loop() + token = _current.set(control) + reason = "run_ended" + try: + yield + except InputGuardrailTripwireTriggered: + reason = "guardrail" + raise + except asyncio.CancelledError: + reason = "cancelled" + raise + except BaseException: + reason = "run_failed" + raise + finally: + _current.reset(token) + if control is not None: + control._close(control._end_reason if reason == "run_ended" else reason) diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index 9e5a1c5d2e..5ff62090f2 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -82,6 +82,7 @@ from ..run_budget import _admit from ..run_config import ReasoningItemIdPolicy, RunConfig from ..run_context import AgentHookContext, RunContextWrapper, TContext +from ..run_control import current_control from ..run_error_handlers import RunErrorHandlers from ..run_state import RunState from ..sandbox.runtime import SandboxRuntime @@ -961,6 +962,9 @@ async def start_streaming( sandbox_runtime: SandboxRuntime[TContext] | None = None, ): """Run the streaming loop for a run result.""" + control = current_control() + if control is not None and is_resumed_state: + control._accepting = True streamed_result._stream_started = True if streamed_result._approved_output is not None and session is not None: streamed_result._approved_output.session_id = session.session_id or None @@ -1697,10 +1701,15 @@ def on_resumed_policy_error() -> None: if streamed_result.is_complete: break - if run_state is not None and run_state._pending_input: + live_input = ( + control._take(current_turn + 1) + if control is not None and (max_turns is None or current_turn < max_turns) + else [] + ) + if run_state is not None and (run_state._pending_input or live_input): if run_state._current_step is None: run_state._current_step = NextStepRunAgain() - pending_input = run_state.pending_input + pending_input = run_state.pending_input + deepcopy(live_input) pending_guardrails = current_agent.input_guardrails + ( run_config.input_guardrails or [] ) @@ -1734,6 +1743,9 @@ def on_resumed_policy_error() -> None: store_setting = current_agent.model_settings.resolve( run_config.model_settings ).store + if live_input and control is not None: + run_state._pending_input.extend(live_input) + control._retained = True admission_items = await admit_pending_input( run_state=run_state, agent=current_agent, @@ -1749,6 +1761,8 @@ def on_resumed_policy_error() -> None: pending_input_admission_items = [ item for item in admission_items if isinstance(item, InputItem) ] + if control is not None: + control._admitted(pending_input_admission_items) if not run_state._pending_input: run_state._generated_items = list(streamed_result._model_input_items) run_state._session_items = list(streamed_result.new_items) @@ -2579,6 +2593,9 @@ async def raise_if_input_guardrail_tripwire_known() -> None: reasoning_item_id_policy, ) + control = current_control() + if control is not None: + control._before_filter(input, server_conversation_tracker) filtered = await maybe_filter_model_input( agent=public_agent, run_config=run_config, @@ -2679,9 +2696,22 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: prompt=prompt_config, ) + async def controlled_stream() -> AsyncIterator[TResponseStreamEvent]: + # Defer dispatch until the retry driver actually pulls the stream. + stream = get_model_stream() + assert control is not None + control._dispatch(filtered.input) + try: + async for event in stream: + yield event + finally: + close = getattr(stream, "aclose", None) + if close is not None: + await close() + await _admit(context_wrapper._budget, model, session, streamed_result=streamed_result) retry_stream = stream_response_with_retry( - get_stream=get_model_stream, + get_stream=controlled_stream if control is not None else get_model_stream, preview=( streamed_result._approved_output.for_turn(streamed_result.current_turn, model) if streamed_result._approved_output is not None and current_redactor() is None @@ -3080,6 +3110,9 @@ async def get_new_response( """Call the model and return the raw response, handling retries and hooks.""" public_agent = bindings.public_agent execution_agent = bindings.execution_agent + control = current_control() + if control is not None: + control._before_filter(input, server_conversation_tracker) filtered = await maybe_filter_model_input( agent=public_agent, run_config=run_config, @@ -3185,10 +3218,11 @@ async def rewind_model_request() -> None: ), record_failed_attempt_usage_on_error(context_wrapper.usage) as reported_usage, ): - await _admit(context_wrapper._budget, model, session) - new_response = await get_response_with_retry( - budget=context_wrapper._budget, - get_response=lambda: model.get_response( + + async def request_response() -> ModelResponse: + if control is not None: + control._dispatch(filtered.input) + return await model.get_response( system_instructions=filtered.instructions, input=filtered.input, model_settings=model_settings, @@ -3201,7 +3235,12 @@ async def rewind_model_request() -> None: previous_response_id=previous_response_id, conversation_id=conversation_id, prompt=prompt_config, - ), + ) + + await _admit(context_wrapper._budget, model, session) + new_response = await get_response_with_retry( + budget=context_wrapper._budget, + get_response=request_response, rewind=rewind_model_request, retry_settings=model_settings.retry, reported_usage=reported_usage, diff --git a/tests/test_run_control.py b/tests/test_run_control.py new file mode 100644 index 0000000000..9e225cb7ca --- /dev/null +++ b/tests/test_run_control.py @@ -0,0 +1,890 @@ +"""Public M2 acceptance checks with deterministic request and tool barriers.""" + +from __future__ import annotations + +import asyncio +import copy +from typing import Any + +import pytest + +from agents import ( + Agent, + GuardrailFunctionOutput, + InputGuardrail, + InputGuardrailTripwireTriggered, + MaxTurnsExceeded, + ModelSettings, + RunConfig, + RunContextWrapper, + RunControl, + Runner, + RunState, + UserError, +) +from agents.decorators import tool +from agents.models.interface import ModelProvider +from agents.retry import ModelRetrySettings +from agents.testing import ModelStep, ScriptedModel, assistant_message, function_call +from tests.utils.simple_session import SimpleListSession + +pytestmark = pytest.mark.asyncio + + +async def drive(streamed: bool, agent: Agent[Any], value: Any = "start", **kwargs: Any) -> Any: + kwargs.setdefault("run_config", RunConfig(tracing_disabled=True)) + if not streamed: + return await Runner.run(agent, value, **kwargs) + result = Runner.run_streamed(agent, value, **kwargs) + try: + async for _ in result.stream_events(): + pass + return result + finally: + if not result.is_complete: + result.cancel() + + +async def wait(event: asyncio.Event) -> None: + await asyncio.wait_for(event.wait(), 3) + + +async def finish(task: asyncio.Task[Any], *release: asyncio.Event) -> None: + for event in release: + event.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +def user_text(item: Any) -> str | None: + if not isinstance(item, dict) or item.get("role") != "user": + return None + content = item.get("content") + if isinstance(content, str): + return content + return "".join(part.get("text", "") for part in content or [] if isinstance(part, dict)) + + +def messages(items: list[Any]) -> list[str]: + return [text for item in items if (text := user_text(item)) is not None] + + +def gate_tool(*, terminal: bool = False, approval: bool = False): + entered, release = asyncio.Event(), asyncio.Event() + effects: list[str] = [] + + @tool(needs_approval=approval) + async def work() -> str: + entered.set() + await release.wait() + effects.append("worked") + return "tool-result" + + model = ScriptedModel( + [[function_call("work", "{}", call_id="work-1")], [assistant_message("done")]] + ) + agent = Agent( + name="worker", + model=model, + tools=[work], + tool_use_behavior="stop_on_first_tool" if terminal else "run_llm_again", + ) + return agent, model, entered, release, effects + + +@pytest.mark.parametrize("streamed", [False, True], ids=["awaited", "streamed"]) +async def test_live_input_follows_all_parallel_tools_in_send_order( + streamed: bool, +) -> None: + entered = [asyncio.Event(), asyncio.Event()] + release = [asyncio.Event(), asyncio.Event()] + completed = [asyncio.Event(), asyncio.Event()] + + @tool + async def work(index: int) -> str: + entered[index].set() + await release[index].wait() + completed[index].set() + return f"tool-result-{index}" + + model = ScriptedModel( + [ + [ + function_call("work", '{"index":0}', call_id="zero"), + function_call("work", '{"index":1}', call_id="one"), + ], + [assistant_message("done")], + ] + ) + agent = Agent(name="worker", model=model, tools=[work]) + control = RunControl() + task = asyncio.create_task(drive(streamed, agent, control=control)) + try: + await asyncio.gather(*(wait(event) for event in entered)) + first = control.send("Explain the failure.") + second = control.send("Then suggest a fix.") + assert first.status == second.status == "queued" + release[1].set() + await wait(completed[1]) + assert len(model.calls) == 1 and first.status == second.status == "queued" + release[0].set() + assert (await asyncio.wait_for(task, 3)).final_output == "done" + outcomes = await asyncio.gather(first.wait(), second.wait()) + assert [outcome.status for outcome in outcomes] == ["submitted", "submitted"] + assert [outcome.turn_number for outcome in outcomes] == [2, 2] + payload = model.calls[1].input + assert messages(payload)[-2:] == ["Explain the failure.", "Then suggest a fix."] + output_positions = [ + i for i, item in enumerate(payload) if item.get("type") == "function_call_output" + ] + correction_positions = [ + i for i, item in enumerate(payload) if user_text(item) in messages(payload)[-2:] + ] + assert len(output_positions) == 2 and max(output_positions) < min(correction_positions) + finally: + await finish(task, *release) + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("terminal", [False, True], ids=["max-turns", "terminal-tool"]) +async def test_no_extra_request_for_unused_correction(streamed: bool, terminal: bool) -> None: + agent, model, entered, release, _ = gate_tool(terminal=terminal) + control = RunControl() + task = asyncio.create_task(drive(streamed, agent, control=control, max_turns=1)) + try: + await wait(entered) + receipt = control.send("No extra request.") + release.set() + if terminal: + assert (await asyncio.wait_for(task, 3)).final_output == "tool-result" + else: + with pytest.raises(MaxTurnsExceeded): + await asyncio.wait_for(task, 3) + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert outcome.status == "not_submitted" and outcome.reason + assert outcome.retained is False and len(model.calls) == 1 + with pytest.raises(UserError): + control.send("too late") + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_final_model_response_does_not_start_followup(streamed: bool) -> None: + entered, release = asyncio.Event(), asyncio.Event() + + async def respond(call): + entered.set() + await release.wait() + return [assistant_message("done")] + + model = ScriptedModel([ModelStep.respond(respond)]) + control = RunControl() + task = asyncio.create_task(drive(streamed, Agent(name="final", model=model), control=control)) + try: + await wait(entered) + receipt = control.send("Unused final correction.") + release.set() + assert (await asyncio.wait_for(task, 3)).final_output == "done" + assert (await asyncio.wait_for(receipt.wait(), 3)).status == "not_submitted" + assert len(model.calls) == 1 + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_preopen_late_and_reused_handles_reject(streamed: bool) -> None: + agent, _, entered, release, _ = gate_tool() + control = RunControl() + with pytest.raises(UserError): + control.send("before binding") + task = asyncio.create_task(drive(streamed, agent, control=control)) + try: + with pytest.raises(UserError): + control.send("task has not started") + await wait(entered) + release.set() + await asyncio.wait_for(task, 3) + with pytest.raises(UserError): + control.send("after completion") + with pytest.raises(UserError): + await asyncio.wait_for(drive(streamed, agent, control=control), 3) + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_approval_pause_closes_unused_receipt_without_executing_tool( + streamed: bool, +) -> None: + entered, release = asyncio.Event(), asyncio.Event() + effects = [] + + @tool(needs_approval=True) + def protected() -> str: + effects.append("executed") + return "effect" + + async def pending(call): + entered.set() + await release.wait() + return [function_call("protected", "{}", call_id="protected-1")] + + model = ScriptedModel([ModelStep.respond(pending)]) + agent = Agent(name="approval", model=model, tools=[protected]) + control = RunControl() + task = asyncio.create_task(drive(streamed, agent, control=control)) + try: + await wait(entered) + receipt = control.send("This does not approve the call.") + release.set() + result = await asyncio.wait_for(task, 3) + assert len(result.interruptions) == 1 and effects == [] + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert outcome.status == "not_submitted" and outcome.retained is False + assert len(model.calls) == 1 + with pytest.raises(UserError): + control.send("after pause") + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_parent_correction_never_enters_nested_agent_request( + streamed: bool, +) -> None: + nested_entered, nested_release = asyncio.Event(), asyncio.Event() + + async def child_response(call): + nested_entered.set() + await nested_release.wait() + return [assistant_message("child answer")] + + child_model = ScriptedModel([ModelStep.respond(child_response)]) + child = Agent(name="child", model=child_model) + child_tool = child.as_tool(tool_name="delegate", tool_description="Delegate a question.") + parent_model = ScriptedModel( + [ + [function_call("delegate", '{"input":"child question"}', call_id="delegate-1")], + [assistant_message("parent answer")], + ] + ) + parent = Agent(name="parent", model=parent_model, tools=[child_tool]) + control = RunControl() + task = asyncio.create_task(drive(streamed, parent, control=control)) + try: + await wait(nested_entered) + receipt = control.send("parent correction") + assert receipt.status == "queued" + nested_release.set() + assert (await asyncio.wait_for(task, 3)).final_output == "parent answer" + assert (await receipt.wait()).status == "submitted" + assert "parent correction" not in messages(child_model.calls[0].input) + assert messages(parent_model.calls[1].input)[-1] == "parent correction" + assert len(child_model.calls) == 1 and len(parent_model.calls) == 2 + finally: + await finish(task, nested_release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_queue_overflow_preserves_existing_receipts_and_duplicate_messages( + streamed: bool, +) -> None: + agent, model, entered, release, _ = gate_tool() + control = RunControl(max_pending=2) + task = asyncio.create_task(drive(streamed, agent, control=control)) + try: + await wait(entered) + first, second = control.send("same"), control.send("same") + with pytest.raises(UserError): + control.send("overflow") + release.set() + await asyncio.wait_for(task, 3) + assert (await first.wait()).status == (await second.wait()).status == "submitted" + assert messages(model.calls[1].input).count("same") == 2 + assert "overflow" not in messages(model.calls[1].input) + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_cancelled_receipt_waiter_preserves_other_waiters_and_delivery( + streamed: bool, +) -> None: + agent, model, entered, release, _ = gate_tool() + control = RunControl() + task = asyncio.create_task(drive(streamed, agent, control=control)) + waiter = None + try: + await wait(entered) + receipt = control.send("Keep this occurrence.") + waiting = asyncio.Event() + + async def cancelled_waiter(): + waiting.set() + return await receipt.wait() + + waiter = asyncio.create_task(cancelled_waiter()) + await wait(waiting) + waiter.cancel() + with pytest.raises(asyncio.CancelledError): + await waiter + assert receipt.status == "queued" + release.set() + await asyncio.wait_for(task, 3) + assert (await asyncio.wait_for(receipt.wait(), 3)).status == "submitted" + assert messages(model.calls[1].input).count("Keep this occurrence.") == 1 + finally: + if waiter is not None: + await finish(waiter) + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("mode", ["drop", "copy"], ids=["dropped", "reconstructed"]) +async def test_filter_outcome_tracks_occurrence_instead_of_equal_text( + streamed: bool, mode: str +) -> None: + agent, model, entered, release, _ = gate_tool() + control = RunControl() + + def filter_input(data): + if mode == "drop": + data.model_data.input = [ + item for item in data.model_data.input if user_text(item) != "correction" + ] + else: + data.model_data.input = copy.deepcopy(data.model_data.input) + return data.model_data + + task = asyncio.create_task( + drive( + streamed, + agent, + control=control, + run_config=RunConfig(call_model_input_filter=filter_input, tracing_disabled=True), + ) + ) + try: + await wait(entered) + receipt = control.send("correction") + release.set() + await asyncio.wait_for(task, 3) + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert outcome.status == ("not_submitted" if mode == "drop" else "unknown") + assert ("correction" in messages(model.calls[1].input)) == (mode == "copy") + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_live_guardrail_rejection_prevents_filter_model_and_session_exposure( + streamed: bool, +) -> None: + agent, model, entered, release, _ = gate_tool() + guarded, filter_inputs = [], [] + session = SimpleListSession() + + async def guard(context, current_agent, value): + text = [value] if isinstance(value, str) else messages(value) + guarded.append(text) + return GuardrailFunctionOutput( + output_info=None, tripwire_triggered="blocked correction" in text + ) + + def filter_input(data): + filter_inputs.extend(messages(data.model_data.input)) + return data.model_data + + agent.input_guardrails = [InputGuardrail(guardrail_function=guard, run_in_parallel=True)] + control = RunControl() + task = asyncio.create_task( + drive( + streamed, + agent, + control=control, + session=session, + run_config=RunConfig(call_model_input_filter=filter_input, tracing_disabled=True), + ) + ) + try: + await wait(entered) + receipt = control.send("blocked correction") + release.set() + with pytest.raises(InputGuardrailTripwireTriggered): + await asyncio.wait_for(task, 3) + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert outcome.status == "not_submitted" and outcome.retained is False + assert len(model.calls) == 1 + assert "blocked correction" not in filter_inputs + assert "blocked correction" not in messages(await session.get_items()) + assert any("blocked correction" in batch for batch in guarded) + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_cancelled_run_settles_queued_receipts_and_closes_intake( + streamed: bool, +) -> None: + agent, model, entered, release, effects = gate_tool() + control = RunControl() + task = asyncio.create_task(drive(streamed, agent, control=control)) + try: + await wait(entered) + receipt = control.send("pending cancellation") + task.cancel() + await asyncio.gather(task, return_exceptions=True) + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert outcome.status == "not_submitted" and outcome.reason + assert len(model.calls) == 1 and not effects + with pytest.raises(UserError): + control.send("too late") + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_concurrent_runs_never_exchange_corrections(streamed: bool) -> None: + entered = {name: asyncio.Event() for name in ("left", "right")} + release = {name: asyncio.Event() for name in entered} + + @tool + async def work(ctx: RunContextWrapper[str]) -> str: + entered[ctx.context].set() + await release[ctx.context].wait() + return ctx.context + + payloads = {} + + async def final(call): + context = next( + item["output"] for item in call.input if item.get("type") == "function_call_output" + ) + payloads[context] = messages(call.input) + return [assistant_message(context)] + + model = ScriptedModel( + [ + [function_call("work", "{}", call_id="left-tool")], + [function_call("work", "{}", call_id="right-tool")], + ModelStep.respond(final), + ModelStep.respond(final), + ] + ) + agent = Agent(name="shared", model=model, tools=[work]) + controls = {name: RunControl() for name in entered} + tasks = { + name: asyncio.create_task(drive(streamed, agent, context=name, control=controls[name])) + for name in entered + } + try: + await asyncio.gather(*(wait(event) for event in entered.values())) + receipts = {name: controls[name].send(f"correction-{name}") for name in entered} + release["right"].set() + assert (await asyncio.wait_for(tasks["right"], 3)).final_output == "right" + assert receipts["left"].status == "queued" + release["left"].set() + await asyncio.wait_for(tasks["left"], 3) + for name in entered: + assert (await receipts[name].wait()).status == "submitted" + assert payloads[name] == ["start", f"correction-{name}"] + finally: + await asyncio.gather(*(finish(tasks[name], release[name]) for name in entered)) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_approved_tool_resume_accepts_input_before_tool_finishes( + streamed: bool, +) -> None: + agent, model, entered, release, effects = gate_tool(approval=True) + paused = await drive(streamed, agent) + state = paused.to_state() + state.approve(state.get_interruptions()[0]) + control = RunControl() + task = asyncio.create_task(drive(streamed, agent, state, control=control)) + try: + await wait(entered) + receipt = control.send("Explain before editing again.") + assert receipt.status == "queued" and len(model.calls) == 1 + release.set() + assert (await asyncio.wait_for(task, 3)).final_output == "done" + assert (await receipt.wait()).status == "submitted" + assert effects == ["worked"] + assert messages(model.calls[1].input)[-1] == "Explain before editing again." + assert model.calls[1].input[-2]["type"] == "function_call_output" + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_retry_preserves_submission_and_defers_new_correction( + streamed: bool, +) -> None: + agent, model, entered, release, _ = gate_tool() + retry_entered, retry_release = asyncio.Event(), asyncio.Event() + + async def fail(call): + retry_entered.set() + await retry_release.wait() + raise RuntimeError("transient") + + model = ScriptedModel( + [ + [function_call("work", "{}", call_id="work-1")], + ModelStep.respond(fail), + [assistant_message("done")], + ] + ) + agent.model = model + control = RunControl() + config = RunConfig( + tracing_disabled=True, + model_settings=ModelSettings( + retry=ModelRetrySettings( + max_retries=1, + backoff={"initial_delay": 0}, + policy=lambda _: True, + ) + ), + ) + task = asyncio.create_task(drive(streamed, agent, control=control, run_config=config)) + try: + await wait(entered) + first = control.send("first correction") + release.set() + await wait(retry_entered) + assert first.status == "submitted" + second = control.send("during retry") + retry_release.set() + await asyncio.wait_for(task, 3) + assert (await first.wait()).status == "submitted" + assert (await second.wait()).status == "not_submitted" + assert model.calls[1].input == model.calls[2].input + assert messages(model.calls[2].input).count("first correction") == 1 + assert "during retry" not in messages(model.calls[2].input) + finally: + await finish(task, release, retry_release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_send_after_filter_cutoff_waits_for_later_request(streamed: bool) -> None: + agent, model, entered, release, _ = gate_tool() + filtering, allow_filter = asyncio.Event(), asyncio.Event() + count = 0 + + async def filter_input(data): + nonlocal count + count += 1 + if count == 2: + filtering.set() + await allow_filter.wait() + return data.model_data + + control = RunControl() + task = asyncio.create_task( + drive( + streamed, + agent, + control=control, + run_config=RunConfig(call_model_input_filter=filter_input, tracing_disabled=True), + ) + ) + try: + await wait(entered) + first = control.send("before cutoff") + release.set() + await wait(filtering) + second = control.send("after cutoff") + assert first.status == second.status == "queued" + allow_filter.set() + await asyncio.wait_for(task, 3) + assert (await first.wait()).status == "submitted" + assert (await second.wait()).status == "not_submitted" + assert messages(model.calls[1].input)[-1] == "before cutoff" + assert "after cutoff" not in messages(model.calls[1].input) + finally: + await finish(task, release, allow_filter) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_local_session_retains_one_admitted_occurrence(streamed: bool) -> None: + agent, model, entered, release, _ = gate_tool() + session, control = SimpleListSession(), RunControl() + task = asyncio.create_task(drive(streamed, agent, control=control, session=session)) + try: + await wait(entered) + receipt = control.send("stored correction") + release.set() + await asyncio.wait_for(task, 3) + outcome = await receipt.wait() + assert outcome.status == "submitted" and outcome.retained is True + assert messages(await session.get_items()).count("stored correction") == 1 + model.enqueue([assistant_message("followup")]) + await drive(streamed, agent, "follow up", session=session) + assert messages(model.calls[-1].input).count("stored correction") == 1 + assert messages(await session.get_items()).count("stored correction") == 1 + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("server_managed", [False, True]) +async def test_handoff_keeps_correction_in_same_run_for_destination( + streamed: bool, + server_managed: bool, +) -> None: + entered, release = asyncio.Event(), asyncio.Event() + + async def transfer(call): + entered.set() + await release.wait() + return [function_call("transfer_to_destination", "{}", call_id="handoff")] + + first = ScriptedModel([ModelStep.respond(transfer)]) + second = ScriptedModel([[assistant_message("destination")]]) + destination = Agent(name="destination", model=second) + source = Agent(name="source", model=first, handoffs=[destination]) + control = RunControl() + task = asyncio.create_task( + drive(streamed, source, control=control, auto_previous_response_id=server_managed) + ) + try: + await wait(entered) + receipt = control.send("destination correction") + release.set() + assert (await asyncio.wait_for(task, 3)).final_output == "destination" + outcome = await receipt.wait() + assert outcome.status == "submitted" and outcome.turn_number == 2 + assert messages(second.calls[0].input)[-1] == "destination correction" + assert len(first.calls) == len(second.calls) == 1 + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_redaction_precedes_live_guardrails_filter_and_persistence( + streamed: bool, +) -> None: + agent, model, entered, release, _ = gate_tool() + guard_inputs, filter_inputs = [], [] + + async def guard(context, current_agent, value): + guard_inputs.append(value if isinstance(value, str) else messages(value)) + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=False) + + def filter_input(data): + filter_inputs.extend(messages(data.model_data.input)) + return data.model_data + + session, control = SimpleListSession(), RunControl() + config = RunConfig( + tracing_disabled=True, + redact_text=lambda value: value.replace("synthetic-secret", "[removed]"), + input_guardrails=[InputGuardrail(guardrail_function=guard, run_in_parallel=True)], + call_model_input_filter=filter_input, + ) + task = asyncio.create_task( + drive(streamed, agent, control=control, session=session, run_config=config) + ) + try: + await wait(entered) + receipt = control.send("Explain synthetic-secret") + assert "synthetic-secret" not in repr(receipt) + release.set() + await asyncio.wait_for(task, 3) + outcome = await receipt.wait() + assert outcome.status == "submitted" + assert "synthetic-secret" not in repr(outcome) + assert "synthetic-secret" not in repr(guard_inputs) + assert "Explain [removed]" in filter_inputs + assert "Explain [removed]" in messages(model.calls[1].input) + assert "synthetic-secret" not in repr(await session.get_items()) + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("drop", [False, True], ids=["sent-delta", "filtered-delta"]) +async def test_server_managed_delta_commits_only_sent_live_occurrence( + streamed: bool, drop: bool +) -> None: + agent, _, entered, release, _ = gate_tool() + model = ScriptedModel( + [ + [function_call("work", "{}", call_id="first")], + [function_call("work", "{}", call_id="second")], + [assistant_message("done")], + ] + ) + agent.model = model + filter_calls = 0 + + def filter_input(data): + nonlocal filter_calls + filter_calls += 1 + if drop and filter_calls == 2: + data.model_data.input = [ + item for item in data.model_data.input if user_text(item) != "server correction" + ] + return data.model_data + + control = RunControl() + task = asyncio.create_task( + drive( + streamed, + agent, + control=control, + auto_previous_response_id=True, + run_config=RunConfig(call_model_input_filter=filter_input, tracing_disabled=True), + ) + ) + try: + await wait(entered) + receipt = control.send("server correction") + release.set() + result = await asyncio.wait_for(task, 3) + outcome = await receipt.wait() + assert outcome.status == ("not_submitted" if drop else "submitted") + assert messages(model.calls[1].input).count("server correction") == int(not drop) + assert messages(model.calls[2].input).count("server correction") == int(drop) + assert "start" not in messages(model.calls[1].input) + assert result.to_state().pending_input == [] + assert len(model.calls) == 3 + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_server_filtered_input_survives_approval_state_roundtrip( + streamed: bool, +) -> None: + agent, _, entered, release, effects = gate_tool() + + @tool(needs_approval=True) + def protected() -> str: + effects.append("protected") + return "approved" + + agent.tools.append(protected) + model = ScriptedModel( + [ + [function_call("work", "{}", call_id="first")], + [function_call("protected", "{}", call_id="protected")], + [assistant_message("done")], + ] + ) + agent.model = model + + def omit_correction(data): + data.model_data.input = [ + item for item in data.model_data.input if user_text(item) != "resume correction" + ] + return data.model_data + + control = RunControl() + task = asyncio.create_task( + drive( + streamed, + agent, + control=control, + auto_previous_response_id=True, + run_config=RunConfig(call_model_input_filter=omit_correction, tracing_disabled=True), + ) + ) + try: + await wait(entered) + receipt = control.send("resume correction") + release.set() + paused = await asyncio.wait_for(task, 3) + assert len(paused.interruptions) == 1 and effects == ["worked"] + outcome = await receipt.wait() + assert outcome.status == "not_submitted" and outcome.retained is True + state = await RunState.from_json(agent, paused.to_state().to_json()) + assert messages(state.pending_input) == ["resume correction"] + state.approve(state.get_interruptions()[0]) + resumed = await drive(streamed, agent, state, control=RunControl()) + assert resumed.final_output == "done" and effects == ["worked", "protected"] + assert messages(model.calls[2].input).count("resume correction") == 1 + assert state.pending_input == [] + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_failed_server_request_preserves_dispatch_receipt(streamed: bool) -> None: + agent, _, entered, release, _ = gate_tool() + model = ScriptedModel( + [ + [function_call("work", "{}", call_id="first")], + RuntimeError("request failed"), + ] + ) + agent.model = model + control = RunControl() + task = asyncio.create_task( + drive(streamed, agent, control=control, auto_previous_response_id=True) + ) + try: + await wait(entered) + receipt = control.send("uncertain server acceptance") + release.set() + with pytest.raises(RuntimeError, match="request failed"): + await asyncio.wait_for(task, 3) + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert outcome.status == "submitted" and outcome.turn_number == 2 + assert messages(model.calls[1].input).count("uncertain server acceptance") == 1 + assert len(model.calls) == 2 + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_selector_failure_after_local_save_retains_one_recoverable_occurrence( + streamed: bool, +) -> None: + agent, model, entered, release, _ = gate_tool() + + class Provider(ModelProvider): + def get_model(self, name): + return model + + def select(data): + if data.turn_number == 2: + raise RuntimeError("selector failed") + + agent.model = "configured" + session, control = SimpleListSession(), RunControl() + task = asyncio.create_task( + drive( + streamed, + agent, + control=control, + session=session, + run_config=RunConfig( + model_provider=Provider(), model_selector=select, tracing_disabled=True + ), + ) + ) + try: + await wait(entered) + receipt = control.send("recoverable correction") + release.set() + with pytest.raises(RuntimeError, match="selector failed"): + await asyncio.wait_for(task, 3) + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert outcome.status == "not_submitted" and outcome.retained is True + assert len(model.calls) == 1 + assert messages(await session.get_items()).count("recoverable correction") == 1 + await drive( + streamed, + agent, + "follow up", + session=session, + run_config=RunConfig(model_provider=Provider(), tracing_disabled=True), + ) + assert messages(model.calls[-1].input).count("recoverable correction") == 1 + assert messages(await session.get_items()).count("recoverable correction") == 1 + finally: + await finish(task, release) From 4d93a4a3c6caeb714ea6890a25d6848b413e3f61 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Mon, 23 Nov 2026 23:17:10 -0800 Subject: [PATCH 3/6] Preserve provider routing and output guardrails during model selection --- integration_tests/_contract_surface.py | 6 +- src/agents/models/multi_provider.py | 12 ++- .../run_internal/agent_runner_helpers.py | 13 +++- src/agents/run_internal/run_loop.py | 3 + .../released_api_contract_policy.json | 4 + tests/test_released_api_contract.py | 29 +++++++ tests/test_turn_model_selection.py | 76 ++++++++++++++++++- 7 files changed, 133 insertions(+), 10 deletions(-) diff --git a/integration_tests/_contract_surface.py b/integration_tests/_contract_surface.py index 26067ac728..aa5f2fdb0e 100644 --- a/integration_tests/_contract_surface.py +++ b/integration_tests/_contract_surface.py @@ -10,7 +10,7 @@ import json import sys import typing -from collections.abc import Callable, Iterable, Mapping +from collections.abc import Awaitable, Callable, Iterable, Mapping from importlib.util import find_spec from pathlib import Path from types import FunctionType, ModuleType, UnionType @@ -1056,7 +1056,9 @@ def _type_alias_definition( } if origin is not None: if not isinstance(origin, type) or not ( - origin.__module__ == "agents" or origin.__module__.startswith("agents.") + origin is Awaitable + or origin.__module__ == "agents" + or origin.__module__.startswith("agents.") ): raise TypeError(f"unsupported public generic type alias origin: {origin!r}") return { diff --git a/src/agents/models/multi_provider.py b/src/agents/models/multi_provider.py index c867b1fc1a..42c1e9f6dc 100644 --- a/src/agents/models/multi_provider.py +++ b/src/agents/models/multi_provider.py @@ -223,10 +223,14 @@ def _model_route( raise UserError(f"Unknown prefix: {prefix}") - def _validate_model_selection(self, configured: str | None, selected: str) -> None: - original, _ = self._model_route(configured) - target, _ = self._model_route(selected) - if target is original or (isinstance(target, str) and target == original): + def _validate_model_selection(self, configured: str | None, selected: str | None) -> None: + original, configured_name = self._model_route(configured) + target, selected_name = self._model_route(selected) + if target is original: + if isinstance(original, MultiProvider): + original._validate_model_selection(configured_name, selected_name) + return + if isinstance(original, str) and isinstance(target, str) and target == original: return raise UserError( "model_selector cannot switch providers. Choose a model on the same provider." diff --git a/src/agents/run_internal/agent_runner_helpers.py b/src/agents/run_internal/agent_runner_helpers.py index 0da768da3a..920584fd9b 100644 --- a/src/agents/run_internal/agent_runner_helpers.py +++ b/src/agents/run_internal/agent_runner_helpers.py @@ -15,6 +15,7 @@ from ..guardrail import InputGuardrailResult from ..items import ModelResponse, RunItem, ToolApprovalItem, TResponseInputItem from ..memory import Session +from ..models.interface import Model from ..models.openai_agent_registration import add_openai_harness_id_to_metadata from ..models.openai_chatcompletions import OpenAIChatCompletionsModel from ..result import RunResult @@ -67,6 +68,7 @@ "finalize_conversation_tracking", "get_unsent_tool_call_ids_for_interrupted_state", "input_guardrails_triggered", + "validate_output_guardrails_for_server_model", "validate_output_guardrails_with_server_managed_conversation", "validate_session_conversation_settings", "resolve_trace_settings", @@ -293,9 +295,18 @@ def validate_output_guardrails_with_server_managed_conversation( """Reject an output-guardrail run whose rejected history cannot be locally replaced.""" if conversation_id is None and previous_response_id is None and not auto_previous_response_id: return + validate_output_guardrails_for_server_model(agent, run_config) + + +def validate_output_guardrails_for_server_model( + agent: Agent[Any], run_config: RunConfig, model: Model | None = None +) -> None: + """Check the configured model early and the actual model before each server-managed request.""" if not agent.output_guardrails and not run_config.output_guardrails: return - if isinstance(get_model(agent, run_config), OpenAIChatCompletionsModel): + if model is None: + model = get_model(agent, run_config) + if isinstance(model, OpenAIChatCompletionsModel): # Chat Completions owns its released warn-and-ignore or strict rejection behavior. return raise UserError( diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index 9e5a1c5d2e..16cbf13cf3 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -115,6 +115,7 @@ reject_unrecoverable_terminal_state, snapshot_usage, usage_delta, + validate_output_guardrails_for_server_model, validate_output_guardrails_with_server_managed_conversation, ) from .agent_tool_configuration import guard_agent_tool_configuration @@ -2543,6 +2544,7 @@ async def raise_if_input_guardrail_tripwire_known() -> None: ) if server_conversation_tracker is not None: server_conversation_tracker.validate_model(model) + validate_output_guardrails_for_server_model(public_agent, run_config, model) tool_use_tracker.record_model(model) model_settings = get_model_settings( public_agent, @@ -3098,6 +3100,7 @@ async def get_new_response( ) if server_conversation_tracker is not None: server_conversation_tracker.validate_model(model) + validate_output_guardrails_for_server_model(public_agent, run_config, model) tool_use_tracker.record_model(model) model_settings = get_model_settings( public_agent, diff --git a/tests/fixtures/released_api_contract_policy.json b/tests/fixtures/released_api_contract_policy.json index ea33dbf1ed..b7454b4128 100644 --- a/tests/fixtures/released_api_contract_policy.json +++ b/tests/fixtures/released_api_contract_policy.json @@ -705,6 +705,10 @@ { "module": "agents", "name": "OutputGuardrailBlockedMessageFormatter" + }, + { + "module": "agents", + "name": "ModelSelector" } ], "public_typed_dicts": [ diff --git a/tests/test_released_api_contract.py b/tests/test_released_api_contract.py index 8c9fe0c2a9..36b839bb89 100644 --- a/tests/test_released_api_contract.py +++ b/tests/test_released_api_contract.py @@ -3910,6 +3910,10 @@ def test_repository_release_policy_declares_public_state_surfaces() -> None: "module": "agents", "name": "OutputGuardrailBlockedMessageFormatter", }, + { + "module": "agents", + "name": "ModelSelector", + }, ) type_aliases: dict[tuple[str, str], dict[str, Any]] = { (cast(str, entry["module"]), cast(str, entry["name"])): cast( @@ -3967,6 +3971,31 @@ def test_repository_release_policy_declares_public_state_surfaces() -> None: ], }, } + selector_results = [ + {"identity": "builtins.NoneType", "kind": "type"}, + {"identity": "builtins.str", "kind": "type"}, + ] + assert type_aliases[("agents", "ModelSelector")] == { + "kind": "callable", + "parameters": [ + { + "arguments": [{"kind": "any"}], + "kind": "generic", + "origin": "agents.run_config.ModelSelectionData", + } + ], + "return": { + "kind": "union", + "members": [ + { + "arguments": [{"kind": "union", "members": selector_results}], + "kind": "generic", + "origin": "collections.abc.Awaitable", + }, + *selector_results, + ], + }, + } assert policy.public_typed_dicts == ( { "class_name": "WebSearchToolImageSettings", diff --git a/tests/test_turn_model_selection.py b/tests/test_turn_model_selection.py index f0c5a69ac7..7c1d4fc0b2 100644 --- a/tests/test_turn_model_selection.py +++ b/tests/test_turn_model_selection.py @@ -3,17 +3,23 @@ import asyncio from typing import Any +import httpx import pytest +from openai import AsyncOpenAI from agents import ( Agent, + GuardrailFunctionOutput, ModelSelectionData, ModelSettings, + OpenAIChatCompletionsModel, + OpenAIResponsesModel, RunBudget, RunConfig, Runner, UserError, function_tool, + output_guardrail, ) from agents.models.interface import Model, ModelProvider from agents.models.multi_provider import MultiProvider, MultiProviderMap @@ -349,19 +355,50 @@ async def test_dictionary_config_accepts_selector(streamed: bool) -> None: @pytest.mark.parametrize("streamed", [False, True]) -async def test_same_provider_alias_keeps_original_route(streamed: bool) -> None: +async def test_nested_provider_switch_fails_before_model_lookup(streamed: bool) -> None: + first = RecordingProvider({}) + second = RecordingProvider({"B": ScriptedModel([[assistant_message("wrong provider")]])}) + leaves = MultiProviderMap() + leaves.add_provider("first", first) + leaves.add_provider("second", second) + groups = MultiProviderMap() + groups.add_provider("group", MultiProvider(provider_map=leaves)) + + with pytest.raises(UserError, match="cannot switch providers"): + await run_agent( + streamed, + Agent(name="worker", model="group/first/A"), + run_config=RunConfig( + model_provider=MultiProvider(provider_map=groups), + model_selector=lambda _: "group/second/B", + tracing_disabled=True, + ), + ) + assert first.selections == second.selections == [] + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("nested", [False, True]) +async def test_same_provider_alias_keeps_original_route(streamed: bool, nested: bool) -> None: model = ScriptedModel([[assistant_message("same provider")]]) inner = RecordingProvider({"B": model}) mapping = MultiProviderMap() mapping.add_provider("primary", inner) mapping.add_provider("alias", inner) provider = MultiProvider(provider_map=mapping) + configured, selected = "primary/A", "alias/B" + if nested: + groups = MultiProviderMap() + groups.add_provider("group", provider) + groups.add_provider("other-name", provider) + provider = MultiProvider(provider_map=groups) + configured, selected = f"group/{configured}", f"other-name/{selected}" result = await run_agent( streamed, - Agent(name="worker", model="primary/A"), + Agent(name="worker", model=configured), run_config=RunConfig( model_provider=provider, - model_selector=lambda data: "alias/B", + model_selector=lambda data: selected, tracing_disabled=True, ), ) @@ -369,6 +406,39 @@ async def test_same_provider_alias_keeps_original_route(streamed: bool) -> None: assert inner.selections == ["B"] and len(model.calls) == 1 +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.allow_call_model_methods +async def test_selected_model_cannot_persist_guarded_output(streamed: bool) -> None: + # Use both real adapters so a request reaching the network boundary fails the test. + def unexpected_request(request: httpx.Request) -> httpx.Response: + pytest.fail(f"Guarded output could be stored by {request.url.path}") + + @output_guardrail + def reject_output(context: Any, agent: Agent[Any], output: str) -> GuardrailFunctionOutput: + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=True) + + async with httpx.AsyncClient(transport=httpx.MockTransport(unexpected_request)) as http_client: + client = AsyncOpenAI(api_key="test", http_client=http_client) + provider = RecordingProvider( + { + "chat": OpenAIChatCompletionsModel("chat", client), + "responses": OpenAIResponsesModel("responses", client), + } + ) + with pytest.raises(UserError, match="server-managed conversation history"): + await run_agent( + streamed, + Agent(name="worker", model="chat", output_guardrails=[reject_output]), + conversation_id="conv_test", + run_config=RunConfig( + model_provider=provider, + model_selector=lambda _: "responses", + tracing_disabled=True, + ), + ) + assert provider.selections.count("responses") == 1 + + @pytest.mark.parametrize("streamed", [False, True]) async def test_provider_switch_fails_before_fallback_construction(streamed: bool) -> None: # The double detects optional-provider construction before any model can receive data. From e002fc7d888ce5b19a3fbb015509dfa2af9cfd3b Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Tue, 24 Nov 2026 13:35:28 -0800 Subject: [PATCH 4/6] Keep follow-up approvals tied to their request and honor cancellation --- src/agents/result.py | 2 +- src/agents/run_inbox.py | 6 +- src/agents/run_internal/run_loop.py | 8 + src/agents/run_internal/turn_resolution.py | 2 +- src/agents/run_state.py | 126 +++++++++++--- tests/test_agent_hooks.py | 57 +++++-- tests/test_decisions.py | 10 +- tests/test_run_inbox.py | 183 ++++++++++++++++++++- tests/test_run_state.py | 4 + tests/test_tool_text_transforms.py | 57 ++++++- 10 files changed, 412 insertions(+), 43 deletions(-) diff --git a/src/agents/result.py b/src/agents/result.py index 8dd002fb18..1a8b362cf0 100644 --- a/src/agents/result.py +++ b/src/agents/result.py @@ -497,7 +497,7 @@ def previous_outputs(self) -> tuple[Any, ...]: default_factory=list, init=False, repr=False ) """Pending input preserved when a non-streaming result is converted back to RunState.""" - _task_input_ids_for_state: tuple[str, ...] | None = field( + _task_input_ids_for_state: tuple[str, ...] | Literal["handoff"] | None = field( default=None, init=False, repr=False, compare=False ) _pending_input_ids_for_state: tuple[str, ...] = field( diff --git a/src/agents/run_inbox.py b/src/agents/run_inbox.py index 759bc56bc0..b5fa95bc92 100644 --- a/src/agents/run_inbox.py +++ b/src/agents/run_inbox.py @@ -129,9 +129,9 @@ class RunInbox: For a paused run, use RunState.add_input before resuming with a fresh inbox. Do not wait for a receipt inside a tool that must finish before delivery. - If approval pauses a follow-up that depends on context.turn_input, resume - the RunState in memory. Serialized checkpoints preserve the conversation - but omit the boundary between tasks. + If approval pauses a follow-up, the checkpoint identifies the active task + so guardrails see the same input after resume. It does not save the inbox + or messages still waiting in the queue. Callbacks should propagate CancelledError after cleanup. On Python 3.10, Runner.run cannot detect cancellation if a callback suppresses that exception. diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index abe9e10dae..2fa3ed0c5b 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -3188,6 +3188,10 @@ async def run_single_turn( response_accepted = False if on_response_accepted is not None: response_accepted = on_response_accepted(new_response, None) + # Keep the accepted response and its usage, even if the adapter suppressed cancellation. + inbox = current_inbox() + if inbox is not None: + inbox._check_owner_cancellation() async def after_invocation_validation( _processed_response: ProcessedResponse | None, @@ -3196,6 +3200,8 @@ async def after_invocation_validation( require_clean_run_items(original_input, session_items, _processed_response.new_items) if response_accepted and on_response_accepted is not None: on_response_accepted(new_response, _processed_response) + if inbox is not None: + inbox._check_owner_cancellation() if response_accepted and on_response_hooks_started is not None: on_response_hooks_started() await gather_with_cancel( @@ -3206,6 +3212,8 @@ async def after_invocation_validation( ), hooks.on_llm_end(context_wrapper, public_agent, new_response), ) + if inbox is not None: + inbox._check_owner_cancellation() return response_accepted return await get_single_step_result_from_response( diff --git a/src/agents/run_internal/turn_resolution.py b/src/agents/run_internal/turn_resolution.py index 33e40f629e..9b256780c8 100644 --- a/src/agents/run_internal/turn_resolution.py +++ b/src/agents/run_internal/turn_resolution.py @@ -398,7 +398,7 @@ def _get_turn_input( if run_state is not None and run_state._task_input_ids == (): # The caller withdrew the follow-up. Do not revive the previous task. return [] - if run_state is not None and run_state._task_input_ids: + if run_state is not None and isinstance(run_state._task_input_ids, tuple): # An approval can pause the run before the server accepts the whole # task. Restore its order from pending input and the agent's history. visible: dict[str, TResponseInputItem | None] = dict.fromkeys(run_state._task_input_ids) diff --git a/src/agents/run_state.py b/src/agents/run_state.py index 1c6f6fa452..b5ed0f66d8 100644 --- a/src/agents/run_state.py +++ b/src/agents/run_state.py @@ -266,7 +266,7 @@ def _default_run_state_validation_error( # 3. to_json() always emits CURRENT_SCHEMA_VERSION. # 4. Forward compatibility is intentionally fail-fast (older SDKs reject newer or unsupported # versions). -CURRENT_SCHEMA_VERSION = "1.26" +CURRENT_SCHEMA_VERSION = "1.27" _PROGRAMMATIC_TOOL_CALLING_MIN_SCHEMA_VERSION = "1.13" _HOSTED_MCP_APPROVALS_MIN_SCHEMA_VERSION = "1.14" _CURRENT_RESPONSE_OWNERSHIP_MIN_SCHEMA_VERSION = "1.17" @@ -335,7 +335,11 @@ def _default_run_state_validation_error( ), "1.24": "Requires caller-supplied text redaction when resuming protected RunState snapshots.", "1.25": "Preserves required Runner budgets and consumption across approval resumes.", - "1.26": "Requires an exact text editor when resuming selected tool calls.", + # Replace the unreleased 1.26 writer. It would ignore the active task on resume. + "1.27": ( + "Preserves the active task across approval resumes and requires an exact text " + "editor when resuming selected tool calls." + ), } SUPPORTED_SCHEMA_VERSIONS = frozenset(SCHEMA_VERSION_SUMMARIES) @@ -929,9 +933,10 @@ class RunState(Generic[TContext, TAgent]): _pending_input: list[TResponseInputItem] = field(default_factory=list) """Input staged for admission immediately before the next resumed model call.""" - # None selects the original task. An empty tuple means the caller withdrew + # None selects the original task. "handoff" selects the replacement input + # supplied by a handoff filter. An empty tuple means the caller withdrew # the whole follow-up. The next admitted input becomes its replacement. - _task_input_ids: tuple[str, ...] | None = field( + _task_input_ids: tuple[str, ...] | Literal["handoff"] | None = field( default=None, init=False, repr=False, compare=False ) # Input stays pending until the session saves it or the server acknowledges it. @@ -1083,6 +1088,70 @@ def _restore_task_input(self, context: RunContextWrapper[Any]) -> None: context.turn_input = _get_turn_input(self, self._original_input, self._generated_items) + def _visible_task_input_ids( + self, + ids: set[str], + validation_error_factory: RunStateValidationErrorFactory, + ) -> set[str]: + # A handoff filter may repeat an occurrence. Its ID still identifies one + # task message as long as all visible copies have the same content. + visible: dict[str, InputItem] = {} + for item in self._generated_items: + if not isinstance(item, InputItem) or item.input_id not in ids: + continue + previous = visible.setdefault(item.input_id, item) + if previous is not item and json.dumps( + _serialize_raw_item_value(previous.raw_item), sort_keys=True + ) != json.dumps(_serialize_raw_item_value(item.raw_item), sort_keys=True): + raise validation_error_factory("Invalid active task input references.", UserError) + return set(visible) + + def _task_input_refs(self) -> list[str | int] | Literal["handoff"] | None: + """Reference only input visible to the current agent, without copying its text.""" + if not isinstance(self._task_input_ids, tuple): + return self._task_input_ids + pending = {key: index for index, key in enumerate(self._pending_input_ids)} + visible = self._visible_task_input_ids( + set(self._task_input_ids), _default_run_state_validation_error + ) + refs = [ + pending.get(key, key) + for key in self._task_input_ids + if key in pending or key in visible + ] + # A handoff can replace the entire task with the receiving agent's input. + # An explicitly withdrawn task stays empty instead. + return refs if refs or not self._task_input_ids else "handoff" + + def _restore_task_input_refs( + self, refs: object, validation_error_factory: RunStateValidationErrorFactory + ) -> None: + if refs is None: + return + + def invalid() -> RunStateValidationError: + return validation_error_factory("Invalid active task input references.", UserError) + + if refs == "handoff": + self._task_input_ids = "handoff" + return + if not isinstance(refs, list): + raise invalid() + visible = self._visible_task_input_ids( + {ref for ref in refs if isinstance(ref, str)}, validation_error_factory + ) + ids: list[str] = [] + for ref in refs: + if isinstance(ref, str) and ref and ref in visible: + ids.append(ref) + elif type(ref) is int and 0 <= ref < len(self._pending_input): + ids.append(self._track_pending_input()[ref]) + else: + raise invalid() + if len(ids) != len(set(ids)): + raise invalid() + self._task_input_ids = tuple(ids) + async def _check_pending_specialists( self, root: Agent[Any], context: RunContextWrapper[Any] ) -> bool: @@ -1289,7 +1358,7 @@ def _consume_pending_input(self) -> None: def clear_pending_input(self) -> None: """Remove all input staged for the next resumed model call.""" - if self._task_input_ids and self._pending_input_ids: + if isinstance(self._task_input_ids, tuple) and self._pending_input_ids: withdrawn = set(self._pending_input_ids) self._task_input_ids = tuple( input_id for input_id in self._task_input_ids if input_id not in withdrawn @@ -1695,7 +1764,7 @@ def _serialize_tool_invocations(self) -> dict[str, dict[str, Any]]: "executed": invocation.executed, "completed": invocation.completed, } - # Schema 1.26 retains the requirement, never the editor or selector objects. + # The checkpoint retains the requirement, never the editor or selector objects. if invocation.requires_text_transform and not invocation.completed: record["requires_text_transform"] = True if invocation.input_rewrite is not None: @@ -2253,6 +2322,7 @@ def _serialize_snapshot( "current_agent": current_agent_entry, "original_input": original_input_serialized, "pending_input": self._serialize_input(self._pending_input), + "task_input_refs": self._task_input_refs(), "model_responses": model_responses, "context": context_entry, "tool_use_tracker": copy.deepcopy(self._tool_use_tracker_snapshot), @@ -2856,8 +2926,11 @@ def _validate_pending_approvals( required_children: set[int], *, nested: bool = False, -) -> tuple[bool, bool]: - """Check pending approvals and propagate budget and editor requirements to ancestors.""" +) -> tuple[bool, bool, bool]: + """Propagate the requirements of pending approvals to their ancestors.""" + if state.get("$schemaVersion") == CURRENT_SCHEMA_VERSION and "task_input_refs" not in state: + raise validation_error_factory("Missing active task input references.", UserError) + requires_task = state.get("task_input_refs") is not None context = state.get("context") requires_budget = isinstance(context, dict) and "budget" in context invocations = context.get("tool_invocations") if isinstance(context, dict) else None @@ -2885,26 +2958,32 @@ def _validate_pending_approvals( child = entry.get("agent_run_state") if isinstance(entry, dict) else None if not isinstance(child, dict): continue - budget, editor = _validate_pending_approvals( + budget, editor, task = _validate_pending_approvals( child, validation_error_factory, required_children, nested=True ) - if budget or editor: + if budget or editor or task: # Track the exact child snapshot until its pending run is registered. required_children.add(id(child)) requires_budget |= budget requires_editor |= editor - if requires_budget or requires_editor: + requires_task |= task + # A 1.26 child lacks the marker that would otherwise make its restoration mandatory. + if requires_budget or requires_editor or requires_task or state.get("$schemaVersion") == "1.26": version = _validate_run_state_schema_version( state, validation_error_factory=validation_error_factory ) schema = tuple(map(int, version.split("."))) - if requires_editor and schema < (1, 26): + if requires_task and schema < (1, 27): raise validation_error_factory( - "Tool text transforms require RunState schema 1.26.", UserError + "Active task input requires RunState schema 1.27.", UserError + ) + if requires_editor and schema < (1, 27): + raise validation_error_factory( + "Tool text transforms require RunState schema 1.27.", UserError ) if requires_budget and schema < (1, 25): raise _BudgetCheckpointError("Run budgets require schema 1.25 or later.") - return requires_budget, requires_editor + return requires_budget, requires_editor, requires_task def _validate_run_state_json_value(value: object) -> None: @@ -4897,11 +4976,6 @@ async def _build_run_state_from_json( [dict(item) if isinstance(item, Mapping) else item for item in pending_input_raw], ) state._model_responses = _deserialize_model_responses(state_json.get("model_responses", [])) - state._check_specialist( - initial_agent, - context if context_override is not None else None, - restore_error=validation_error_factory, - ) serialized_generated_items = state_json.get("generated_items", []) state._generated_items, generated_source_indexes = _deserialize_items_with_source_indexes( serialized_generated_items, @@ -4910,6 +4984,15 @@ async def _build_run_state_from_json( validation_error_factory=validation_error_factory, ) + # Authorization checks, including those for nested tools, need the current task. + state._restore_task_input_refs(state_json.get("task_input_refs"), validation_error_factory) + state._restore_task_input(context) + state._check_specialist( + initial_agent, + context if context_override is not None else None, + restore_error=validation_error_factory, + ) + last_processed_response_data = state_json.get("last_processed_response") if last_processed_response_data and state._context is not None: if last_processed_response_data.get("tool_output_guardrail_result_start") is not None and ( @@ -6121,6 +6204,9 @@ def _clone_original_input(original_input: str | list[Any]) -> str | list[Any]: "Start a new run with unique agent names; the saved hook ordering is unavailable." ), "Run state pending_input must be a list", + "Missing active task input references.", + "Invalid active task input references.", + "Active task input requires RunState schema 1.27.", "Run state pending Session write is invalid", "Invalid tool output guardrail result boundary", "Run state tool output guardrail result boundary requires schema 1.20.", @@ -6161,7 +6247,7 @@ def _clone_original_input(original_input: str | list[Any]) -> str | list[Any]: _REQUIRED_CHILD_MISSING, "RunState tool_invocations must be a mapping.", "RunState tool_invocations contains an invalid call ID.", - "Tool text transforms require RunState schema 1.26.", + "Tool text transforms require RunState schema 1.27.", "RunState tool text transform requirement is invalid.", "RunState tool invocation must be a mapping.", "RunState tool invocation contains invalid lifecycle data.", diff --git a/tests/test_agent_hooks.py b/tests/test_agent_hooks.py index ca104d2757..d9b9b47f06 100644 --- a/tests/test_agent_hooks.py +++ b/tests/test_agent_hooks.py @@ -703,13 +703,14 @@ def omit_last_occurrence(data: CallModelData[Any]) -> ModelInputData: @pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("serialize", [False, True], ids=["in-memory", "json"]) @pytest.mark.parametrize( "server_managed,omission", [(False, None), (True, None), (True, "all"), (True, "partial")], ids=["local", "server", "server-withheld", "server-partly-withheld"], ) async def test_follow_up_turn_input_survives_approval_resume( - streamed: bool, server_managed: bool, omission: str | None + streamed: bool, serialize: bool, server_managed: bool, omission: str | None ) -> None: inbox = RunInbox() hooks = AgentHooksWithTurnInput() @@ -754,6 +755,8 @@ async def work() -> str: ) assert len(paused.interruptions) == 1 and not effects state = paused.to_state() + if serialize: + state = await RunState.from_string(agent, state.to_string()) outcomes = [await receipt.wait() for receipt in receipts] if omission: assert [item.get("content") for item in state.pending_input] == task[:1] @@ -881,19 +884,33 @@ def withhold_both(data: CallModelData[Any]) -> ModelInputData: @pytest.mark.parametrize("streamed", [False, True]) -@pytest.mark.parametrize("filtered", [False, True]) -async def test_follow_up_turn_input_respects_handoff_filter(streamed: bool, filtered: bool) -> None: +@pytest.mark.parametrize( + "filter_mode,serialize", + [("none", True), ("replace", True), ("repeat", False), ("repeat", True)], +) +async def test_follow_up_turn_input_respects_handoff_filter( + streamed: bool, filter_mode: str, serialize: bool +) -> None: inbox = RunInbox() hooks = AgentHooksWithTurnInput() - destination = Agent( - name="destination", model=ScriptedModel([[get_text_message("done")]]), hooks=hooks - ) + tool_inputs: list[list[Any]] = [] + + @function_tool(needs_approval=True) + async def work(ctx: RunContextWrapper[Any]) -> str: + tool_inputs.append(list(ctx.turn_input)) + return "done" + + model = ScriptedModel([[get_function_tool_call("work", "{}")], [get_text_message("done")]]) + destination = Agent(name="destination", model=model, hooks=hooks, tools=[work]) def first_answer(call: ModelCall) -> list[Any]: inbox.queue("second task") return [get_text_message("first answer")] def filter_input(data: HandoffInputData) -> HandoffInputData: + if filter_mode == "repeat": + items = data.pre_handoff_items + return data.clone(pre_handoff_items=(*items, items[-1])) return replace(data, input_history="public summary", pre_handoff_items=()) source = Agent( @@ -901,12 +918,32 @@ def filter_input(data: HandoffInputData) -> HandoffInputData: model=ScriptedModel( [ModelStep.respond(first_answer), [get_handoff_tool_call(destination, args="{}")]] ), - handoffs=[handoff(destination, input_filter=filter_input if filtered else None)], + handoffs=[ + handoff(destination, input_filter=None if filter_mode == "none" else filter_input) + ], ) - await _run_with_inbox(source, inbox, streamed) - content = "public summary" if filtered else "second task" + paused = await _run_with_inbox(source, inbox, streamed) + content = "public summary" if filter_mode == "replace" else "second task" expected = [[{"role": "user", "content": content}]] - assert hooks.captured_turn_inputs == hooks.end_inputs == expected + assert hooks.captured_turn_inputs == expected + assert len(paused.interruptions) == 1 and not tool_inputs + state = paused.to_state() + if serialize: + context = RunContextWrapper(context=None) + state = await RunState.from_string(source, state.to_string(), context_override=context) + assert context.turn_input == expected[0] + state.approve(state.get_interruptions()[0]) + resumed = await _run_with_inbox(source, RunInbox(), streamed, value=state) + assert resumed.final_output == "done" + assert tool_inputs == hooks.end_inputs == expected + if filter_mode == "replace": + assert [ + item.get("content") for item in model.calls[-1].input if item.get("role") == "user" + ] == ["public summary"] + elif filter_mode == "repeat": + assert [ + item.get("content") for item in model.calls[-1].input if item.get("role") == "user" + ] == ["first task", "second task", "second task"] @pytest.mark.asyncio diff --git a/tests/test_decisions.py b/tests/test_decisions.py index 4c596d7223..35547cd6e2 100644 --- a/tests/test_decisions.py +++ b/tests/test_decisions.py @@ -717,7 +717,8 @@ def record(ctx: RunContextWrapper[dict[str, str]]) -> str: @pytest.mark.parametrize("stream", [False, True]) @pytest.mark.parametrize("clear_pending", [False, True], ids=["retained", "cleared"]) -async def test_specialist_resume_checks_current_follow_up_input(stream, clear_pending): +@pytest.mark.parametrize("serialized", [False, True]) +async def test_specialist_resume_checks_current_follow_up_input(stream, clear_pending, serialized): inbox = RunInbox() effects = [] @@ -774,6 +775,13 @@ def record() -> str: assert [item.get("content") for item in state.pending_input] == ["include blue"] if clear_pending: state.clear_pending_input() + if serialized: + if clear_pending: + with pytest.raises(UserError, match="specialist unavailable"): + await RunState.from_json(source, state.to_json(), context_override={}) + assert not effects + return + state = await RunState.from_json(source, state.to_json(), context_override={}) state.approve(state.get_interruptions()[0]) if clear_pending: with pytest.raises(UserError, match="specialist unavailable"): diff --git a/tests/test_run_inbox.py b/tests/test_run_inbox.py index bc4b175beb..ea3f5bbd94 100644 --- a/tests/test_run_inbox.py +++ b/tests/test_run_inbox.py @@ -29,11 +29,14 @@ RunState, ToolCallOutputItem, ToolExecutionConfig, + ToolGuardrailFunctionOutput, + ToolInputGuardrailData, ToolsToFinalOutputResult, UserError, function_tool, handoff, output_guardrail, + tool_input_guardrail, ) from agents.decorators import tool from agents.models.interface import ModelProvider @@ -941,10 +944,145 @@ def omit_correction(data): await finish(task, release) +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("serialize", [False, True], ids=["in-memory", "json"]) +async def test_approved_tool_guardrail_checks_follow_up_after_resume( + streamed: bool, serialize: bool +) -> None: + inbox = RunInbox() + checked: list[list[str]] = [] + effects: list[str] = [] + + def first_answer(call): + inbox.queue("Review the private draft.") + return [assistant_message("Public draft reviewed.")] + + @tool_input_guardrail + def check_publication(data: ToolInputGuardrailData) -> ToolGuardrailFunctionOutput: + task = messages(data.context.turn_input) + checked.append(task) + if task == ["Review the public draft."]: + return ToolGuardrailFunctionOutput.allow() + return ToolGuardrailFunctionOutput.reject_content("Publication blocked.") + + @function_tool(needs_approval=True, tool_input_guardrails=[check_publication]) + async def publish() -> str: + effects.append("published") + return "Published." + + model = ScriptedModel( + [ + ModelStep.respond(first_answer), + [function_call("publish", "{}", call_id="publish-draft")], + [assistant_message("Review complete.")], + ] + ) + agent = Agent(name="editor", model=model, tools=[publish]) + paused = await drive(streamed, agent, "Review the public draft.", inbox=inbox) + assert len(paused.interruptions) == 1 + assert checked == effects == [] + state = paused.to_state() + if serialize: + state = await RunState.from_string(agent, state.to_string()) + state.approve(state.get_interruptions()[0]) + await drive(streamed, agent, state) + + assert checked == [["Review the private draft."]] + assert effects == [] + assert model.calls[-1].input[-1]["output"] == "Publication blocked." + + +@pytest.mark.parametrize( + "invalid", + [ + "missing-field-generated", + "missing-field-pending", + "missing-item-id", + "unknown-id", + "ambiguous-id", + "duplicate-id", + "duplicate-position", + "boolean-position", + "negative-position", + "out-of-range-position", + "non-list", + "older-schema", + ], +) +async def test_approval_rejects_invalid_task_input_refs(invalid: str) -> None: + inbox = RunInbox() + effects: list[str] = [] + + def first_answer(call): + inbox.steer("Review the private draft.") + inbox.steer("Do not publish it.") + return [assistant_message("Public draft reviewed.")] + + @function_tool(needs_approval=True) + async def publish() -> str: + effects.append("published") + return "Published." + + model = ScriptedModel() + if invalid != "missing-field-pending": + model.enqueue(ModelStep.respond(first_answer)) + model.enqueue([function_call("publish", "{}", call_id="publish-draft")]) + agent = Agent(name="editor", model=model, tools=[publish]) + paused = await drive(False, agent, "Review the public draft.", inbox=inbox) + state = paused.to_state() + state.approve(state.get_interruptions()[0]) + if invalid != "missing-field-generated": + state.add_input("One more instruction.") + payload = state.to_json() + if invalid.startswith("missing-field"): + payload.pop("task_input_refs", None) + with pytest.raises(UserError): + await RunState.from_json(agent, payload) + assert effects == [] + return + first, second = [ + item["input_id"] for item in payload["generated_items"] if item["type"] == "input_item" + ] + if invalid in {"missing-item-id", "ambiguous-id"}: + for history in ("generated_items", "session_items"): + for item in payload[history]: + if item.get("input_id") == second: + if invalid == "missing-item-id": + del item["input_id"] + else: + item["input_id"] = first + payload["task_input_refs"] = [second if invalid == "missing-item-id" else first] + elif invalid == "older-schema": + payload["$schemaVersion"] = "1.26" + payload.pop("task_input_refs", None) + # The intermediate writer omitted follow-up identity. It cannot resume safely. + with pytest.raises(UserError, match="schema version is not supported"): + await RunState.from_json(agent, payload) + payload["$schemaVersion"] = "1.25" + # The older label alone is valid. It cannot carry a newer task selection. + await RunState.from_json(agent, payload) + payload["task_input_refs"] = [first, second] + else: + payload["task_input_refs"] = { + "unknown-id": ["missing"], + "duplicate-id": [first, first], + "duplicate-position": [0, 0], + "boolean-position": [False], + "negative-position": [-1], + "out-of-range-position": [1], + "non-list": first, + }[invalid] + + with pytest.raises(UserError): + await RunState.from_json(agent, payload) + assert effects == [] + + @pytest.mark.parametrize("resume_streamed", [False, True]) @pytest.mark.parametrize("replace_pending", [False, True], ids=["retained", "replaced"]) +@pytest.mark.parametrize("serialized", [False, True]) async def test_follow_up_survives_session_append_failure( - resume_streamed: bool, replace_pending: bool + resume_streamed: bool, replace_pending: bool, serialized: bool ) -> None: class Session(SimpleListSession): failed = False @@ -994,9 +1132,13 @@ def respond_to_resume(call): assert messages(await session.get_items()) == ["first task"] state = stream.to_state() + if serialized: + state = await RunState.from_string(agent, state.to_string()) assert messages(state.pending_input) == ["second task"] if replace_pending: state.clear_pending_input() + if serialized: + state = await RunState.from_json(agent, state.to_json()) state.add_input("replacement") expected = "replacement" if replace_pending else "second task" @@ -1842,6 +1984,45 @@ async def on_llm_end(self, context, agent, response): ] +@pytest.mark.skipif(not hasattr(asyncio.Task, "cancelling"), reason="Requires Task.cancelling") +async def test_awaited_cancel_prevents_tool_from_late_queued_response() -> None: + inbox = RunInbox() + entered = asyncio.Event() + effects: list[str] = [] + receipts: list[MessageReceipt] = [] + + @tool + async def work() -> str: + effects.append("tool") + return "unexpected" + + def first(call): + receipts.append(inbox.queue("next")) + return [assistant_message("first")] + + async def late_response(call): + entered.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + return [function_call("work", "{}", call_id="late-call")] + + model = ScriptedModel([ModelStep.respond(first), ModelStep.respond(late_response)]) + agent = Agent(name="worker", model=model, tools=[work], tool_use_behavior="stop_on_first_tool") + task = asyncio.create_task( + Runner.run(agent, "start", inbox=inbox, run_config=RunConfig(tracing_disabled=True)) + ) + try: + await wait(entered) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(task, 3) + assert effects == [] + assert (await receipts[0].wait()).status == "submitted" + finally: + await finish(task) + + async def test_immediate_cancel_during_input_filter_never_dispatches() -> None: filtering = asyncio.Event() diff --git a/tests/test_run_state.py b/tests/test_run_state.py index a6a196c907..8baa3ff79c 100644 --- a/tests/test_run_state.py +++ b/tests/test_run_state.py @@ -4506,6 +4506,7 @@ async def test_from_string_normalizes_original_input_dict_items(self): # Create state JSON with original_input containing dict items that should be normalized. state_json = { "$schemaVersion": CURRENT_SCHEMA_VERSION, + "task_input_refs": None, "current_turn": 0, "current_agent": {"name": "TestAgent"}, "original_input": [ @@ -11101,6 +11102,7 @@ async def test_deserialize_items_handles_non_dict_items_in_original_input(self): state_json = { "$schemaVersion": CURRENT_SCHEMA_VERSION, + "task_input_refs": None, "current_turn": 0, "current_agent": {"name": "TestAgent"}, "original_input": [ @@ -11129,6 +11131,7 @@ async def test_from_json_handles_string_original_input(self): state_json = { "$schemaVersion": CURRENT_SCHEMA_VERSION, + "task_input_refs": None, "current_turn": 0, "current_agent": {"name": "TestAgent"}, "original_input": "string_input", # String - tests line 762-763 @@ -11213,6 +11216,7 @@ async def test_from_json_preserves_function_call_output_items(self): state_json = { "$schemaVersion": CURRENT_SCHEMA_VERSION, + "task_input_refs": None, "current_turn": 0, "current_agent": {"name": "TestAgent"}, "original_input": [ diff --git a/tests/test_tool_text_transforms.py b/tests/test_tool_text_transforms.py index 680d7c67af..a157fef704 100644 --- a/tests/test_tool_text_transforms.py +++ b/tests/test_tool_text_transforms.py @@ -940,18 +940,63 @@ async def edit(call, texts): config = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=[(report, edit)])) paused = await Runner.run(agent, "go", run_config=config) snapshot = paused.to_state().to_json() - assert snapshot["$schemaVersion"] == "1.26" + assert snapshot["$schemaVersion"] == "1.27" snapshot["$schemaVersion"] = historical - with pytest.raises(UserError, match="require RunState schema 1.26"): + with pytest.raises(UserError, match="require RunState schema 1.27"): await RunState.from_json(agent, snapshot) del snapshot["context"]["tool_invocations"]["one"]["requires_text_transform"] state = await RunState.from_json(agent, snapshot) - assert not effects and state.to_json()["$schemaVersion"] == "1.26" + assert not effects and state.to_json()["$schemaVersion"] == "1.27" state.approve(state.get_interruptions()[0]) result = await Runner.run(agent, state, run_config=config) assert effects == [True] and RAW not in result.to_state().to_string() +@pytest.mark.asyncio +async def test_invalid_task_reference_cannot_drop_pending_child(): + effects = [] + + @function_tool(needs_approval=True) + def report(): + effects.append("report") + return "done" + + # No editor or budget independently requires this child to be restored. + child = Agent(name="reports", tools=[report], model=model_for("report")) + parent = Agent( + name="parent", + tools=[child.as_tool("delegate", "Delegate", failure_error_function=None)], + model=ScriptedModel( + [ + [function_call("delegate", {"input": "go"}, call_id="parent")], + [assistant_message("done")], + ] + ), + ) + paused = await Runner.run(parent, "go") + snapshot = paused.to_state().to_json() + nested = snapshot["last_processed_response"]["functions"][0]["agent_run_state"] + nested["task_input_refs"] = ["missing-input"] + with pytest.raises(UserError, match="Cannot restore a required pending agent tool"): + await RunState.from_json(parent, snapshot) + assert not effects + + # A 1.26 child has no task references to trigger the required-child check. + snapshot = paused.to_state().to_json() + nested = snapshot["last_processed_response"]["functions"][0]["agent_run_state"] + nested["$schemaVersion"] = "1.26" + del nested["task_input_refs"] + with pytest.raises(UserError, match="schema version is not supported"): + await RunState.from_json(parent, snapshot) + assert not effects + + state = await RunState.from_json(parent, paused.to_state().to_json()) + state.approve(state.get_interruptions()[0]) + result = await Runner.run(parent, state) + assert result.final_output == "done" + assert effects == ["report"] + + @pytest.mark.asyncio async def test_admitted_call_cannot_lose_editor_before_invocation(): @function_tool @@ -1071,12 +1116,12 @@ def configure(settings): if route == "child": snapshot = paused.to_state().to_json() child = snapshot["last_processed_response"]["functions"][0]["agent_run_state"] - assert child["$schemaVersion"] == snapshot["$schemaVersion"] == "1.26" + assert child["$schemaVersion"] == snapshot["$schemaVersion"] == "1.27" for node in (child, snapshot): node["$schemaVersion"] = "1.25" - with pytest.raises(UserError, match="require RunState schema 1.26"): + with pytest.raises(UserError, match="require RunState schema 1.27"): await RunState.from_json(agent, snapshot) - node["$schemaVersion"] = "1.26" + node["$schemaVersion"] = "1.27" assert not effects saved = store.records[session.session_id] From 36fa6e13bd2eca875c2d99837e8539ce7512d7fe Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Tue, 24 Nov 2026 15:48:19 -0800 Subject: [PATCH 5/6] Clarify synchronous steering and preserve task input across handoffs --- examples/model_providers/mid_run_steering.py | 4 +- src/agents/handoffs/history.py | 35 +- src/agents/items.py | 50 +- src/agents/result.py | 21 +- src/agents/run.py | 51 +- src/agents/run_inbox.py | 31 +- src/agents/run_internal/run_loop.py | 104 ++- src/agents/run_internal/turn_resolution.py | 317 +++++++- src/agents/run_state.py | 157 +++- tests/sandbox/test_runtime.py | 264 ++++++- tests/test_agent_hooks.py | 763 ++++++++++++++++++- tests/test_guardrails.py | 11 +- tests/test_run_inbox.py | 154 +++- 13 files changed, 1776 insertions(+), 186 deletions(-) diff --git a/examples/model_providers/mid_run_steering.py b/examples/model_providers/mid_run_steering.py index 2a6bedcc89..1c8b32ec9d 100644 --- a/examples/model_providers/mid_run_steering.py +++ b/examples/model_providers/mid_run_steering.py @@ -55,8 +55,8 @@ async def simulate_ui() -> tuple[MessageReceipt, MessageReceipt]: print(ItemHelpers.text_message_output(event.item)) if search_started.is_set(): steering, follow_up = await ui - print("Steering:", (await steering.wait()).status) - print("Follow-up:", (await follow_up.wait()).status) + print("Steering:", steering.status) + print("Follow-up:", follow_up.status) finally: # The run can finish without calling the search tool. ui.cancel() diff --git a/src/agents/handoffs/history.py b/src/agents/handoffs/history.py index 0692874773..454ffe12be 100644 --- a/src/agents/handoffs/history.py +++ b/src/agents/handoffs/history.py @@ -12,6 +12,8 @@ RunItem, ToolApprovalItem, TResponseInputItem, + _copy_observer, + _CopyObserver, ) if TYPE_CHECKING: @@ -111,11 +113,8 @@ def _nest_handoff_history_with_provenance( ) -> tuple[HandoffInputData, tuple[NestedHistoryOwnedItem, ...]]: """Return nested input and exact provenance for items moved into default history.""" - normalized_history = _normalize_input_history(handoff_input_data.input_history) - flattened_history = [ - _strip_transcript_item_metadata(item) - for item in _flatten_nested_history_messages(normalized_history) - ] + observe = _copy_observer.get() + flattened_history = _flatten_nested_history_messages(handoff_input_data, observe) # Partition items between summary segments and lossless model input while retaining order. normalized_pre_items: list[tuple[TResponseInputItem, bool, RunItem]] = [] @@ -135,6 +134,9 @@ def _nest_handoff_history_with_provenance( normalized_new_items.append((plain_input, forward_verbatim, run_item)) normalized_items = normalized_pre_items + normalized_new_items + if observe is not None: + for plain_input, _, run_item in normalized_items: + observe(run_item, plain_input) owned_items: list[NestedHistoryOwnedItem] = [] if history_mapper is not None: @@ -147,6 +149,9 @@ def _nest_handoff_history_with_provenance( ) copied_history = [deepcopy(item) for item in history_items] + if observe is not None: + for source, target in zip(history_items, copied_history, strict=True): + observe(source, target) owned_items = [ replace( owned_item, @@ -464,15 +469,27 @@ def _stringify_content(content: Any) -> str: def _flatten_nested_history_messages( - items: list[TResponseInputItem], + data: HandoffInputData, + observe: _CopyObserver | None, ) -> list[TResponseInputItem]: flattened: list[TResponseInputItem] = [] - for item in items: + history = data.input_history + # A bare string cannot identify an occurrence without its surrounding inputs. + sources = (data,) if isinstance(history, str) else history + for source, item in zip(sources, _normalize_input_history(history), strict=True): nested_transcript = _extract_nested_history_transcript(item) if nested_transcript is not None: - flattened.extend(nested_transcript) + # A user quote recovered from an assistant summary is history. + for message in nested_transcript: + cleaned = _strip_transcript_item_metadata(message) + if observe is not None: + observe(None, cleaned) + flattened.append(cleaned) continue - flattened.append(deepcopy(item)) + cleaned = _strip_transcript_item_metadata(deepcopy(item)) + if observe is not None: + observe(source, cleaned) + flattened.append(cleaned) return flattened diff --git a/src/agents/items.py b/src/agents/items.py index a55e8f0bb6..c739f4171e 100644 --- a/src/agents/items.py +++ b/src/agents/items.py @@ -3,7 +3,9 @@ import abc import json import weakref -from collections.abc import Mapping +from collections.abc import Callable, Iterator, Mapping +from contextlib import contextmanager +from contextvars import ContextVar from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Generic, Literal, TypeAlias, TypeVar, cast from uuid import uuid4 @@ -73,6 +75,30 @@ if TYPE_CHECKING: from .agent import Agent +# A handoff filter can convert a message before editing or moving it. Record +# these copies at the conversion boundary without adding fields to model input. +_CopyObserver = Callable[[object, object], None] +_copy_observer: ContextVar[_CopyObserver | None] = ContextVar( + "handoff_input_copy_observer", default=None +) + + +@contextmanager +def _observe_input_copies(observer: _CopyObserver | None) -> Iterator[None]: + def notify(source: object, target: object) -> None: + if observer is not None: + observer(source, target) + + token = _copy_observer.set(notify if observer is not None else None) + try: + yield + finally: + # Child tasks may have inherited the callback. Release the messages + # and stop accepting copies as soon as the filter returns. + observer = None + _copy_observer.reset(token) + + TResponse = Response """A type alias for the Response type from the OpenAI SDK.""" @@ -150,7 +176,10 @@ def _get_agent_via_weakref(self, attr_name: str, ref_name: str) -> Any: def to_input_item(self) -> TResponseInputItem: """Converts this item into an input item suitable for passing to the model.""" - return _output_item_to_input_item(self.raw_item) + result = _output_item_to_input_item(self.raw_item) + if (observe := _copy_observer.get()) is not None: + observe(self, result) + return result @dataclass @@ -814,14 +843,17 @@ def input_to_new_input_list( cls, input: str | list[TResponseInputItem] ) -> list[TResponseInputItem]: """Converts a string or list of input items into a list of input items.""" + observe = _copy_observer.get() if isinstance(input, str): - return [ - { - "content": input, - "role": "user", - } - ] - return cast(list[TResponseInputItem], _to_dump_compatible(input)) + message: TResponseInputItem = {"content": input, "role": "user"} + if observe is not None: + observe(input, message) + return [message] + result = cast(list[TResponseInputItem], _to_dump_compatible(input)) + if observe is not None: + for source, target in zip(input, result, strict=True): + observe(source, target) + return result @classmethod def text_message_outputs(cls, items: list[RunItem]) -> str: diff --git a/src/agents/result.py b/src/agents/result.py index 1a8b362cf0..fadd2952d8 100644 --- a/src/agents/result.py +++ b/src/agents/result.py @@ -55,7 +55,7 @@ ProcessedResponse, QueueCompleteSentinel, ) -from .run_state import RunState, _PendingSessionWrite +from .run_state import RunState, _PendingSessionWrite, _TaskInputRefs from .stream_events import ApprovedText, RunCompleted, StreamEvent from .tool_guardrails import ToolInputGuardrailResult, ToolOutputGuardrailResult from .tracing import Trace @@ -497,7 +497,7 @@ def previous_outputs(self) -> tuple[Any, ...]: default_factory=list, init=False, repr=False ) """Pending input preserved when a non-streaming result is converted back to RunState.""" - _task_input_ids_for_state: tuple[str, ...] | Literal["handoff"] | None = field( + _task_input_ids_for_state: _TaskInputRefs = field( default=None, init=False, repr=False, compare=False ) _pending_input_ids_for_state: tuple[str, ...] = field( @@ -1043,8 +1043,12 @@ def run_loop_exception(self) -> BaseException | None: def steer(self, text: str) -> MessageReceipt: """Guide this task after the current model request and its tools finish. - If the model has already answered, Runner continues with the new input. - Call on the run's event loop. This never interrupts a tool or a Codex request. + Call ``receipt = result.steer(text)`` on the run's event loop without ``await``. + This queues the message immediately, without interrupting a tool or a Codex + request. If the model has already answered, Runner continues with the new input. + + Keep consuming ``stream_events()``. Check ``receipt.status`` for the submission + status, or use ``await receipt.wait()`` in a separate task for the full outcome. """ if self._inbox is None: raise UserError("This result has no active run") @@ -1053,8 +1057,13 @@ def steer(self, text: str) -> MessageReceipt: def queue(self, text: str) -> MessageReceipt: """Run a follow-up after this task finishes successfully. - Follow-ups run one at a time in the same conversation and share the run's limits. - Keep consuming stream_events() until the last answer. + Call ``receipt = result.queue(text)`` on the run's event loop without ``await``. + This queues the follow-up immediately. Follow-ups run one at a time in the + same conversation and share the run's limits. + + Keep consuming ``stream_events()`` until the last answer. Check ``receipt.status`` + for the submission status, or use ``await receipt.wait()`` in a separate task + for the full outcome. """ if self._inbox is None: raise UserError("This result has no active run") diff --git a/src/agents/run.py b/src/agents/run.py index bbef9c8eff..3eca7a996a 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -84,7 +84,6 @@ from .run_context import RunContextWrapper, TContext from .run_error_handlers import RunErrorHandlers from .run_inbox import RunInbox, current_inbox, inbox_scope, stop_inbox_intake -from .run_internal.agent_bindings import bind_public_agent from .run_internal.agent_runner_helpers import ( append_model_response_if_new, apply_resumed_conversation_settings, @@ -136,7 +135,6 @@ copy_input_items, ensure_nested_history_run_item_occurrence_key, normalize_resumed_input, - reconcile_nested_history_owned_input_after_rewrite, ) from .run_internal.model_provider_lifecycle import ( _close_runner_owned_model_provider, @@ -153,6 +151,7 @@ cleanup_models_after_run, finalize_max_turns_handler_output, get_output_schema, + prepare_agent_for_turn, preserve_tool_task_cancellation, resolve_interrupted_turn, run_input_guardrails, @@ -983,17 +982,7 @@ async def _run_impl( if is_resumed_state and run_state is not None: run_state.set_trace(get_current_trace()) current_turn = run_state._current_turn - raw_original_input = run_state._original_input - original_input = normalize_resumed_input(raw_original_input) - ( - original_input, - run_state._nested_history_owned_session_item_refs, - ) = reconcile_nested_history_owned_input_after_rewrite( - raw_original_input, - original_input, - run_state._nested_history_owned_session_item_refs, - ) - run_state._original_input = copy_input_items(original_input) + original_input = run_state._normalize_resume_history() # Copy every list adopted from the state: the run appends to these, and # the caller still owns the state as a resumable snapshot. generated_items = list(run_state._generated_items) @@ -1279,32 +1268,20 @@ def _start_inbox_turn(step: NextStepFinalOutput) -> bool: raise sequential_guardrails = [] - current_bindings = bind_public_agent(current_agent) - execution_agent = current_bindings.execution_agent - input_before_sandbox = copy_input_items(original_input) - prepared_sandbox = await sandbox_runtime.prepare_agent( + current_bindings, original_input, _ = await prepare_agent_for_turn( + sandbox_runtime=sandbox_runtime, current_agent=current_agent, current_input=original_input, context_wrapper=context_wrapper, is_resumed_state=resuming_turn, + run_state=run_state, + owned_refs=run_state._nested_history_owned_session_item_refs + if run_state + else [], ) - current_bindings = prepared_sandbox.bindings execution_agent = current_bindings.execution_agent - if run_state is not None: - ( - original_input, - run_state._nested_history_owned_session_item_refs, - ) = reconcile_nested_history_owned_input_after_rewrite( - input_before_sandbox, - prepared_sandbox.input, - run_state._nested_history_owned_session_item_refs, - ) - else: - original_input = copy_input_items(prepared_sandbox.input) if starting_input is not None and not isinstance(starting_input, RunState): starting_input = copy_input_items(original_input) - if run_state is not None: - run_state._original_input = copy_input_items(original_input) normalized_starting_input: str | list[TResponseInputItem] = ( starting_input @@ -2970,17 +2947,7 @@ def run_streamed( ) # When resuming, use the original_input from state. # primeFromState will mark items as sent so prepareInput skips them - raw_input_for_result = run_state._original_input - input_for_result = normalize_resumed_input(raw_input_for_result) - ( - input_for_result, - run_state._nested_history_owned_session_item_refs, - ) = reconcile_nested_history_owned_input_after_rewrite( - raw_input_for_result, - input_for_result, - run_state._nested_history_owned_session_item_refs, - ) - run_state._original_input = copy_input_items(input_for_result) + input_for_result = run_state._normalize_resume_history() # Use context from RunState if not provided, otherwise override it. context_wrapper = resolve_resumed_context( run_state=run_state, diff --git a/src/agents/run_inbox.py b/src/agents/run_inbox.py index b5fa95bc92..33f6f81f6f 100644 --- a/src/agents/run_inbox.py +++ b/src/agents/run_inbox.py @@ -107,10 +107,12 @@ def status(self) -> Literal["queued", "submitted", "not_submitted", "unknown"]: return self._future.result().status if self._future.done() else "queued" async def wait(self) -> MessageOutcome: - """Wait until Runner knows the outcome. + """Wait for the outcome of the first attempt to submit this message to the adapter. - Keep consuming stream events while waiting. Waiting inside a tool or the - stream consumer can prevent the next model request from starting. + A run can end before it tries to submit the message. Use ``receipt.status`` + to check without waiting. Waiting inside a tool or the stream consumer + can prevent the next model request from starting. Wait in a separate task + or after the run ends. """ return await asyncio.shield(self._future) @@ -119,20 +121,32 @@ class RunInbox: """Send messages to one asynchronous run. Pass a fresh inbox to Runner.run(..., inbox=inbox). For Runner.run_streamed, - you can call steer() and queue() directly on the returned result. Call these - methods on the run's event loop. Neither interrupts a running tool or model + you can call steer() and queue() directly on the returned result. Call either + method on the run's event loop without ``await``. Each queues the message and + returns a receipt immediately. Neither interrupts a running tool or model request. In Codex mode, messages arrive between Runner requests, never inside a native Codex turn. Messages stay in memory. Pausing for approval, cancellation, failure, or reaching the turn limit ends delivery. Check the receipt before resending. For a paused run, use RunState.add_input before resuming with a fresh inbox. - Do not wait for a receipt inside a tool that must finish before delivery. + Use ``await receipt.wait()`` in a separate task or after the run ends if you + need the submission outcome. Waiting inside a tool can block delivery. If approval pauses a follow-up, the checkpoint identifies the active task so guardrails see the same input after resume. It does not save the inbox or messages still waiting in the queue. + Custom handoff filters should preserve message objects or InputItem IDs + when editing or moving messages. This lets tool guardrails distinguish the + current task from earlier requests. To replace a task with a summary, + edit its message in place or keep its InputItem ID. Use steer() or queue() + to add a new instruction. If the run continues after an answer, a handoff + filter or sandbox context hook can rebuild messages without their original + objects or IDs only if it preserves the entire sequence of user messages + and the SDK can still identify each message's task. Otherwise the run + raises UserError before the next model request or tool call. + Callbacks should propagate CancelledError after cleanup. On Python 3.10, Runner.run cannot detect cancellation if a callback suppresses that exception. """ @@ -162,6 +176,7 @@ def __init__(self, *, max_pending: int = 100) -> None: def steer(self, text: str) -> MessageReceipt: """Guide the current task after the current model request and its tools finish. + Call ``receipt = inbox.steer(text)`` without ``await`` to queue the message now. Runner sends all pending steering messages in order before starting a queued task. If the model has already answered, Runner continues with the new input. """ @@ -172,6 +187,7 @@ def steer(self, text: str) -> MessageReceipt: def queue(self, text: str) -> MessageReceipt: """Start this follow-up after the current task finishes successfully. + Call ``receipt = inbox.queue(text)`` without ``await`` to queue the follow-up now. Runner takes one follow-up at a time in arrival order. The same agent, conversation, guardrails and run limits apply. The last answer is final_output. """ @@ -242,6 +258,9 @@ def _advance( if not self._has_pending: self._stop_accepting() return False + # Saving the answer may have finished after the caller cancelled. + # Do not start preparing another task in that case. + self._check_owner_cancellation() if not self._can_admit_input(current_turn, max_turns, budget): return False if not self._steers: diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index 2fa3ed0c5b..13913ceff1 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -64,6 +64,7 @@ ToolCallItem, TResponseInputItem, TResponseStreamEvent, + _observe_input_copies, ) from ..lifecycle import RunHooks from ..logger import ( @@ -87,6 +88,7 @@ from ..run_inbox import current_inbox, stop_inbox_intake from ..run_state import RunState from ..sandbox.runtime import SandboxRuntime +from ..sandbox.sandbox_agent import SandboxAgent from ..stream_events import ( AgentUpdatedStreamEvent, RawResponsesStreamEvent, @@ -155,11 +157,11 @@ ) from .items import ( REJECTION_MESSAGE, + NestedHistoryOwnedItemRef, copy_input_items, deduplicate_input_items_preferring_latest, ensure_input_item_format, ensure_nested_history_run_item_occurrence_key, - normalize_resumed_input, prepare_model_input_items, reconcile_nested_history_owned_input_after_rewrite, run_items_to_input_items, @@ -249,6 +251,7 @@ ) from .turn_resolution import ( _get_turn_input, + _HandoffTaskInputs, _snapshot_function_calls, check_for_final_output_from_tools, execute_final_output, @@ -1024,6 +1027,55 @@ async def preserve_tool_task_cancellation(awaitable: Awaitable[T]) -> T: raise +async def prepare_agent_for_turn( + *, + sandbox_runtime: SandboxRuntime[TContext], + current_agent: Agent[TContext], + current_input: str | list[TResponseInputItem], + context_wrapper: RunContextWrapper[TContext], + is_resumed_state: bool, + run_state: RunState[Any, Any] | None, + owned_refs: list[NestedHistoryOwnedItemRef], +) -> tuple[ + AgentBindings[TContext], str | list[TResponseInputItem], list[NestedHistoryOwnedItemRef] +]: + """Keep the model input and the task seen by tool guardrails aligned.""" + task_inputs = None + if isinstance(current_agent, SandboxAgent) and run_state is not None: + task = run_state._task_input_ids + inbox = current_inbox() + # Sandbox preparation precedes admission. Check the first request + # after an answer too, while the checkpoint still owns that answer. + if task is not None or (inbox is not None and inbox._pending_output): + run_state._validate_task_history(current_input) + # A capability may edit nested message content and then raise. + # Keep the published stream and the last checkpoint intact. + memo: dict[int, Any] = {} + current_input = deepcopy(current_input, memo) + owned_refs = [ + _dc.replace(ref, input_item=memo.get(id(ref.input_item), ref.input_item)) + for ref in owned_refs + ] + task_inputs = _HandoffTaskInputs(current_input, [], task or (), []) + before = copy_input_items(current_input) + with _observe_input_copies(task_inputs.record_context_copy if task_inputs else None): + prepared = await sandbox_runtime.prepare_agent( + current_agent=current_agent, + current_input=current_input, + context_wrapper=context_wrapper, + is_resumed_state=is_resumed_state, + ) + rewritten, retained = reconcile_nested_history_owned_input_after_rewrite( + before, prepared.input, owned_refs + ) + if run_state is not None: + if task_inputs is not None: + task_inputs.rebase_context(run_state, rewritten) + run_state._original_input = copy_input_items(rewritten) + run_state._nested_history_owned_session_item_refs = list(retained) + return prepared.bindings, rewritten, retained + + async def start_streaming( starting_input: str | list[TResponseInputItem], streamed_result: RunResultStreaming, @@ -1222,9 +1274,9 @@ async def _stop_before_turn_if_cancelled(*, during_admission: bool = False) -> b streamed_result._event_queue.put_nowait(QueueCompleteSentinel()) return True - def _start_inbox_turn(completed_turn: SingleStepResult) -> None: - nonlocal should_run_agent_start_hooks - should_run_agent_start_hooks = True + def _record_continued_turn(completed_turn: SingleStepResult) -> None: + # Both policy and inbox continuations have now passed output guardrails. + # Include this turn's checks in the next server acceptance checkpoint. if run_state is not None: run_state._current_step = NextStepRunAgain() accepted_tool_input_guardrail_results.extend( @@ -1286,16 +1338,7 @@ def _mark_response_hooks_started() -> None: prepared_input: str | list[TResponseInputItem] if is_resumed_state and run_state is not None: - prepared_input = normalize_resumed_input(starting_input) - ( - prepared_input, - run_state._nested_history_owned_session_item_refs, - ) = reconcile_nested_history_owned_input_after_rewrite( - starting_input, - prepared_input, - run_state._nested_history_owned_session_item_refs, - ) - run_state._original_input = copy_input_items(prepared_input) + prepared_input = run_state._normalize_resume_history() streamed_result._nested_history_owned_session_item_refs = list( run_state._nested_history_owned_session_item_refs ) @@ -1493,28 +1536,23 @@ async def _save_max_turns_items( sequential_guardrails = [] if sandbox_runtime is not None: - input_before_sandbox = copy_input_items(prepared_turn_input) - prepared_sandbox = await sandbox_runtime.prepare_agent( + ( + current_bindings, + prepared_turn_input, + retained_owned_refs, + ) = await prepare_agent_for_turn( + sandbox_runtime=sandbox_runtime, current_agent=current_agent, current_input=prepared_turn_input, context_wrapper=context_wrapper, is_resumed_state=is_resumed_state, + run_state=run_state, + owned_refs=streamed_result._nested_history_owned_session_item_refs, ) - current_bindings = prepared_sandbox.bindings execution_agent = current_bindings.execution_agent - prepared_turn_input, retained_owned_refs = ( - reconcile_nested_history_owned_input_after_rewrite( - input_before_sandbox, - prepared_sandbox.input, - streamed_result._nested_history_owned_session_item_refs, - ) - ) streamed_result._nested_history_owned_session_item_refs = retained_owned_refs streamed_result.input = prepared_turn_input streamed_result._original_input = copy_input_items(prepared_turn_input) - if run_state is not None: - run_state._original_input = copy_input_items(prepared_turn_input) - run_state._nested_history_owned_session_item_refs = list(retained_owned_refs) sandbox_runtime.apply_result_metadata(streamed_result) # Resumed tool work belongs to the agent even when it finishes or fails @@ -1782,12 +1820,12 @@ def on_resumed_policy_error() -> None: turn_result.tool_output_guardrail_results ) if finish_previous_answer is not None: - _start_inbox_turn(turn_result) + _record_continued_turn(turn_result) + should_run_agent_start_hooks = True continue if turn_result.next_step.continue_after_guardrails: pending_feedback = turn_result.feedback - if run_state is not None: - run_state._current_step = NextStepRunAgain() + _record_continued_turn(turn_result) if await _wait_for_streamed_turn_events_and_stop_if_cancelled( streamed_result ): @@ -2395,7 +2433,8 @@ def _record_max_turns_handler_output( if streamed_result._stored_exception is not None: break if finish_previous_answer is not None: - _start_inbox_turn(turn_result) + _record_continued_turn(turn_result) + should_run_agent_start_hooks = True continue if turn_result.next_step.continue_after_guardrails: pending_feedback = turn_result.feedback @@ -2404,8 +2443,7 @@ def _record_max_turns_handler_output( streamed_result._replay_from_model_input_items = ( model_input_items != streamed_result.new_items ) - if run_state is not None: - run_state._current_step = NextStepRunAgain() + _record_continued_turn(turn_result) if await _wait_for_streamed_turn_events_and_stop_if_cancelled( streamed_result ): diff --git a/src/agents/run_internal/turn_resolution.py b/src/agents/run_internal/turn_resolution.py index 9b256780c8..0b986244a0 100644 --- a/src/agents/run_internal/turn_resolution.py +++ b/src/agents/run_internal/turn_resolution.py @@ -107,6 +107,7 @@ ToolSearchOutputItem, TResponseInputItem, TResponseOutputItem, + _observe_input_copies, coerce_tool_search_call_raw_item, coerce_tool_search_output_raw_item, ) @@ -123,7 +124,7 @@ from ..run_context import AgentHookContext, RunContextWrapper, TContext from ..run_error_handlers import RunErrorHandlers from ..run_inbox import stop_inbox_intake -from ..run_state import RunState +from ..run_state import RunState, _user_message_key, _user_message_keys from ..tool import ( ApplyPatchTool, CodeInterpreterTool, @@ -162,7 +163,9 @@ REJECTION_MESSAGE, NestedHistoryOwnedItem, apply_patch_rejection_item, + copy_input_items, drop_orphan_function_calls, + ensure_nested_history_run_item_occurrence_key, extract_mcp_request_id_from_run, function_rejection_item, order_current_turn_tool_outputs, @@ -395,22 +398,25 @@ def _get_turn_input( original_input: str | list[TResponseInputItem], generated_items: list[RunItem], ) -> list[TResponseInputItem]: - if run_state is not None and run_state._task_input_ids == (): - # The caller withdrew the follow-up. Do not revive the previous task. - return [] - if run_state is not None and isinstance(run_state._task_input_ids, tuple): - # An approval can pause the run before the server accepts the whole - # task. Restore its order from pending input and the agent's history. - visible: dict[str, TResponseInputItem | None] = dict.fromkeys(run_state._task_input_ids) - for index, input_id in enumerate(run_state._pending_input_ids): - if input_id in visible: - visible[input_id] = run_state._pending_input[index] - for item in generated_items: - if isinstance(item, InputItem) and item.input_id in visible: - visible[item.input_id] = item.raw_item - task_input = [item for item in visible.values() if item is not None] - if task_input: - original_input = task_input + if run_state is not None and (task := run_state._task_input_ids) is not None: + # A handoff may split a task between rewritten history and retained items. + # Missing messages never grant the original task's permissions. + ids = {key for key in task if isinstance(key, str)} + visible = run_state._visible_task_inputs(ids, generated_items) + history = ( + ItemHelpers.input_to_new_input_list(original_input) if len(ids) < len(task) else [] + ) + keys = _user_message_keys(history) + task_input: list[TResponseInputItem] = [] + for key in task: + if isinstance(key, str): + if key in visible: + task_input.append(visible[key]) + elif keys.get(key[0]) == key[1]: + task_input.append(history[key[0]]) + else: + raise UserError("Invalid active task input references.") + original_input = task_input try: return ItemHelpers.input_to_new_input_list(original_input) except Exception: @@ -690,6 +696,208 @@ def _resolve_server_managed_handoff_behavior( return input_filter, False +_MessageOwner = Literal["current", "earlier", "ambiguous"] + + +def _copy_handoff_messages(items: list[RunItem], memo: dict[int, Any]) -> list[RunItem]: + """Isolate editable inputs without cloning agents, tools or session resources.""" + copied: list[RunItem] = [] + for item in items: + if isinstance(item, InputItem): + if id(item) not in memo: + # Session history still owns the original occurrence. + ensure_nested_history_run_item_occurrence_key(item) + clone = copy(item) + clone.raw_item = deepcopy(item.raw_item, memo) + memo[id(item)] = clone + copied.append(memo[id(item)]) + else: + copied.append(item) + return copied + + +class _HandoffTaskInputs: + """Identify the current task's user messages across a handoff filter.""" + + def __init__( + self, + history: str | list[TResponseInputItem], + items: list[RunItem], + task: Container[str | tuple[int, str]], + turn_input: list[TResponseInputItem], + ) -> None: + self._input_ids: dict[str, _MessageOwner] = {} + self._string_source: tuple[str, _MessageOwner] | None = None + self._user_item_ids: set[str] = set() + self._content: dict[str, _MessageOwner] = {} + self._sequence: list[tuple[str, _MessageOwner]] = [] + # Keep each object alive while a filter can move or edit it. + self._objects: dict[int, tuple[object, _MessageOwner]] = {} + for i, key in _user_message_keys(history).items(): + raw = history if isinstance(history, str) else history[i] + owner: _MessageOwner = "current" if (i, key) in task else "earlier" + if isinstance(raw, str): + self._string_source = (key, owner) + self._remember_source(raw, key, owner) + for item in items: + if isinstance(item, InputItem): + owner = "current" if item.input_id in task else "earlier" + self._input_ids[item.input_id] = owner + for key in _user_message_keys([item.raw_item]).values(): + self._remember_source(item.raw_item, key, owner) + self._user_item_ids.add(item.input_id) + # Hooks receive a separate copy of the current task before the filter + # runs. Only recognize messages that are still part of that task. + for i, key in _user_message_keys(turn_input).items(): + if self._content.get(key) in ("current", "ambiguous"): + self._remember(turn_input[i], key, "current") + + def _remember_source(self, raw: object, key: str, owner: _MessageOwner) -> None: + self._sequence.append((key, owner)) + self._remember(raw, key, owner) + + def _remember(self, raw: object, key: str, owner: _MessageOwner) -> None: + if self._content.setdefault(key, owner) != owner: + self._content[key] = "ambiguous" + if isinstance(raw, str): + return + if self._objects.setdefault(id(raw), (raw, owner))[1] != owner: + self._objects[id(raw)] = (raw, "ambiguous") + + def _owner(self, raw: object, input_id: str | None = None) -> _MessageOwner | None: + record = self._objects.get(id(raw)) + by_object = record[1] if record is not None else None + by_id = self._input_ids.get(input_id) if input_id is not None else None + if by_object is not None and by_id is not None and by_object != by_id: + return "ambiguous" + return by_id or by_object + + def record_copy(self, source: object, target: object) -> None: + # Record the source before a mapper can edit or reorder its inputs. + # Defer ambiguous cases until we know which messages the destination sees. + owner: _MessageOwner | None + if isinstance(source, HandoffInputData) and isinstance(source.input_history, str): + key = _user_message_key(target) + if key is None: + return + # Nesting reads new_items even when the filter sets input_items. + owner = self._string_owner(key, (*source.pre_handoff_items, *source.new_items)) + elif isinstance(source, str): + # A standalone conversion has no surrounding items to disambiguate text. + return + elif source is None: + owner = "earlier" # A quote from an earlier assistant summary. + elif isinstance(source, InputItem): + owner = self._owner(source.raw_item, source.input_id) + else: + owner = self._owner(source) + if owner is not None: + self._objects[id(target)] = (target, owner) + + def _string_owner(self, key: str, items: Sequence[RunItem]) -> _MessageOwner | None: + # A filter such as remove_all_tools can keep a string history while + # retaining the other user messages by ID. If a message disappears, + # the string could be a replacement for it, even if its text is unchanged. + if self._string_source is None or self._string_source[0] != key: + return None + retained = { + item.input_id + for item in items + if isinstance(item, InputItem) + and _user_message_key(item.raw_item) is not None + and self._owner(item.raw_item, item.input_id) != "ambiguous" + } + return self._string_source[1] if self._user_item_ids <= retained else None + + def _current_messages( + self, messages: list[tuple[str, _MessageOwner | None]], *, handoff: bool + ) -> list[bool]: + if all(owner in ("current", "earlier") for _, owner in messages): + return [owner == "current" for _, owner in messages] + # New wording cannot identify a task. An untracked copy is safe + # only when the entire user sequence and its task assignments agree. + resolved = [(key, owner or self._content.get(key)) for key, owner in messages] + if resolved == self._sequence: + return [owner == "current" for _, owner in resolved] + if handoff: + raise UserError( + "Cannot identify active task input after the handoff filter. " + "Preserve the original message objects or their InputItem IDs." + ) + raise UserError( + "Cannot identify active task input after context processing. " + "Preserve the original user message objects." + ) + + def handoff_refs( + self, + history: str | list[TResponseInputItem], + items: list[RunItem], + *, + pending: dict[str, bool], + ) -> tuple[list[tuple[int, str]], set[str]]: + keys = _user_message_keys(history) + messages = [ + ( + key, + self._string_owner(key, items) + if isinstance(history, str) + else self._owner(history[i]), + ) + for i, key in keys.items() + ] + item_ids: list[str] = [] + for item in items: + if ( + isinstance(item, InputItem) + and (key := _user_message_key(item.raw_item)) is not None + ): + messages.append((key, self._owner(item.raw_item, item.input_id))) + item_ids.append(item.input_id) + current = self._current_messages(messages, handoff=True) + refs = [ref for ref, keep in zip(keys.items(), current[: len(keys)], strict=True) if keep] + # A filter can wrap two distinct messages with the same new ID. + # Check each occurrence before reducing the active task to a set of + # IDs, including input still held for a server acknowledgement. + by_id = dict(pending) + for input_id, active in zip(item_ids, current[len(keys) :], strict=True): + if ( + not isinstance(input_id, str) + or not input_id + or by_id.setdefault(input_id, active) != active + ): + raise UserError("Invalid active task input references.") + return refs, {key for key, active in by_id.items() if active} + + def record_context_copy(self, source: object, target: object) -> None: + # Context processing can carry an existing occurrence through a public + # conversion. A bare string or a newly constructed transcript has no ID. + if isinstance(source, InputItem): + source = source.raw_item + if not isinstance(source, str) and (owner := self._owner(source)) is not None: + self._objects[id(target)] = (target, owner) + + def rebase_context( + self, + state: RunState[Any, Any], + history: str | list[TResponseInputItem], + ) -> None: + """A context hook can retain or remove messages, without starting a new task.""" + task = state._task_input_ids + keys = _user_message_keys(history) + messages = [ + (key, self._owner(history if isinstance(history, str) else history[i])) + for i, key in keys.items() + ] + current = self._current_messages(messages, handoff=False) + if task is None: + # The first follow-up has not passed admission yet. + return + refs = [ref for ref, keep in zip(keys.items(), current, strict=True) if keep] + generated = (ref for ref in task if isinstance(ref, str)) + state._task_input_ids = (*refs, *generated) + + async def execute_handoffs( *, public_agent: Agent[TContext], @@ -706,6 +914,7 @@ async def execute_handoffs( tool_input_guardrail_results: list[ToolInputGuardrailResult] | None = None, tool_output_guardrail_results: list[ToolOutputGuardrailResult] | None = None, handoff_output_committer: Callable[[HandoffOutputItem, Agent[Any]], None] | None = None, + run_state: RunState[Any] | None = None, ) -> SingleStepResult: """Execute a handoff and prepare the next turn for the new agent.""" @@ -851,7 +1060,24 @@ def nest_history( handoff_input_data: HandoffInputData | None = None session_step_items: list[RunItem] | None = None nested_history_owned_items: list[NestedHistoryOwnedItem] | None = None + task_inputs = None + source_history = original_input + filter_copies: dict[int, Any] = {} if input_filter is not None or should_nest_history: + # An empty follow-up can still receive replacement input at a later handoff. + if run_state is not None and (task := run_state._task_input_ids) is not None: + if input_filter is not None: + # A filter can edit a message, then raise or be cancelled. + # Publish its changes only after the handoff is validated. + original_input = deepcopy(original_input, filter_copies) + pre_step_items = _copy_handoff_messages(pre_step_items, filter_copies) + new_step_items = _copy_handoff_messages(new_step_items, filter_copies) + task_inputs = _HandoffTaskInputs( + original_input, + pre_step_items + new_step_items, + task, + context_wrapper.turn_input, + ) handoff_input_data = HandoffInputData( input_history=tuple(original_input) if isinstance(original_input, list) @@ -880,9 +1106,10 @@ def nest_history( ), ) raise UserError(f"Invalid input filter: {input_filter}") - filtered = input_filter(handoff_input_data) - if inspect.isawaitable(filtered): - filtered = await filtered + with _observe_input_copies(task_inputs.record_copy if task_inputs else None): + filtered = input_filter(handoff_input_data) + if inspect.isawaitable(filtered): + filtered = await filtered if not isinstance(filtered, HandoffInputData): _error_tracing.attach_error_to_span( span_handoff, @@ -911,10 +1138,11 @@ def nest_history( _get_nested_history_owned_items(filtered, source_data=handoff_input_data) ) elif should_nest_history and handoff_input_data is not None: - nested, nested_history_owned_items = nest_history( - handoff_input_data, - run_config.handoff_history_mapper, - ) + with _observe_input_copies(task_inputs.record_copy if task_inputs else None): + nested, nested_history_owned_items = nest_history( + handoff_input_data, + run_config.handoff_history_mapper, + ) original_input = ( nested.input_history if isinstance(nested.input_history, str) @@ -938,6 +1166,45 @@ def nest_history( ): _register_tool_call_items(context_wrapper, [handoff_output]) + if ( + task_inputs is not None + and run_state is not None + and (task := run_state._task_input_ids) is not None + ): + # History precedes generated items in the destination request. Keep both + # portions when a filter moves only some messages into input_history. + items = pre_step_items + new_step_items + history_refs, ids = task_inputs.handoff_refs( + original_input, + items, + pending={key: key in task for key in run_state._pending_input_ids}, + ) + visible = run_state._visible_task_inputs(ids, items) + item_refs = dict.fromkeys( + item.input_id + for item in items + if isinstance(item, InputItem) and item.input_id in visible + ) + # A server-managed request can still be holding unacknowledged input. + for key in task: + if isinstance(key, str) and key in visible: + item_refs.setdefault(key) + # Commit references with the history and items they identify, including + # when persistence fails before the destination's first request. + if filter_copies and isinstance(source_history, list) and isinstance(original_input, list): + # Keep exact session occurrences when a filter retained equal messages. + sources = { + id(filter_copies[id(item)]): item + for item in source_history + if id(item) in filter_copies + } + for index, raw in enumerate(original_input): + if (source := sources.get(id(raw))) is not None and source == raw: + original_input[index] = source + run_state._original_input = copy_input_items(original_input) + run_state._generated_items = list(items) + run_state._task_input_ids = (*history_refs, *item_refs) + return SingleStepResult( original_input=original_input, model_response=new_response, @@ -1346,6 +1613,7 @@ def _publish_completed_tools() -> None: if run_handoffs := processed_response.handoffs: return await execute_handoffs_call( + run_state=run_state, public_agent=public_agent, original_input=original_input, pre_step_items=pre_step_items, @@ -3313,6 +3581,7 @@ def _commit_handoff_output( return _commit_missing_state( await execute_handoffs_call( + run_state=run_state, public_agent=public_agent, original_input=original_input, pre_step_items=pre_step_items, diff --git a/src/agents/run_state.py b/src/agents/run_state.py index b5ed0f66d8..f89ef3d576 100644 --- a/src/agents/run_state.py +++ b/src/agents/run_state.py @@ -133,9 +133,12 @@ from .run_internal.items import ( NestedHistoryOwnedItemRef, ReasoningItemIdPolicy, + copy_input_items, digest_input_item, ensure_nested_history_run_item_occurrence_key, nested_history_run_item_occurrence_key, + normalize_resumed_input, + reconcile_nested_history_owned_input_after_rewrite, run_item_to_input_item, ) from .run_internal.tool_caller import ( @@ -879,6 +882,29 @@ def _copy_tool_approval_raw_item(raw_item: Any) -> Any: raise TypeError("Unsupported tool approval raw item") +# Follow-up message IDs, or (position, content digest) pairs after a history rewrite. +_TaskInputRef = str | tuple[int, str] +_TaskInputRefs = tuple[_TaskInputRef, ...] | None + + +def _user_message_key(item: object) -> str | None: + if not isinstance(item, dict) or item.get("role") != "user": + return None + content = item.get("content") + if isinstance(content, str): + content = [{"type": "input_text", "text": content}] + return digest_input_item({"role": "user", "content": content}) + + +def _user_message_keys(history: str | list[TResponseInputItem]) -> dict[int, str]: + """Compare user content across handoffs, including string and message-list inputs.""" + return { + index: key + for index, item in enumerate(ItemHelpers.input_to_new_input_list(history)) + if (key := _user_message_key(item)) is not None + } + + @dataclass class RunState(Generic[TContext, TAgent]): """Serializable snapshot of an agent run, including context, usage, and interruptions. @@ -933,12 +959,10 @@ class RunState(Generic[TContext, TAgent]): _pending_input: list[TResponseInputItem] = field(default_factory=list) """Input staged for admission immediately before the next resumed model call.""" - # None selects the original task. "handoff" selects the replacement input - # supplied by a handoff filter. An empty tuple means the caller withdrew - # the whole follow-up. The next admitted input becomes its replacement. - _task_input_ids: tuple[str, ...] | Literal["handoff"] | None = field( - default=None, init=False, repr=False, compare=False - ) + # None selects the original task. A follow-up can span history, generated + # items and pending input. Keep its references in the order seen by the agent. + # An empty tuple means there is no visible task until new input arrives. + _task_input_ids: _TaskInputRefs = field(default=None, init=False, repr=False, compare=False) # Input stays pending until the session saves it or the server acknowledges it. _pending_input_ids: tuple[str, ...] = field(default=(), init=False, repr=False, compare=False) @@ -1088,40 +1112,82 @@ def _restore_task_input(self, context: RunContextWrapper[Any]) -> None: context.turn_input = _get_turn_input(self, self._original_input, self._generated_items) - def _visible_task_input_ids( + def _validate_task_history(self, history: str | list[TResponseInputItem]) -> dict[int, str]: + keys = _user_message_keys(history) + for ref in self._task_input_ids or (): + if isinstance(ref, tuple) and keys.get(ref[0]) != ref[1]: + raise UserError("Invalid active task input references.") + return keys + + def _normalize_resume_history(self) -> str | list[TResponseInputItem]: + """Normalize once at each resume entry, keeping user occurrences in order.""" + previous = self._original_input + normalized, session_refs = reconcile_nested_history_owned_input_after_rewrite( + previous, + normalize_resumed_input(previous), + self._nested_history_owned_session_item_refs, + ) + task = self._task_input_ids + if task and any(isinstance(ref, tuple) for ref in task): + # Normalization removes orphan tool records. It preserves every + # user message in order, including distinct occurrences of equal text. + before = self._validate_task_history(previous) + after = _user_message_keys(normalized) + if list(before.values()) != list(after.values()): + raise UserError("Cannot identify active task input after resume normalization.") + positions = dict(zip(before, after, strict=True)) + self._task_input_ids = tuple( + (positions[ref[0]], ref[1]) if isinstance(ref, tuple) else ref for ref in task + ) + self._nested_history_owned_session_item_refs = session_refs + self._original_input = copy_input_items(normalized) + return normalized + + def _visible_task_inputs( self, ids: set[str], - validation_error_factory: RunStateValidationErrorFactory, - ) -> set[str]: + generated_items: list[RunItem], + validation_error_factory: RunStateValidationErrorFactory | None = None, + ) -> dict[str, TResponseInputItem]: # A handoff filter may repeat an occurrence. Its ID still identifies one # task message as long as all visible copies have the same content. - visible: dict[str, InputItem] = {} - for item in self._generated_items: + visible = { + key: self._pending_input[index] + for index, key in enumerate(self._pending_input_ids) + if key in ids + } + for item in generated_items: if not isinstance(item, InputItem) or item.input_id not in ids: continue - previous = visible.setdefault(item.input_id, item) - if previous is not item and json.dumps( - _serialize_raw_item_value(previous.raw_item), sort_keys=True + previous = visible.setdefault(item.input_id, item.raw_item) + if previous is not item.raw_item and json.dumps( + _serialize_raw_item_value(previous), sort_keys=True ) != json.dumps(_serialize_raw_item_value(item.raw_item), sort_keys=True): - raise validation_error_factory("Invalid active task input references.", UserError) - return set(visible) + invalid = validation_error_factory or _default_run_state_validation_error + raise invalid("Invalid active task input references.", UserError) + # A filter may keep an occurrence ID while converting the message + # into a transcript quote. Only user messages can carry task input. + # Check for conflicting copies above before discarding other roles. + return { + key: item + for key, item in visible.items() + if isinstance(item, dict) and item.get("role") == "user" + } - def _task_input_refs(self) -> list[str | int] | Literal["handoff"] | None: - """Reference only input visible to the current agent, without copying its text.""" - if not isinstance(self._task_input_ids, tuple): - return self._task_input_ids + def _task_input_refs(self) -> list[str | int] | dict[str, Any] | None: + """Use history positions, generated IDs and pending positions without copying text.""" + task = self._task_input_ids + if task is None: + return None pending = {key: index for index, key in enumerate(self._pending_input_ids)} - visible = self._visible_task_input_ids( - set(self._task_input_ids), _default_run_state_validation_error - ) - refs = [ - pending.get(key, key) - for key in self._task_input_ids - if key in pending or key in visible - ] - # A handoff can replace the entire task with the receiving agent's input. - # An explicitly withdrawn task stays empty instead. - return refs if refs or not self._task_input_ids else "handoff" + ids = {key for key in task if isinstance(key, str)} + visible = self._visible_task_inputs(ids, self._generated_items) + items = [pending.get(key, key) for key in task if isinstance(key, str) and key in visible] + history = [key for key in task if isinstance(key, tuple)] + if history: + self._validate_task_history(self._original_input) + return {"history": [i for i, _ in history], "items": items} + return items def _restore_task_input_refs( self, refs: object, validation_error_factory: RunStateValidationErrorFactory @@ -1132,19 +1198,34 @@ def _restore_task_input_refs( def invalid() -> RunStateValidationError: return validation_error_factory("Invalid active task input references.", UserError) - if refs == "handoff": - self._task_input_ids = "handoff" - return + ids: list[_TaskInputRef] = [] + if isinstance(refs, dict) and set(refs) == {"history", "items"}: + positions = refs["history"] + keys = _user_message_keys(self._original_input) + if ( + not isinstance(positions, list) + or not positions + or any(type(i) is not int or i not in keys for i in positions) + or positions != sorted(set(positions)) + ): + raise invalid() + ids.extend((i, keys[i]) for i in positions) + refs = refs["items"] if not isinstance(refs, list): raise invalid() - visible = self._visible_task_input_ids( - {ref for ref in refs if isinstance(ref, str)}, validation_error_factory + visible = self._visible_task_inputs( + {ref for ref in refs if isinstance(ref, str)}, + self._generated_items, + validation_error_factory, ) - ids: list[str] = [] for ref in refs: if isinstance(ref, str) and ref and ref in visible: ids.append(ref) - elif type(ref) is int and 0 <= ref < len(self._pending_input): + elif ( + type(ref) is int + and 0 <= ref < len(self._pending_input) + and _user_message_key(self._pending_input[ref]) is not None + ): ids.append(self._track_pending_input()[ref]) else: raise invalid() diff --git a/tests/sandbox/test_runtime.py b/tests/sandbox/test_runtime.py index cf1acb2ddf..09676e4c12 100644 --- a/tests/sandbox/test_runtime.py +++ b/tests/sandbox/test_runtime.py @@ -22,7 +22,19 @@ import agents._debug as _debug import agents.sandbox.runtime_agent_preparation as runtime_agent_preparation_module -from agents import Agent, AgentHooks, LocalShellTool, RunHooks, Runner, function_tool +from agents import ( + Agent, + AgentHooks, + LocalShellTool, + RunHooks, + RunInbox, + Runner, + ToolGuardrailFunctionOutput, + ToolInputGuardrailData, + function_tool, + handoff, + tool_input_guardrail, +) from agents._run_state_agent_identity import _build_agent_identity_map from agents.exceptions import InputGuardrailTripwireTriggered, UserError from agents.guardrail import GuardrailFunctionOutput, InputGuardrail, OutputGuardrail @@ -2494,6 +2506,256 @@ async def test_context_rewrite_releases_removed_nested_history_ownership(streame assert replay_texts.count("handoff message") == 1 +@pytest.mark.parametrize("streamed", [False, True], ids=["non_streamed", "streamed"]) +@pytest.mark.parametrize( + "rewrite", ["drop-prefix", "withdraw-task", "edit-in-place", "replace", "replace-with-earlier"] +) +@pytest.mark.asyncio +async def test_context_rewrite_preserves_visible_follow_up_for_tool_guardrail( + streamed: bool, rewrite: str +) -> None: + inbox = RunInbox() + restriction = "Do not publish." + checked: list[list[TResponseInputItem]] = [] + effects: list[str] = [] + + class EditTask(Capability): + def process_context(self, context: list[TResponseInputItem]) -> list[TResponseInputItem]: + for index, item in enumerate(context): + if item.get("role") == "user" and item.get("content") == "Review only.": + # Identical text, but only the in-place edit preserves the occurrence. + if rewrite in ("replace", "replace-with-earlier"): + context[index] = {"role": "user", "content": restriction} + else: + cast(dict[str, Any], item)["content"] = restriction + return context + + collision = rewrite == "replace-with-earlier" + initial = restriction if collision else "old context" + edit = rewrite in ("edit-in-place", "replace", "replace-with-earlier") + capability = ( + EditTask(type="edit-task") + if edit + else _DropContextTextCapability( + restriction if rewrite == "withdraw-task" else "old context" + ) + ) + + @tool_input_guardrail + def check_task(data: ToolInputGuardrailData) -> ToolGuardrailFunctionOutput: + checked.append(list(data.context.turn_input)) + if any(item.get("content") == restriction for item in data.context.turn_input): + return ToolGuardrailFunctionOutput.reject_content("Publication blocked.") + return ToolGuardrailFunctionOutput.allow() + + @function_tool(tool_input_guardrails=[check_task]) + async def publish() -> str: + effects.append("published") + return "done" + + worker_model = ScriptedModel( + [[get_function_tool_call("publish", "{}")], [get_final_output_message("done")]] + ) + worker = SandboxAgent( + name="worker", + model=worker_model, + default_manifest=Manifest(), + capabilities=[capability], + tools=[publish], + ) + + def first_answer(call: Any) -> list[Any]: + inbox.queue("Review only." if edit else restriction) + return [get_final_output_message("first answer")] + + triage = SandboxAgent( + name="triage", + model=ScriptedModel([ModelStep.respond(first_answer), [get_handoff_tool_call(worker)]]), + default_manifest=Manifest(), + capabilities=[], + handoffs=[worker], + ) + config = RunConfig( + sandbox=SandboxRunConfig(client=_ManifestSessionClient()), + nest_handoff_history=True, + # Keep the earlier user occurrence alongside its identically worded replacement. + handoff_history_mapper=(lambda items: items) if collision else None, + ) + + async def run() -> None: + if streamed: + stream = Runner.run_streamed(triage, initial, inbox=inbox, run_config=config) + async for _ in stream.stream_events(): + pass + else: + await Runner.run(triage, initial, inbox=inbox, run_config=config) + + if rewrite in ("replace", "replace-with-earlier"): + with pytest.raises( + UserError, match="Cannot identify active task input after context processing" + ): + await run() + assert not worker_model.calls and not checked and not effects + return + + await run() + withdraw = rewrite == "withdraw-task" + expected = [] if withdraw else [{"role": "user", "content": restriction}] + assert [item for item in worker_model.calls[0].input if item.get("role") == "user"] == expected + assert checked == [expected] + assert effects == (["published"] if withdraw else []) + + +@pytest.mark.parametrize("streamed", [False, True], ids=["non_streamed", "streamed"]) +@pytest.mark.parametrize("path", ["queue", "steer", "handoff", "withdrawn", "ordinary"]) +@pytest.mark.asyncio +async def test_context_rewrite_without_history_backed_task(streamed: bool, path: str) -> None: + inbox = RunInbox() + direct = path in ("queue", "steer") + rewrite = not direct + effects: list[str] = [] + initial: list[TResponseInputItem] = [{"role": "user", "content": "Old context."}] + restriction = "Do not publish." + + class AddMessage(Capability): + def process_context(self, context: list[TResponseInputItem]) -> list[TResponseInputItem]: + if not rewrite or any(item.get("content") == restriction for item in context): + return context + # A rejected rewrite must also discard edits to existing messages. + cast(dict[str, Any], context[0])["content"] = "Edited context." + return [*context, {"role": "user", "content": restriction}] + + @function_tool + async def publish() -> str: + effects.append("published") + return "done" + + def first_answer(call: Any) -> list[Any]: + nonlocal rewrite + rewrite = True + send = inbox.steer if path == "steer" else inbox.queue + send("Review only.") + return [get_final_output_message("first answer")] + + worker_model = ScriptedModel() + if direct: + worker_model.extend([ModelStep.respond(first_answer)]) + worker_model.extend( + [[get_function_tool_call("publish", "{}")], [get_final_output_message("done")]] + ) + worker = SandboxAgent( + name="worker", + model=worker_model, + default_manifest=Manifest(), + capabilities=[AddMessage(type="add-message")], + tools=[publish], + ) + agent = worker + if not direct: + triage_model = ScriptedModel() + if path != "ordinary": + triage_model.extend([ModelStep.respond(first_answer)]) + triage_model.extend([[get_handoff_tool_call(worker)]]) + agent = SandboxAgent( + name="triage", + model=triage_model, + default_manifest=Manifest(), + capabilities=[], + handoffs=[ + handoff(worker, input_filter=lambda data: data.clone(pre_handoff_items=())) + if path == "withdrawn" + else worker + ], + ) + config = RunConfig( + sandbox=SandboxRunConfig(client=_ManifestSessionClient()), nest_handoff_history=False + ) + stream: RunResultStreaming | None = None + + async def run() -> None: + nonlocal stream + if streamed: + stream = Runner.run_streamed(agent, initial, inbox=inbox, run_config=config) + async for _ in stream.stream_events(): + pass + else: + await Runner.run(agent, initial, inbox=inbox, run_config=config) + + if path == "ordinary": + await run() + assert restriction in [item.get("content") for item in worker_model.calls[0].input] + assert effects == ["published"] + return + + with pytest.raises( + UserError, match="Cannot identify active task input after context processing" + ): + await run() + assert len(worker_model.calls) == (1 if direct else 0) + assert not effects + if streamed: + assert stream is not None + expected = [{"role": "user", "content": "Old context."}] + assert stream.input == expected + assert stream.to_state().to_json()["original_input"] == expected + + +@pytest.mark.asyncio +async def test_failed_context_edit_preserves_stream_checkpoint() -> None: + inbox = RunInbox() + fail = True + + class EditTask(Capability): + def process_context(self, context: list[TResponseInputItem]) -> list[TResponseInputItem]: + if fail: + for item in context: + if item.get("role") == "user": + cast(dict[str, Any], item)["content"] = "Failed edit." + raise RuntimeError("context failed after editing") + return context + + worker_model = ScriptedModel([[get_final_output_message("done")]]) + worker = SandboxAgent( + name="worker", + model=worker_model, + default_manifest=Manifest(), + capabilities=[EditTask(type="edit-task")], + ) + + def first_answer(call: Any) -> list[Any]: + inbox.queue("Review only.") + return [get_final_output_message("first answer")] + + triage_model = ScriptedModel([ModelStep.respond(first_answer), [get_handoff_tool_call(worker)]]) + triage = SandboxAgent( + name="triage", + model=triage_model, + default_manifest=Manifest(), + capabilities=[], + handoffs=[worker], + ) + config = RunConfig( + sandbox=SandboxRunConfig(client=_ManifestSessionClient()), nest_handoff_history=True + ) + stream = Runner.run_streamed(triage, "old context", inbox=inbox, run_config=config) + with pytest.raises(RuntimeError, match="context failed after editing"): + async for _ in stream.stream_events(): + pass + assert not worker_model.calls + state = await RunState.from_string(triage, stream.to_state().to_string()) + assert isinstance(stream.input, list) + assert [item.get("content") for item in stream.input if item.get("role") == "user"] == [ + "Review only." + ] + + fail = False + result = await Runner.run(triage, state, run_config=config) + assert result.final_output == "done" + assert result.context_wrapper.turn_input == [{"role": "user", "content": "Review only."}] + assert len(triage_model.calls) == 2 + assert len(worker_model.calls) == 1 + + @pytest.mark.parametrize("streamed", [False, True], ids=["non_streamed", "streamed"]) @pytest.mark.asyncio async def test_context_rebuild_retains_unambiguous_nested_history_ownership( diff --git a/tests/test_agent_hooks.py b/tests/test_agent_hooks.py index d9b9b47f06..5f29196822 100644 --- a/tests/test_agent_hooks.py +++ b/tests/test_agent_hooks.py @@ -2,6 +2,7 @@ import json from collections import defaultdict +from copy import copy from dataclasses import replace from typing import Any @@ -9,8 +10,10 @@ from typing_extensions import TypedDict from agents.agent import Agent, AgentBase +from agents.exceptions import UserError from agents.guardrail import GuardrailFunctionOutput, output_guardrail -from agents.handoffs import HandoffInputData, handoff +from agents.handoffs import HandoffInputData, handoff, nest_handoff_history +from agents.items import InputItem, ItemHelpers, TResponseInputItem from agents.lifecycle import AgentHooks from agents.result import RunResult, RunResultStreaming from agents.run import Runner @@ -21,6 +24,11 @@ from agents.testing import ModelCall, ModelStep, ScriptedModel from agents.tool import Tool, function_tool from agents.tool_context import ToolContext +from agents.tool_guardrails import ( + ToolGuardrailFunctionOutput, + ToolInputGuardrailData, + tool_input_guardrail, +) from .test_responses import ( get_final_output_message, @@ -504,7 +512,7 @@ async def _run_with_inbox( inbox: RunInbox, streamed: bool, *, - value: str | RunState[Any] = "first task", + value: str | list[TResponseInputItem] | RunState[Any] = "first task", server_managed: bool = False, run_config: RunConfig | None = None, context: RunContextWrapper[Any] | None = None, @@ -886,7 +894,19 @@ def withhold_both(data: CallModelData[Any]) -> ModelInputData: @pytest.mark.parametrize("streamed", [False, True]) @pytest.mark.parametrize( "filter_mode,serialize", - [("none", True), ("replace", True), ("repeat", False), ("repeat", True)], + [ + ("none", True), + ("replace", True), + ("untracked-summary", False), + ("untracked-summary-shared", False), + ("untracked-summary-copy", False), + ("untracked-summary-nested-shared", False), + ("untracked-summary-nested-copy", False), + ("repeat", False), + ("repeat", True), + ("nest-equal-text", True), + ("remove-tools-equal-text", True), + ], ) async def test_follow_up_turn_input_respects_handoff_filter( streamed: bool, filter_mode: str, serialize: bool @@ -894,6 +914,11 @@ async def test_follow_up_turn_input_respects_handoff_filter( inbox = RunInbox() hooks = AgentHooksWithTurnInput() tool_inputs: list[list[Any]] = [] + nested = filter_mode == "nest-equal-text" + follow_up = "first task" if filter_mode.endswith("equal-text") else "second task" + restriction = "Do not publish." + if filter_mode.startswith("untracked-summary-"): + follow_up = "Review the draft. Do not publish." @function_tool(needs_approval=True) async def work(ctx: RunContextWrapper[Any]) -> str: @@ -904,14 +929,34 @@ async def work(ctx: RunContextWrapper[Any]) -> str: destination = Agent(name="destination", model=model, hooks=hooks, tools=[work]) def first_answer(call: ModelCall) -> list[Any]: - inbox.queue("second task") + inbox.queue(follow_up) return [get_text_message("first answer")] def filter_input(data: HandoffInputData) -> HandoffInputData: + if filter_mode == "remove-tools-equal-text": + from agents.extensions.handoff_filters import remove_all_tools + + return remove_all_tools(data) if filter_mode == "repeat": items = data.pre_handoff_items return data.clone(pre_handoff_items=(*items, items[-1])) - return replace(data, input_history="public summary", pre_handoff_items=()) + if filter_mode == "untracked-summary": + return data.clone(input_history="public summary", pre_handoff_items=()) + if filter_mode.startswith("untracked-summary-"): + # The filter replaces both tasks with a summary of the follow-up. + # Its wording matches the first task regardless of string allocation. + summary = ( + restriction if filter_mode.endswith("shared") else restriction.encode().decode() + ) + rewritten = data.clone(input_history=summary, pre_handoff_items=()) + if "nested" in filter_mode: + return nest_handoff_history(rewritten, history_mapper=lambda rows: rows) + return rewritten + active = data.pre_handoff_items[-1] + assert isinstance(active, InputItem) + message: Any = active.raw_item + message["content"] = "public summary" + return data.clone(input_history=(message,), pre_handoff_items=()) source = Agent( name="source", @@ -919,11 +964,19 @@ def filter_input(data: HandoffInputData) -> HandoffInputData: [ModelStep.respond(first_answer), [get_handoff_tool_call(destination, args="{}")]] ), handoffs=[ - handoff(destination, input_filter=None if filter_mode == "none" else filter_input) + handoff(destination, nest_handoff_history=True) + if nested + else handoff(destination, input_filter=None if filter_mode == "none" else filter_input) ], ) + if filter_mode.startswith("untracked-summary"): + initial = "first task" if filter_mode == "untracked-summary" else restriction + with pytest.raises(UserError, match="Cannot identify active task input"): + await _run_with_inbox(source, inbox, streamed, value=initial) + assert not model.calls and not hooks.captured_turn_inputs and not tool_inputs + return paused = await _run_with_inbox(source, inbox, streamed) - content = "public summary" if filter_mode == "replace" else "second task" + content = "public summary" if filter_mode == "replace" else follow_up expected = [[{"role": "user", "content": content}]] assert hooks.captured_turn_inputs == expected assert len(paused.interruptions) == 1 and not tool_inputs @@ -936,7 +989,16 @@ def filter_input(data: HandoffInputData) -> HandoffInputData: resumed = await _run_with_inbox(source, RunInbox(), streamed, value=state) assert resumed.final_output == "done" assert tool_inputs == hooks.end_inputs == expected - if filter_mode == "replace": + if nested: + # The original request is in the assistant summary. Only the queued + # occurrence is still a user message and identifies the active task. + history = model.calls[0].input + assert any( + item.get("role") == "assistant" and "first task" in str(item.get("content")) + for item in history + ) + assert [item for item in history if item.get("role") == "user"] == expected[0] + elif filter_mode == "replace": assert [ item.get("content") for item in model.calls[-1].input if item.get("role") == "user" ] == ["public summary"] @@ -946,6 +1008,691 @@ def filter_input(data: HandoffInputData) -> HandoffInputData: ] == ["first task", "second task", "second task"] +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("serialize", [False, True], ids=["in-memory", "json"]) +@pytest.mark.parametrize( + ("moved", "history_source"), + [ + pytest.param(0, "distinct", id="move-first"), + pytest.param(1, "distinct", id="move-second"), + pytest.param(0, "split-call", id="resume-normalizes-history"), + pytest.param(0, "active", id="move-repeated-active"), + pytest.param(0, "earlier", id="retain-earlier-only"), + pytest.param(0, "copy", id="ambiguous-copy"), + pytest.param(0, "text", id="ambiguous-text"), + pytest.param(0, "nested-text", id="ambiguous-nested-text"), + ], +) +async def test_handoff_splits_follow_up_between_history_and_generated_items( + streamed: bool, serialize: bool, moved: int, history_source: str +) -> None: + inbox = RunInbox() + restriction = "Do not publish." + messages = ["Review the draft."] + messages.insert(moved, restriction) + checked: list[list[Any]] = [] + effects: list[str] = [] + + def first_answer(call: ModelCall) -> list[Any]: + for message in messages: + inbox.steer(message) + return [get_text_message("first answer")] + + def split(data: HandoffInputData) -> HandoffInputData: + items = data.pre_handoff_items[-2:] + item = items[moved] + assert isinstance(item, InputItem) + retained = item.raw_item + if history_source == "split-call": + # The destination receives both halves of the handoff. Resume normalizes + # history separately, so the call before the restriction drops out. + call, output = data.new_items + return data.clone( + input_history=(call.to_input_item(), retained), + pre_handoff_items=(items[1 - moved],), + input_items=(output,), + ) + if history_source == "earlier": + assert isinstance(data.input_history, tuple) + retained = data.input_history[0] + elif history_source == "copy": + retained = copy(item.raw_item) + elif history_source in ("text", "nested-text"): + text = item.raw_item.get("content") + assert isinstance(text, str) + split_input = data.clone(input_history=text, pre_handoff_items=(items[1 - moved],)) + if history_source == "nested-text": + return nest_handoff_history(split_input, history_mapper=lambda rows: rows) + return split_input + return data.clone(input_history=(retained,), pre_handoff_items=(items[1 - moved],)) + + @tool_input_guardrail + def check_task(data: ToolInputGuardrailData) -> ToolGuardrailFunctionOutput: + texts = [item.get("content") for item in data.context.turn_input] + checked.append(texts) + if restriction in texts: + return ToolGuardrailFunctionOutput.reject_content("Publication blocked.") + return ToolGuardrailFunctionOutput.allow() + + @function_tool(needs_approval=True, tool_input_guardrails=[check_task]) + async def publish() -> str: + effects.append("published") + return "done" + + model = ScriptedModel([[get_function_tool_call("publish", "{}")], [get_text_message("done")]]) + destination = Agent(name="destination", model=model, tools=[publish]) + source = Agent( + name="source", + model=ScriptedModel( + [ModelStep.respond(first_answer), [get_handoff_tool_call(destination, args="{}")]] + ), + handoffs=[handoff(destination, input_filter=split)], + ) + initial: str | list[TResponseInputItem] = "first task" + if history_source in ("text", "nested-text"): + initial = restriction + elif history_source not in ("distinct", "split-call"): + initial = [{"role": "user", "content": restriction}] + if history_source in ("copy", "text", "nested-text"): + with pytest.raises(UserError, match="Cannot identify active task input"): + await _run_with_inbox(source, inbox, streamed, value=initial) + assert not model.calls + assert checked == effects == [] + return + + paused = await _run_with_inbox(source, inbox, streamed, value=initial) + assert [item.get("content") for item in model.calls[0].input if item.get("role") == "user"] == [ + restriction, + "Review the draft.", + ] + state = paused.to_state() + if serialize: + state = await RunState.from_string(source, state.to_string()) + state.approve(state.get_interruptions()[0]) + await _run_with_inbox(source, RunInbox(), streamed, value=state) + + if history_source == "earlier": + assert checked == [["Review the draft."]] + assert effects == ["published"] + else: + assert effects == [] + assert checked == [[restriction, "Review the draft."]] + assert model.calls[-1].input[-1]["output"] == "Publication blocked." + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("serialize", [False, True], ids=["in-memory", "json"]) +@pytest.mark.parametrize("history_mode", ["keep", "trim", "add-summary"]) +@pytest.mark.parametrize("drop_before_handoff", [False, True], ids=["direct", "after-drop"]) +async def test_handoff_dropping_follow_up_does_not_reauthorize_original_task( + streamed: bool, serialize: bool, history_mode: str, drop_before_handoff: bool +) -> None: + inbox = RunInbox() + hooks = AgentHooksWithTurnInput() + checked: list[list[Any]] = [] + effects: list[str] = [] + initial: list[TResponseInputItem] = [ + {"role": "user", "content": "Earlier context."}, + {"role": "user", "content": "Publish the public draft."}, + ] + summary: TResponseInputItem = {"role": "user", "content": "Review only. Do not publish."} + expected_task = [summary] if history_mode == "add-summary" else [] + # Reformatting an earlier message as input_text does not make it part of the new task. + reformatted: TResponseInputItem = { + "role": "user", + "content": [{"type": "input_text", "text": "Earlier context."}], + } + + def public_task(context: RunContextWrapper[Any], agent: AgentBase[Any]) -> bool: + return initial[-1] in context.turn_input + + @function_tool(is_enabled=public_task) + async def original_only() -> str: + effects.append("original_only") + return "done" + + @tool_input_guardrail + def check_task(data: ToolInputGuardrailData) -> ToolGuardrailFunctionOutput: + checked.append(list(data.context.turn_input)) + if initial[-1] in data.context.turn_input or ( + history_mode == "add-summary" and summary not in data.context.turn_input + ): + return ToolGuardrailFunctionOutput.allow() + return ToolGuardrailFunctionOutput.reject_content("Publication blocked.") + + @function_tool(needs_approval=True, tool_input_guardrails=[check_task]) + async def publish() -> str: + effects.append("publish") + return "done" + + model = ScriptedModel([[get_function_tool_call("publish", "{}")], [get_text_message("done")]]) + destination = Agent( + name="destination", model=model, hooks=hooks, tools=[original_only, publish] + ) + + def first_answer(call: ModelCall) -> list[Any]: + inbox.queue("Review the private draft.") + return [get_text_message("first answer")] + + def filter_input(data: HandoffInputData) -> HandoffInputData: + assert isinstance(data.input_history, tuple) + history = data.input_history + if history_mode == "trim": + history = history[1:] + elif history_mode == "add-summary": + original: Any = history[0] + original.update(reformatted) + if drop_before_handoff: + history = (*history, summary) + else: + active: Any = next( + item.raw_item for item in data.pre_handoff_items if isinstance(item, InputItem) + ) + active.update(summary) + history = (*history, active) + return data.clone(input_history=history, pre_handoff_items=()) + + def drop_follow_up(data: HandoffInputData) -> HandoffInputData: + return data.clone(pre_handoff_items=()) + + target = destination + if drop_before_handoff: + # The next filter can no longer identify the follow-up it wants to summarize. + target = Agent( + name="middle", + model=ScriptedModel([[get_handoff_tool_call(destination, args="{}")]]), + handoffs=[handoff(destination, input_filter=filter_input)], + ) + + source = Agent( + name="source", + model=ScriptedModel( + [ModelStep.respond(first_answer), [get_handoff_tool_call(target, args="{}")]] + ), + handoffs=[ + handoff(target, input_filter=drop_follow_up if drop_before_handoff else filter_input) + ], + ) + if drop_before_handoff and history_mode == "add-summary": + with pytest.raises(UserError, match="Cannot identify active task input"): + await _run_with_inbox(source, inbox, streamed, value=initial) + assert not model.calls and not checked and not effects + return + paused = await _run_with_inbox(source, inbox, streamed, value=initial) + expected_history = { + "keep": initial, + "trim": initial[1:], + "add-summary": [reformatted, initial[-1], summary], + }[history_mode] + assert [item for item in model.calls[0].input if item.get("role") == "user"] == expected_history + assert len(paused.interruptions) == 1 and checked == effects == [] + state = paused.to_state() + if serialize: + state = await RunState.from_string(source, state.to_string()) + state.approve(state.get_interruptions()[0]) + await _run_with_inbox(source, RunInbox(), streamed, value=state) + + assert effects == [] + assert hooks.captured_turn_inputs == [expected_task, expected_task] + assert [[tool.name for tool in call.tools] for call in model.calls] == [ + ["publish"], + ["publish"], + ] + assert checked == hooks.end_inputs == [expected_task] + assert model.calls[-1].input[-1]["output"] == "Publication blocked." + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize( + ("path", "case"), + [ + ("same-object", "edit-earlier"), + ("same-object", "withdraw"), + ("same-input-id", "edit-earlier"), + ("same-input-id", "withdraw"), + ("assistant-item", "withdraw"), + ("assistant-history", "withdraw"), + ("edit-before-conversion", "edit-earlier"), + ("edit-after-conversion", "edit-earlier"), + ("edit-after-conversion", "edit-active"), + ("tracked-dict", "edit-active"), + ("untracked-keep-earlier", "edit-active"), + ("untracked-drop-earlier", "edit-active"), + ("untracked-earlier", "edit-earlier"), + ("tracked-edited-copy", "edit-earlier"), + ("untracked-edited-copy", "edit-earlier"), + ("rebuild-all", "unchanged"), + ("rebuild-all", "edit-earlier"), + ("normalize-history", "edit-earlier"), + ("context-view", "edit-active"), + *[ + (path, case) + for path in ("config-mapper", "helper-mapper", "after-nesting") + for case in ("edit-earlier", "edit-active", "equal") + ], + ], +) +async def test_handoff_keeps_earlier_permission_out_of_follow_up( + streamed: bool, path: str, case: str +) -> None: + inbox = RunInbox() + restriction = "Do not publish." + earlier = ( + restriction if case in ("edit-active", "equal") else "Publish the public draft for Alice." + ) + edited = "Publish the public draft for [redacted]." + edited_copy = path in ("tracked-edited-copy", "untracked-edited-copy") + task = restriction if case == "equal" or edited_copy else "Review the private draft." + quote_as_assistant = path in ("assistant-item", "assistant-history") + if quote_as_assistant: + task = edited + keep_task = case != "withdraw" + expected_earlier = edited if case in ("edit-earlier", "withdraw") else earlier + expected_task = restriction if case == "edit-active" else task + checked: list[list[Any]] = [] + effects: list[str] = [] + + @tool_input_guardrail + def check_task(data: ToolInputGuardrailData) -> ToolGuardrailFunctionOutput: + texts = [item.get("content") for item in data.context.turn_input] + checked.append(texts) + # The policy must see the current restriction, never an earlier grant. + if edited in texts or (case in ("edit-active", "equal") and restriction not in texts): + return ToolGuardrailFunctionOutput.allow() + return ToolGuardrailFunctionOutput.reject_content("Publication blocked.") + + @function_tool(needs_approval=True, tool_input_guardrails=[check_task]) + async def publish() -> str: + effects.append("published") + return "done" + + model = ScriptedModel([[get_function_tool_call("publish", "{}")], [get_text_message("done")]]) + destination = Agent(name="destination", model=model, tools=[publish]) + + def first_answer(call: ModelCall) -> list[Any]: + inbox.queue(earlier) + inbox.queue(task) + return [get_text_message("first answer")] + + def edit_messages(items: list[TResponseInputItem]) -> list[TResponseInputItem]: + users = [item for item in items if item.get("role") == "user"] + # Keep the mapper's own objects, including when their text is identical. + prior: Any = users[0] + active: Any = users[-1] + if case == "edit-earlier": + prior["content"] = edited + elif case == "edit-active": + active["content"] = restriction + return [prior, active] + + async def edit(data: HandoffInputData) -> HandoffInputData: + if path == "helper-mapper": + return nest_handoff_history(data, history_mapper=edit_messages) + if path == "after-nesting": + nested = nest_handoff_history(data) + assert isinstance(nested.input_history, tuple) + return nested.clone(input_history=tuple(edit_messages(list(nested.input_history)))) + prior, active = [item for item in data.pre_handoff_items if isinstance(item, InputItem)] + if edited_copy: + assert isinstance(data.input_history, tuple) + message: Any = prior.raw_item + message["content"] = edited + duplicate = prior.to_input_item() if path == "tracked-edited-copy" else copy(message) + return data.clone( + input_history=(*data.input_history, message, duplicate), + pre_handoff_items=(active,), + ) + if path == "untracked-earlier": + assert isinstance(data.input_history, tuple) + rewritten: Any = copy(prior.raw_item) + rewritten["content"] = edited + return data.clone( + input_history=(*data.input_history, rewritten), pre_handoff_items=(active,) + ) + if path == "rebuild-all": + assert isinstance(data.input_history, tuple) + # Copy the entire user sequence. Editing just the earlier permission + # loses its identity even though the active text stays unchanged. + messages = edit_messages([copy(prior.raw_item), copy(active.raw_item)]) + history = (copy(data.input_history[0]), *messages) + return data.clone(input_history=history, pre_handoff_items=()) + if path in ("tracked-dict", "untracked-keep-earlier", "untracked-drop-earlier"): + # The same edit collides with the earlier text. Only the original + # dictionary identifies which task the edited message belongs to. + current = active.raw_item if path == "tracked-dict" else copy(active.raw_item) + messages = edit_messages([prior.raw_item, current]) + if path == "untracked-drop-earlier": + messages = messages[1:] + return data.clone(input_history=tuple(messages), pre_handoff_items=()) + if path == "context-view": + assert data.run_context is not None + messages = edit_messages([prior.raw_item, data.run_context.turn_input[-1]]) + return data.clone(input_history=tuple(messages), pre_handoff_items=()) + retained = (active,) if keep_task else () + if path in ("same-object", "normalize-history"): + assert isinstance(data.input_history, tuple) + history = list(data.input_history) + if path == "normalize-history": + history = ItemHelpers.input_to_new_input_list(history) + original: Any = history[0] + original["content"] = edited + return data.clone(input_history=tuple(history), pre_handoff_items=retained) + if path == "edit-before-conversion": + earlier_message: Any = prior.raw_item + earlier_message["content"] = edited + return data.clone(input_history=(prior.to_input_item(),), pre_handoff_items=retained) + if path == "edit-after-conversion": + if case == "edit-active": + messages = edit_messages([prior.to_input_item(), active.to_input_item()]) + return data.clone(input_history=tuple(messages), pre_handoff_items=()) + converted: Any = prior.to_input_item() + converted["content"] = edited + return data.clone(input_history=(converted,), pre_handoff_items=retained) + prior = replace(prior, raw_item={"role": "user", "content": edited}) + if quote_as_assistant: + # Both filters quote the same text as an assistant message. Keeping + # the InputItem ID must not keep the quote in the user's task. + quote = replace(active, raw_item={"role": "assistant", "content": task}) + earlier_message = prior.to_input_item() + if path == "assistant-history": + return data.clone( + input_history=(earlier_message, quote.to_input_item()), pre_handoff_items=() + ) + return data.clone(input_history=(earlier_message,), pre_handoff_items=(quote,)) + return data.clone(pre_handoff_items=(prior, *retained)) + + source = Agent( + name="source", + model=ScriptedModel( + [ + ModelStep.respond(first_answer), + [get_text_message("second answer")], + [get_handoff_tool_call(destination, args="{}")], + ] + ), + handoffs=[ + handoff(destination, nest_handoff_history=True) + if path == "config-mapper" + else handoff(destination, input_filter=edit) + ], + ) + initial: list[TResponseInputItem] = [ + { + "role": "user", + "content": earlier + if path in ("same-object", "normalize-history", "config-mapper", "helper-mapper") + else "Start.", + } + ] + config = RunConfig(handoff_history_mapper=edit_messages) if path == "config-mapper" else None + if path.startswith("untracked-") or (path == "rebuild-all" and case == "edit-earlier"): + with pytest.raises(UserError, match="Cannot identify active task input"): + await _run_with_inbox(source, inbox, streamed, value=initial, run_config=config) + assert not model.calls + assert not checked and not effects + return + paused = await _run_with_inbox(source, inbox, streamed, value=initial, run_config=config) + visible = [item.get("content") for item in model.calls[0].input if item.get("role") == "user"] + expected_active = [expected_task] if keep_task else [] + if quote_as_assistant: + assert [item for item in model.calls[0].input if item.get("role") == "assistant"] == [ + {"role": "assistant", "content": task} + ] + if path == "tracked-edited-copy": + assert visible == ["Start.", edited, edited, restriction] + else: + assert visible == (["Start."] if path in ("same-input-id", "rebuild-all") else []) + [ + expected_earlier, + *expected_active, + ] + state = await RunState.from_string(source, paused.to_state().to_string()) + state.approve(state.get_interruptions()[0]) + await _run_with_inbox(source, RunInbox(), streamed, value=state) + + assert effects == [] + assert checked == [expected_active] + + +@pytest.mark.parametrize("serialize", [False, True], ids=["in-memory", "json"]) +async def test_failed_handoff_filter_preserves_source_task_on_resume(serialize: bool) -> None: + inbox = RunInbox() + checked: list[list[Any]] = [] + effects: list[str] = [] + + def first_answer(call: ModelCall) -> list[Any]: + inbox.queue("Do not publish.") + return [get_text_message("first answer")] + + def edit_then_fail(data: HandoffInputData) -> HandoffInputData: + assert isinstance(data.input_history, tuple) + original: Any = data.input_history[0] + original["content"][0]["text"] = "Edited history." + task = next(item for item in data.pre_handoff_items if isinstance(item, InputItem)) + message: Any = task.raw_item + message["content"] = "Publish." + raise ValueError("filter failed") + + @tool_input_guardrail + def check_task(data: ToolInputGuardrailData) -> ToolGuardrailFunctionOutput: + texts = [item.get("content") for item in data.context.turn_input] + checked.append(texts) + if "Publish." in texts: + return ToolGuardrailFunctionOutput.allow() + return ToolGuardrailFunctionOutput.reject_content("Publication blocked.") + + @function_tool(tool_input_guardrails=[check_task]) + async def publish() -> str: + effects.append("published") + return "published" + + destination = Agent(name="destination", model=ScriptedModel([])) + model = ScriptedModel( + [ + ModelStep.respond(first_answer), + [get_handoff_tool_call(destination, args="{}")], + [get_function_tool_call("publish", "{}")], + [get_text_message("done")], + ] + ) + source = Agent( + name="source", + model=model, + tools=[publish], + handoffs=[handoff(destination, input_filter=edit_then_fail)], + ) + initial: list[TResponseInputItem] = [ + {"role": "user", "content": [{"type": "input_text", "text": "Review the draft."}]} + ] + stream = Runner.run_streamed(source, initial, inbox=inbox) + with pytest.raises(ValueError, match="filter failed"): + async for _ in stream.stream_events(): + pass + + state = stream.to_state() + if serialize: + state = await RunState.from_string(source, state.to_string()) + await Runner.run(source, state) + + assert effects == [] + assert checked == [["Do not publish."]] + assert [item.get("content") for item in model.calls[2].input if item.get("role") == "user"] == [ + [{"type": "input_text", "text": "Review the draft."}], + "Do not publish.", + ] + + +@pytest.mark.asyncio +async def test_expanding_nested_history_keeps_quoted_permission_out_of_follow_up() -> None: + inbox = RunInbox() + permission = "Publish the public draft." + task = "Review the private draft." + hooks = AgentHooksWithTurnInput() + + def first_answer(call: ModelCall) -> list[Any]: + inbox.queue(task) + return [get_text_message("Published the public draft.")] + + @function_tool( + is_enabled=lambda context, agent: any( + item.get("content") == permission for item in context.turn_input + ) + ) + async def publish() -> str: + return "published" + + model = ScriptedModel([[get_text_message("Reviewed.")]]) + destination = Agent(name="destination", model=model, hooks=hooks, tools=[publish]) + middle_model = ScriptedModel([[get_handoff_tool_call(destination, args="{}")]]) + middle = Agent( + name="middle", + model=middle_model, + handoffs=[ + handoff( + destination, + input_filter=lambda data: nest_handoff_history( + data, history_mapper=lambda items: items + ), + ) + ], + ) + source = Agent( + name="source", + model=ScriptedModel( + [ModelStep.respond(first_answer), [get_handoff_tool_call(middle, args="{}")]] + ), + handoffs=[handoff(middle, nest_handoff_history=True)], + ) + await _run_with_inbox(source, inbox, False, value=permission) + + assert any( + item.get("role") == "assistant" and permission in str(item.get("content")) + for item in middle_model.calls[0].input + ) + assert [item.get("content") for item in model.calls[0].input if item.get("role") == "user"] == [ + permission, + task, + ] + assert hooks.captured_turn_inputs == [[{"role": "user", "content": task}]] + assert not model.calls[0].tools + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("shared_id", [False, True], ids=["distinct-ids", "shared-id"]) +async def test_handoff_keeps_identical_permissions_separate_when_follow_up_is_dropped( + streamed: bool, shared_id: bool +) -> None: + inbox = RunInbox() + permission = "Publish." + initial: list[TResponseInputItem] = [{"role": "user", "content": permission}] + checked: list[list[TResponseInputItem]] = [] + effects: list[str] = [] + + @tool_input_guardrail + def check_task(data: ToolInputGuardrailData) -> ToolGuardrailFunctionOutput: + checked.append(list(data.context.turn_input)) + if initial[0] in data.context.turn_input: + return ToolGuardrailFunctionOutput.allow() + return ToolGuardrailFunctionOutput.reject_content("Publication blocked.") + + @function_tool(tool_input_guardrails=[check_task]) + async def publish() -> str: + effects.append("published") + return "done" + + def first_answer(call: ModelCall) -> list[Any]: + inbox.queue(permission) + return [get_text_message("first answer")] + + def move_both(data: HandoffInputData) -> HandoffInputData: + assert isinstance(data.input_history, tuple) + active = next(item for item in data.pre_handoff_items if isinstance(item, InputItem)) + earlier = InputItem(agent=active.agent, raw_item=data.input_history[0]) + if shared_id: + # Copying the wrapper keeps its ID even though the messages belong to different tasks. + active = replace(earlier, raw_item=active.raw_item) + return data.clone(input_history=(), pre_handoff_items=(earlier, active)) + + def drop_active(data: HandoffInputData) -> HandoffInputData: + return data.clone(pre_handoff_items=data.pre_handoff_items[:1]) + + destination = Agent( + name="destination", + model=ScriptedModel( + [[get_function_tool_call("publish", "{}")], [get_text_message("done")]] + ), + tools=[publish], + ) + middle_model = ScriptedModel([[get_handoff_tool_call(destination, args="{}")]]) + middle = Agent( + name="middle", + model=middle_model, + handoffs=[handoff(destination, input_filter=drop_active)], + ) + source = Agent( + name="source", + model=ScriptedModel( + [ModelStep.respond(first_answer), [get_handoff_tool_call(middle, args="{}")]] + ), + handoffs=[handoff(middle, input_filter=move_both)], + ) + + if shared_id: + with pytest.raises(UserError, match="active task input"): + await _run_with_inbox(source, inbox, streamed, value=initial) + assert not middle_model.calls and not checked + else: + await _run_with_inbox(source, inbox, streamed, value=initial) + assert checked == [[]] + assert not effects + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_follow_up_rejects_conflicting_handoff_copies_before_tool_execution( + streamed: bool, +) -> None: + inbox = RunInbox() + effects: list[str] = [] + + @function_tool(needs_approval=True) + async def publish() -> str: + effects.append("published") + return "done" + + destination = Agent( + name="destination", + model=ScriptedModel( + [[get_function_tool_call("publish", "{}")], [get_text_message("done")]] + ), + tools=[publish], + ) + + def first_answer(call: ModelCall) -> list[Any]: + inbox.queue("private") + return [get_text_message("first answer")] + + def filter_input(data: HandoffInputData) -> HandoffInputData: + task = data.pre_handoff_items[-1] + assert isinstance(task, InputItem) + edited = replace(task, raw_item={"role": "user", "content": "public"}) + return data.clone(pre_handoff_items=(*data.pre_handoff_items, edited)) + + source = Agent( + name="source", + model=ScriptedModel( + [ModelStep.respond(first_answer), [get_handoff_tool_call(destination, args="{}")]] + ), + handoffs=[handoff(destination, input_filter=filter_input)], + ) + with pytest.raises(UserError, match="Invalid active task input references"): + paused = await _run_with_inbox(source, inbox, streamed, value="public") + state = paused.to_state() + state.approve(state.get_interruptions()[0]) + await _run_with_inbox(source, RunInbox(), streamed, value=state) + assert effects == [] + + @pytest.mark.asyncio async def test_agent_hooks_receives_turn_input_string(): """Test that on_start receives turn_input when input is a string.""" diff --git a/tests/test_guardrails.py b/tests/test_guardrails.py index 8983ae5279..d4fb659811 100644 --- a/tests/test_guardrails.py +++ b/tests/test_guardrails.py @@ -542,6 +542,7 @@ async def slow_parallel_check( @pytest.mark.asyncio async def test_parallel_guardrail_trip_cancels_model_task(): model_started = asyncio.Event() + release_model = asyncio.Event() model_cancelled = asyncio.Event() model_finished = asyncio.Event() @@ -561,7 +562,8 @@ async def tripwire_after_model_starts( async def slow_get_response(*args, **kwargs): model_started.set() try: - await asyncio.sleep(0.02) + # Keep the request in flight until Runner handles the tripwire. + await release_model.wait() return await original_get_response(*args, **kwargs) except asyncio.CancelledError: model_cancelled.set() @@ -578,8 +580,11 @@ async def slow_get_response(*args, **kwargs): model.enqueue([get_text_message("should_not_finish")]) with patch.object(model, "get_response", side_effect=slow_get_response): - with pytest.raises(InputGuardrailTripwireTriggered): - await Runner.run(agent, "trigger guardrail") + try: + with pytest.raises(InputGuardrailTripwireTriggered): + await asyncio.wait_for(Runner.run(agent, "trigger guardrail"), timeout=3) + finally: + release_model.set() await asyncio.wait_for(model_finished.wait(), timeout=1) assert model_started.is_set() is True diff --git a/tests/test_run_inbox.py b/tests/test_run_inbox.py index ea3f5bbd94..b2c99ed506 100644 --- a/tests/test_run_inbox.py +++ b/tests/test_run_inbox.py @@ -19,11 +19,13 @@ MaxTurnsExceeded, MessageOutputItem, MessageReceipt, + ModelResponse, ModelSettings, ModelTimeoutError, OutputGuardrailTripwireTriggered, RunConfig, RunContextWrapper, + RunHooks, RunInbox, Runner, RunState, @@ -31,12 +33,14 @@ ToolExecutionConfig, ToolGuardrailFunctionOutput, ToolInputGuardrailData, + ToolOutputGuardrailData, ToolsToFinalOutputResult, UserError, function_tool, handoff, output_guardrail, tool_input_guardrail, + tool_output_guardrail, ) from agents.decorators import tool from agents.models.interface import ModelProvider @@ -1005,6 +1009,16 @@ async def publish() -> str: "boolean-position", "negative-position", "out-of-range-position", + "history-missing-items", + "history-empty", + "history-negative", + "history-boolean", + "history-duplicate", + "history-out-of-range", + "history-unsorted", + "history-non-user", + "generated-non-user", + "pending-non-user", "non-list", "older-schema", ], @@ -1052,6 +1066,14 @@ async def publish() -> str: else: item["input_id"] = first payload["task_input_refs"] = [second if invalid == "missing-item-id" else first] + elif invalid == "generated-non-user": + for history in ("generated_items", "session_items"): + for item in payload[history]: + if item.get("input_id") == first: + item["raw_item"]["role"] = "assistant" + elif invalid == "pending-non-user": + payload["pending_input"][0]["role"] = "assistant" + payload["task_input_refs"] = [0] elif invalid == "older-schema": payload["$schemaVersion"] = "1.26" payload.pop("task_input_refs", None) @@ -1062,6 +1084,25 @@ async def publish() -> str: # The older label alone is valid. It cannot carry a newer task selection. await RunState.from_json(agent, payload) payload["task_input_refs"] = [first, second] + elif invalid.startswith("history-"): + payload["original_input"] = [ + {"role": "user", "content": "Review the public draft."}, + {"role": "assistant", "content": "Which section?"}, + {"role": "user", "content": "The introduction."}, + ] + positions = { + "history-missing-items": [0], + "history-empty": [], + "history-negative": [-1], + "history-boolean": [False], + "history-duplicate": [0, 0], + "history-out-of-range": [3], + "history-unsorted": [2, 0], + "history-non-user": [1], + }[invalid] + payload["task_input_refs"] = {"history": positions, "items": []} + if invalid == "history-missing-items": + del payload["task_input_refs"]["items"] else: payload["task_input_refs"] = { "unknown-id": ["missing"], @@ -1220,6 +1261,81 @@ def respond_to_resume(call): assert request.system_instructions == ("replacement" if clear_pending else "second task") +@pytest.mark.parametrize("needs_approval", [False, True], ids=["fresh", "resumed"]) +@pytest.mark.parametrize("serialize", [False, True], ids=["in-memory", "json"]) +async def test_policy_continuation_preserves_tool_guardrails_after_stream_recovery( + needs_approval: bool, serialize: bool +) -> None: + inbox = RunInbox() + effects: list[str] = [] + + @tool_input_guardrail + def check_input(data: ToolInputGuardrailData) -> ToolGuardrailFunctionOutput: + return ToolGuardrailFunctionOutput.allow(output_info=data.context.tool_call_id) + + @tool_output_guardrail + def check_output(data: ToolOutputGuardrailData) -> ToolGuardrailFunctionOutput: + return ToolGuardrailFunctionOutput.allow(output_info=data.context.tool_call_id) + + @function_tool( + needs_approval=needs_approval, + tool_input_guardrails=[check_input], + tool_output_guardrails=[check_output], + ) + async def work() -> str: + effects.append("worked") + inbox.steer("Use the result.") + return "value" + + model = ScriptedModel( + [[function_call("work", "{}", call_id="work-1")], [assistant_message("done")]] + ) + + class Hooks(RunHooks[Any]): + async def on_llm_end( + self, context: RunContextWrapper[Any], agent: Agent[Any], response: ModelResponse + ) -> None: + if len(model.calls) == 2: + raise RuntimeError("after acceptance") + + agent = Agent( + name="worker", + model=model, + tools=[work], + tool_use_behavior="stop_on_first_tool", + hooks=AgentHooks( + final_output_policy=lambda ctx, proposal: ( + "continue" if proposal.kind == "tool" else "finish" + ) + ), + ) + config = RunConfig(tracing_disabled=True) + value: str | RunState[Any] = "start" + if needs_approval: + paused = await Runner.run(agent, value, auto_previous_response_id=True, run_config=config) + value = paused.to_state() + value.approve(value.get_interruptions()[0]) + + failed = Runner.run_streamed( + agent, value, auto_previous_response_id=True, hooks=Hooks(), inbox=inbox, run_config=config + ) + with pytest.raises(RuntimeError, match="after acceptance"): + async for _ in failed.stream_events(): + pass + + state = failed.to_state() + if serialize: + state = await RunState.from_string(agent, state.to_string()) + recovered = await Runner.run(agent, state, run_config=config) + + assert recovered.final_output == "done" + assert len(model.calls) == 2 + assert effects == ["worked"] + for result in (failed, recovered): + assert [r.output.output_info for r in result.tool_input_guardrail_results] == ["work-1"] + assert [r.output.output_info for r in result.tool_output_guardrail_results] == ["work-1"] + + @pytest.mark.parametrize("streamed", [False, True]) async def test_failed_server_request_preserves_dispatch_receipt(streamed: bool) -> None: agent, _, entered, release, _ = gate_tool() @@ -1805,7 +1921,7 @@ def work() -> str: assert outcome.retained -@pytest.mark.parametrize("pause", ["session", "filter"]) +@pytest.mark.parametrize("pause", ["answer_write", "session", "filter"]) @pytest.mark.parametrize("mode", ["propagate", "swallow", "preexisting", "uncancel"]) async def test_awaited_inbox_respects_owner_cancellation(pause: str, mode: str) -> None: if mode in ("swallow", "uncancel") and not hasattr(asyncio.Task, "cancelling"): @@ -1830,6 +1946,10 @@ class Session(SimpleListSession): async def add_items(self, items): if pause == "session" and "next" in messages(items): await pause_before_dispatch() + if pause == "answer_write" and any( + message_text(item, role="assistant") == "first" for item in items + ): + await pause_before_dispatch() await super().add_items(items) async def filter_input(data): @@ -1843,6 +1963,22 @@ def first(call): model = ScriptedModel([ModelStep.respond(first), [assistant_message("second")]]) session = Session() + config = RunConfig(tracing_disabled=True, call_model_input_filter=filter_input) + agent = Agent(name="worker", model=model) + preparations: list[str] = [] + if pause == "answer_write": + from agents.sandbox import Capability, SandboxAgent, SandboxRunConfig + from agents.testing import scripted_sandbox_session + + class ObservePreparation(Capability): + def process_context(self, context): + preparations.append("prepared") + return context + + agent = SandboxAgent( + name="worker", model=model, capabilities=[ObservePreparation(type="observe")] + ) + config.sandbox = SandboxRunConfig(session=scripted_sandbox_session()) async def run(): if mode != "propagate": @@ -1853,11 +1989,11 @@ async def run(): with pytest.raises(asyncio.CancelledError): await asyncio.sleep(0) return await Runner.run( - Agent(name="worker", model=model), + agent, "start", inbox=inbox, session=session, - run_config=RunConfig(tracing_disabled=True, call_model_input_filter=filter_input), + run_config=config, ) task = asyncio.create_task(run()) @@ -1879,8 +2015,16 @@ async def run(): assert (outcome.status, outcome.reason) == ("not_submitted", "cancelled") else: assert outcome.status == "submitted" - assert outcome.retained - wrote_input = pause == "filter" or mode != "propagate" + stopped_at_answer = pause == "answer_write" and mode in ("propagate", "swallow") + assert outcome.retained == (not stopped_at_answer) + if pause == "answer_write": + assert len(preparations) == len(model.calls) + if mode == "swallow": + assert any( + message_text(item, role="assistant") == "first" + for item in await session.get_items() + ) + wrote_input = not stopped_at_answer and (pause == "filter" or mode != "propagate") expected = ["start", "next"] if wrote_input else ["start"] assert messages(await session.get_items()) == expected finally: From c5d393a9fe647c2e8ca9399be508c5de2430ac79 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Tue, 24 Nov 2026 16:12:35 -0800 Subject: [PATCH 6/6] Include admitted steering messages in tool policy checks and approval resumes --- src/agents/run_budget.py | 5 + src/agents/run_inbox.py | 16 +- src/agents/run_internal/turn_resolution.py | 26 +-- src/agents/run_state.py | 85 ++++++--- tests/models/test_codex_run_inbox.py | 95 +++++++++- tests/test_agent_hooks.py | 15 +- tests/test_run_budget.py | 34 ++++ tests/test_run_inbox.py | 199 ++++++++++++++++++++- tests/test_tool_text_transforms.py | 32 ++-- 9 files changed, 440 insertions(+), 67 deletions(-) diff --git a/src/agents/run_budget.py b/src/agents/run_budget.py index 6e66ef2489..fcd74529c8 100644 --- a/src/agents/run_budget.py +++ b/src/agents/run_budget.py @@ -201,6 +201,11 @@ async def _admit( budget.check() budget.requests += 1 except (RunBudgetError, UserError) as error: + from .run_inbox import stop_inbox_intake + + # No further request can accept input, even while guardrails finish + # or the session saves the completed tool results. + stop_inbox_intake() if streamed_result is not None: from .run_internal.guardrails import input_guardrail_tripwire_triggered_for_stream diff --git a/src/agents/run_inbox.py b/src/agents/run_inbox.py index 33f6f81f6f..0772d48b29 100644 --- a/src/agents/run_inbox.py +++ b/src/agents/run_inbox.py @@ -133,15 +133,17 @@ class RunInbox: Use ``await receipt.wait()`` in a separate task or after the run ends if you need the submission outcome. Waiting inside a tool can block delivery. - If approval pauses a follow-up, the checkpoint identifies the active task - so guardrails see the same input after resume. It does not save the inbox - or messages still waiting in the queue. + After the SDK admits a steer, tool policies and guardrails see it in + context.turn_input alongside the task it updates. A message admitted + after an answer starts a separate task. An approval checkpoint keeps + that task's input, including its admitted steers. It does not save the + inbox or messages still waiting in the queue. Custom handoff filters should preserve message objects or InputItem IDs when editing or moving messages. This lets tool guardrails distinguish the current task from earlier requests. To replace a task with a summary, edit its message in place or keep its InputItem ID. Use steer() or queue() - to add a new instruction. If the run continues after an answer, a handoff + to add a new instruction. Once the SDK admits an inbox message, a handoff filter or sandbox context hook can rebuild messages without their original objects or IDs only if it preserves the entire sequence of user messages and the SDK can still identify each message's task. Otherwise the run @@ -308,12 +310,8 @@ def _take( return redact_items(items) def _stage(self, items: list[TResponseInputItem], run_state: RunState[Any]) -> None: - run_state._pending_input.extend(items) + run_state._stage_inbox_input(items, new_task=bool(self._pending_output)) self._retained = True - if self._pending_output: - # A follow-up starts a new task. A steer during a tool turn - # stays with the current task. Retries must keep that distinction. - run_state._task_input_ids = run_state._track_pending_input()[-len(items) :] def _admitted(self, items: list[InputItem]) -> None: if self._batch: diff --git a/src/agents/run_internal/turn_resolution.py b/src/agents/run_internal/turn_resolution.py index 0b986244a0..7ec5d7dab5 100644 --- a/src/agents/run_internal/turn_resolution.py +++ b/src/agents/run_internal/turn_resolution.py @@ -407,15 +407,16 @@ def _get_turn_input( ItemHelpers.input_to_new_input_list(original_input) if len(ids) < len(task) else [] ) keys = _user_message_keys(history) - task_input: list[TResponseInputItem] = [] - for key in task: - if isinstance(key, str): - if key in visible: - task_input.append(visible[key]) - elif keys.get(key[0]) == key[1]: - task_input.append(history[key[0]]) - else: - raise UserError("Invalid active task input references.") + positions = {ref[0]: ref[1] for ref in task if isinstance(ref, tuple)} + if any(keys.get(i) != key for i, key in positions.items()): + raise UserError("Invalid active task input references.") + include_non_user = None in task + task_input = [ + item + for i, item in enumerate(history) + if i in positions or (include_non_user and i not in keys) + ] + task_input.extend(visible[key] for key in task if isinstance(key, str) and key in visible) original_input = task_input try: return ItemHelpers.input_to_new_input_list(original_input) @@ -723,7 +724,7 @@ def __init__( self, history: str | list[TResponseInputItem], items: list[RunItem], - task: Container[str | tuple[int, str]], + task: Container[str | tuple[int, str] | None], turn_input: list[TResponseInputItem], ) -> None: self._input_ids: dict[str, _MessageOwner] = {} @@ -894,8 +895,7 @@ def rebase_context( # The first follow-up has not passed admission yet. return refs = [ref for ref, keep in zip(keys.items(), current, strict=True) if keep] - generated = (ref for ref in task if isinstance(ref, str)) - state._task_input_ids = (*refs, *generated) + state._replace_task_input_refs(refs, (ref for ref in task if isinstance(ref, str))) async def execute_handoffs( @@ -1203,7 +1203,7 @@ def nest_history( original_input[index] = source run_state._original_input = copy_input_items(original_input) run_state._generated_items = list(items) - run_state._task_input_ids = (*history_refs, *item_refs) + run_state._replace_task_input_refs(history_refs, item_refs) return SingleStepResult( original_input=original_input, diff --git a/src/agents/run_state.py b/src/agents/run_state.py index f89ef3d576..72bce949cb 100644 --- a/src/agents/run_state.py +++ b/src/agents/run_state.py @@ -8,7 +8,7 @@ import json import math from collections import deque -from collections.abc import Callable, Collection, Mapping, Sequence +from collections.abc import Callable, Collection, Iterable, Mapping, Sequence from dataclasses import dataclass, field from typing import TYPE_CHECKING, Annotated, Any, Generic, Literal, cast, get_args from uuid import uuid4 @@ -269,7 +269,7 @@ def _default_run_state_validation_error( # 3. to_json() always emits CURRENT_SCHEMA_VERSION. # 4. Forward compatibility is intentionally fail-fast (older SDKs reject newer or unsupported # versions). -CURRENT_SCHEMA_VERSION = "1.27" +CURRENT_SCHEMA_VERSION = "1.28" _PROGRAMMATIC_TOOL_CALLING_MIN_SCHEMA_VERSION = "1.13" _HOSTED_MCP_APPROVALS_MIN_SCHEMA_VERSION = "1.14" _CURRENT_RESPONSE_OWNERSHIP_MIN_SCHEMA_VERSION = "1.17" @@ -338,10 +338,10 @@ def _default_run_state_validation_error( ), "1.24": "Requires caller-supplied text redaction when resuming protected RunState snapshots.", "1.25": "Preserves required Runner budgets and consumption across approval resumes.", - # Replace the unreleased 1.26 writer. It would ignore the active task on resume. - "1.27": ( - "Preserves the active task across approval resumes and requires an exact text " - "editor when resuming selected tool calls." + # The unreleased 1.26 and 1.27 writers could omit task input on resume. + "1.28": ( + "Preserves the active task and its steers across approval resumes and requires " + "an exact text editor when resuming selected tool calls." ), } SUPPORTED_SCHEMA_VERSIONS = frozenset(SCHEMA_VERSION_SUMMARIES) @@ -882,8 +882,9 @@ def _copy_tool_approval_raw_item(raw_item: Any) -> Any: raise TypeError("Unsupported tool approval raw item") -# Follow-up message IDs, or (position, content digest) pairs after a history rewrite. -_TaskInputRef = str | tuple[int, str] +# Message IDs and (position, content digest) pairs identify user messages. +# A None entry keeps the original task's non-user context alongside them. +_TaskInputRef = str | tuple[int, str] | None _TaskInputRefs = tuple[_TaskInputRef, ...] | None @@ -959,8 +960,8 @@ class RunState(Generic[TContext, TAgent]): _pending_input: list[TResponseInputItem] = field(default_factory=list) """Input staged for admission immediately before the next resumed model call.""" - # None selects the original task. A follow-up can span history, generated - # items and pending input. Keep its references in the order seen by the agent. + # Before the first inbox admission, None selects the original input. + # A tracked task can span history, generated items and pending input. # An empty tuple means there is no visible task until new input arrives. _task_input_ids: _TaskInputRefs = field(default=None, init=False, repr=False, compare=False) # Input stays pending until the session saves it or the server acknowledges it. @@ -1184,9 +1185,13 @@ def _task_input_refs(self) -> list[str | int] | dict[str, Any] | None: visible = self._visible_task_inputs(ids, self._generated_items) items = [pending.get(key, key) for key in task if isinstance(key, str) and key in visible] history = [key for key in task if isinstance(key, tuple)] - if history: + if history or None in task: self._validate_task_history(self._original_input) - return {"history": [i for i, _ in history], "items": items} + return { + "history": [i for i, _ in history], + "items": items, + "include_non_user_history": None in task, + } return items def _restore_task_input_refs( @@ -1199,12 +1204,18 @@ def invalid() -> RunStateValidationError: return validation_error_factory("Invalid active task input references.", UserError) ids: list[_TaskInputRef] = [] - if isinstance(refs, dict) and set(refs) == {"history", "items"}: + if isinstance(refs, dict): + if set(refs) != {"history", "items", "include_non_user_history"} or not isinstance( + refs["include_non_user_history"], bool + ): + raise invalid() + if refs["include_non_user_history"]: + ids.append(None) positions = refs["history"] keys = _user_message_keys(self._original_input) if ( not isinstance(positions, list) - or not positions + or (not positions and None not in ids) or any(type(i) is not int or i not in keys for i in positions) or positions != sorted(set(positions)) ): @@ -1424,6 +1435,31 @@ def add_input(self, input: str | list[TResponseInputItem]) -> None: normalized = ItemHelpers.input_to_new_input_list(input) self._pending_input.extend(copy.deepcopy(normalized)) + def _stage_inbox_input(self, items: list[TResponseInputItem], *, new_task: bool) -> None: + """Bind guarded input to its task before a session write can fail.""" + previous = self._task_input_ids + start = len(self._pending_input) + if new_task: + previous = () + elif previous is None: + # The first mid-task steer extends the same prepared input the + # tool policy already saw, including developer and assistant context. + previous = (None, *_user_message_keys(self._original_input).items()) + elif not previous: + # A replacement staged with add_input() after withdrawal also + # belongs to the empty task, as in _track_pending_input(). + start = 0 + self._pending_input.extend(items) + added = self._track_pending_input()[start:] + self._task_input_ids = (*previous, *added) + + def _replace_task_input_refs( + self, history: list[tuple[int, str]], items: Iterable[str] + ) -> None: + """Keep the original task's context when a hook moves its user messages.""" + prefix = (None,) if None in (self._task_input_ids or ()) else () + self._task_input_ids = (*prefix, *history, *items) + def _track_pending_input(self) -> tuple[str, ...]: """Assign stable identities before storage or model dispatch can fail.""" missing = len(self._pending_input) - len(self._pending_input_ids) @@ -3048,19 +3084,24 @@ def _validate_pending_approvals( requires_budget |= budget requires_editor |= editor requires_task |= task - # A 1.26 child lacks the marker that would otherwise make its restoration mandatory. - if requires_budget or requires_editor or requires_task or state.get("$schemaVersion") == "1.26": + # Unreleased children can omit task input even when no marker is present. + if ( + requires_budget + or requires_editor + or requires_task + or state.get("$schemaVersion") in ("1.26", "1.27") + ): version = _validate_run_state_schema_version( state, validation_error_factory=validation_error_factory ) schema = tuple(map(int, version.split("."))) - if requires_task and schema < (1, 27): + if requires_task and schema < (1, 28): raise validation_error_factory( - "Active task input requires RunState schema 1.27.", UserError + "Active task input requires RunState schema 1.28.", UserError ) - if requires_editor and schema < (1, 27): + if requires_editor and schema < (1, 28): raise validation_error_factory( - "Tool text transforms require RunState schema 1.27.", UserError + "Tool text transforms require RunState schema 1.28.", UserError ) if requires_budget and schema < (1, 25): raise _BudgetCheckpointError("Run budgets require schema 1.25 or later.") @@ -6287,7 +6328,7 @@ def _clone_original_input(original_input: str | list[Any]) -> str | list[Any]: "Run state pending_input must be a list", "Missing active task input references.", "Invalid active task input references.", - "Active task input requires RunState schema 1.27.", + "Active task input requires RunState schema 1.28.", "Run state pending Session write is invalid", "Invalid tool output guardrail result boundary", "Run state tool output guardrail result boundary requires schema 1.20.", @@ -6328,7 +6369,7 @@ def _clone_original_input(original_input: str | list[Any]) -> str | list[Any]: _REQUIRED_CHILD_MISSING, "RunState tool_invocations must be a mapping.", "RunState tool_invocations contains an invalid call ID.", - "Tool text transforms require RunState schema 1.27.", + "Tool text transforms require RunState schema 1.28.", "RunState tool text transform requirement is invalid.", "RunState tool invocation must be a mapping.", "RunState tool invocation contains invalid lifecycle data.", diff --git a/tests/models/test_codex_run_inbox.py b/tests/models/test_codex_run_inbox.py index 366e9c2afa..fa246a6254 100644 --- a/tests/models/test_codex_run_inbox.py +++ b/tests/models/test_codex_run_inbox.py @@ -1,9 +1,24 @@ import asyncio import pytest +from openai import AsyncOpenAI -from agents import Agent, RunInbox, Runner +from agents import ( + Agent, + RunConfig, + RunInbox, + Runner, + ToolGuardrailFunctionOutput, + function_tool, + tool_input_guardrail, +) +from agents.models.openai_provider import OpenAIProvider +from .test_codex_mutable_tool_hooks import ( + codex_fixture, + final_message, + model_endpoint as model_endpoint, +) from .test_codex_provider import FakeThread, config, threads as threads @@ -69,3 +84,81 @@ async def send_during_request(inbox): sender.cancel() await asyncio.gather(sender, return_exceptions=True) await run_config.model_provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("harness", ["responses", "codex"]) +@pytest.mark.parametrize("streamed", [False, True], ids=["run", "streamed"]) +async def test_mid_tool_steer_reaches_next_tool_guardrail( + tmp_path, monkeypatch, model_endpoint, harness, streamed +): + # Script the wire so we can compare what the model receives with what the guardrail sees. + port, requests, replies = model_endpoint + for name in ("prepare_draft", "publish"): + replies.append({"type": "function_call", "name": name, "call_id": name, "arguments": "{}"}) + replies.append(final_message()) + original = "Prepare and publish the draft." + restriction = "Do not publish the draft." + inbox = RunInbox() + checked = [] + effects = [] + + @function_tool + async def prepare_draft() -> str: + """Prepare a draft before publication.""" + inbox.steer(restriction) + return "Draft ready." + + @tool_input_guardrail + def check_permission(data): + messages = [ + item["content"] for item in data.context.turn_input if item.get("role") == "user" + ] + checked.append(messages) + if restriction in messages: + return ToolGuardrailFunctionOutput.reject_content("Publication blocked.") + return ToolGuardrailFunctionOutput.allow() + + @function_tool(tool_input_guardrails=[check_permission]) + async def publish() -> str: + """Publish the draft.""" + effects.append("published") + return "Published." + + client = None + if harness == "codex": + provider = codex_fixture(tmp_path, port, monkeypatch) + else: + client = AsyncOpenAI( + base_url=f"http://127.0.0.1:{port}/v1", + api_key="synthetic-fixture-key", + ) + provider = OpenAIProvider(openai_client=client, use_responses=True) + agent = Agent(name="editor", model="gpt-5.4", tools=[prepare_draft, publish]) + run_config = RunConfig(model_provider=provider, tracing_disabled=True) + try: + if streamed: + stream = Runner.run_streamed(agent, original, inbox=inbox, run_config=run_config) + async for _ in stream.stream_events(): + pass + final_output = stream.final_output + else: + result = await Runner.run(agent, original, inbox=inbox, run_config=run_config) + final_output = result.final_output + assert final_output == "done" + steer = requests[1]["input"][-1] + assert steer["role"] == "user" + content = steer["content"] + assert (content if isinstance(content, str) else content[0]["text"]) == restriction + assert (checked, effects) == ([[original, restriction]], []) + assert any( + item.get("type") == "function_call_output" + and item["call_id"] == "publish" + and item["output"] == "Publication blocked." + for item in requests[2]["input"] + ) + finally: + await provider.aclose() + if client is not None: + await client.close() diff --git a/tests/test_agent_hooks.py b/tests/test_agent_hooks.py index 5f29196822..1685962eab 100644 --- a/tests/test_agent_hooks.py +++ b/tests/test_agent_hooks.py @@ -558,7 +558,7 @@ def first_answer(call: ModelCall) -> list[Any]: return [get_text_message("first answer")] def instructions(context: RunContextWrapper[Any], agent: Agent[Any]) -> str: - return str(context.turn_input[0].get("content")) + return " | ".join(str(item.get("content")) for item in context.turn_input) def enabled(context: RunContextWrapper[Any], agent: AgentBase[Any]) -> bool: return context.turn_input == second @@ -578,13 +578,14 @@ async def work() -> str: agent = Agent(name="test", model=model, hooks=hooks, tools=[work], instructions=instructions) result = await _run_with_inbox(agent, inbox, streamed, server_managed=server_managed) - assert hooks.captured_turn_inputs == hooks.end_inputs == [first, second] + assert hooks.captured_turn_inputs == [first, second] + assert hooks.end_inputs == [first, [*second, {"role": "user", "content": "clarification"}]] assert [call.system_instructions for call in model.calls] == [ "first task", "second task", - "second task", + "second task | clarification", ] - assert [bool(call.tools) for call in model.calls] == [False, True, True] + assert [bool(call.tools) for call in model.calls] == [False, True, False] all_messages = ["first task", "second task", "clarification"] for history in (result.to_input_list(), result.to_input_list(mode="normalized")): assert [ @@ -658,9 +659,9 @@ def omit_first_occurrence(data: CallModelData[Any]) -> ModelInputData: task[0], task[0], ] - assert model.calls[2].system_instructions == " | ".join(task) - assert model.calls[2].tools - assert hooks.end_inputs[-1] == expected + assert model.calls[2].system_instructions == " | ".join([*task, task[0]]) + assert not model.calls[2].tools + assert hooks.end_inputs[-1] == [*expected, expected[0]] @pytest.mark.parametrize("streamed", [False, True]) diff --git a/tests/test_run_budget.py b/tests/test_run_budget.py index 9938370c6e..d7f5ad2be8 100644 --- a/tests/test_run_budget.py +++ b/tests/test_run_budget.py @@ -821,6 +821,40 @@ def record() -> str: assert store.checkpoint(session.session_id)["status"] == "ready" +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("method", ["steer", "queue"]) +async def test_budget_stop_closes_inbox_before_checkpoint(streamed, method): + @tool + def record() -> str: + return "saved" + + store = MemoryStore() + session = await ResumableSession.create(store) + store.block_checkpoint = True + inbox = RunInbox() + model = ScriptedModel([[get_function_tool_call("record")]]) + agent = Agent(name="root", model=model, tools=[record]) + task = asyncio.create_task( + run(agent, RunBudget(max_model_calls=1), streamed, session=session, inbox=inbox) + ) + try: + # No steer is waiting when the mandatory second request exhausts the budget. + await asyncio.wait_for(store.saving.wait(), timeout=5) + with pytest.raises(UserError, match="not accepting"): + getattr(inbox, method)("too late") + finally: + store.release.set() + with pytest.raises(RunBudgetError) as error: + await asyncio.wait_for(task, timeout=5) + assert error.value.limit == "model_calls" + assert len(model.calls) == 1 + history = store.checkpoint(session.session_id)["history"] + assert [item["output"] for item in history if item.get("type") == "function_call_output"] == [ + "saved" + ] + + @pytest.mark.asyncio @pytest.mark.parametrize("session_mode", ["none", "ordinary", "durable", "failed_save"]) @pytest.mark.parametrize("protected", [False, True]) diff --git a/tests/test_run_inbox.py b/tests/test_run_inbox.py index b2c99ed506..ccb4cd3289 100644 --- a/tests/test_run_inbox.py +++ b/tests/test_run_inbox.py @@ -948,6 +948,133 @@ def omit_correction(data): await finish(task, release) +@pytest.mark.parametrize("streamed", [False, True]) +async def test_mid_task_steers_reach_tool_guardrails(streamed: bool) -> None: + inbox = RunInbox() + entered, release = asyncio.Event(), asyncio.Event() + checked: list[list[str]] = [] + effects: list[str] = [] + original = "Publish the public draft." + follow_up = "Publish the private draft." + corrections = ["Do not publish the public draft.", "Do not publish the private draft."] + + @function_tool + async def review() -> str: + entered.set() + await release.wait() + release.clear() + return "Reviewed." + + @tool_input_guardrail + def check_publication(data: ToolInputGuardrailData) -> ToolGuardrailFunctionOutput: + task = messages(data.context.turn_input) + checked.append(task) + if any(correction in task for correction in corrections): + return ToolGuardrailFunctionOutput.reject_content("Publication blocked.") + return ToolGuardrailFunctionOutput.allow() + + @function_tool(tool_input_guardrails=[check_publication]) + async def publish() -> str: + effects.append("published") + return "Published." + + @function_tool(needs_approval=True, tool_input_guardrails=[check_publication]) + async def publish_private() -> str: + effects.append("published private draft") + return "Published." + + model = ScriptedModel( + [ + [function_call("review", "{}", call_id="review-public")], + [function_call("publish", "{}", call_id="publish-public")], + [assistant_message("Public review complete.")], + [function_call("review", "{}", call_id="review-private")], + [function_call("publish_private", "{}", call_id="publish-private")], + [assistant_message("Private review complete.")], + ] + ) + agent = Agent(name="editor", model=model, tools=[review, publish, publish_private]) + run = asyncio.create_task(drive(streamed, agent, original, inbox=inbox)) + try: + await wait(entered) + entered.clear() + inbox.queue(follow_up) + first = inbox.steer(corrections[0]) + release.set() + await wait(entered) + second = inbox.steer(corrections[1]) + release.set() + paused = await asyncio.wait_for(run, 3) + finally: + await finish(run, release) + + assert first.status == second.status == "submitted" + assert messages(model.calls[1].input) == [original, corrections[0]] + assert messages(model.calls[4].input) == [original, corrections[0], follow_up, corrections[1]] + state = await RunState.from_string(agent, paused.to_state().to_string()) + state.approve(state.get_interruptions()[0]) + await drive(streamed, agent, state) + assert effects == [] + assert checked == [[original, corrections[0]], [follow_up, corrections[1]]] + for call in (model.calls[2], model.calls[5]): + assert call.input[-1]["output"] == "Publication blocked." + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("approval", [False, True], ids=["direct", "json-approval"]) +async def test_steer_preserves_mixed_initial_input_for_tool_guardrail( + streamed: bool, approval: bool +) -> None: + inbox = RunInbox() + initial = [ + {"role": "developer", "content": "Ask before publishing."}, + {"role": "assistant", "content": "The draft is ready."}, + {"role": "user", "content": "Publish it."}, + ] + correction = {"role": "user", "content": "Wait for my review."} + expected = [(item["role"], item["content"]) for item in [*initial, correction]] + checked: list[list[tuple[str, str | None]]] = [] + effects: list[str] = [] + + @function_tool + async def review() -> str: + inbox.steer(correction["content"]) + return "Reviewed." + + @tool_input_guardrail + def check_publication(data: ToolInputGuardrailData) -> ToolGuardrailFunctionOutput: + task = data.context.turn_input + checked.append( + [(item.get("role", ""), message_text(item, item.get("role", ""))) for item in task] + ) + if correction["content"] in messages(task): + return ToolGuardrailFunctionOutput.reject_content("Publication blocked.") + return ToolGuardrailFunctionOutput.allow() + + @function_tool(needs_approval=approval, tool_input_guardrails=[check_publication]) + async def publish() -> str: + effects.append("published") + return "Published." + + model = ScriptedModel( + [ + [function_call("review", "{}", call_id="review")], + [function_call("publish", "{}", call_id="publish")], + [assistant_message("Done.")], + ] + ) + agent = Agent(name="editor", model=model, tools=[review, publish]) + result = await drive(streamed, agent, initial, inbox=inbox) + if approval: + assert checked == effects == [] + state = await RunState.from_string(agent, result.to_state().to_string()) + state.approve(state.get_interruptions()[0]) + await drive(streamed, agent, state) + assert checked == [expected] + assert effects == [] + assert model.calls[-1].input[-1]["output"] == "Publication blocked." + + @pytest.mark.parametrize("streamed", [False, True]) @pytest.mark.parametrize("serialize", [False, True], ids=["in-memory", "json"]) async def test_approved_tool_guardrail_checks_follow_up_after_resume( @@ -1010,6 +1137,8 @@ async def publish() -> str: "negative-position", "out-of-range-position", "history-missing-items", + "history-missing-context-flag", + "history-invalid-context-flag", "history-empty", "history-negative", "history-boolean", @@ -1078,9 +1207,15 @@ async def publish() -> str: payload["$schemaVersion"] = "1.26" payload.pop("task_input_refs", None) # The intermediate writer omitted follow-up identity. It cannot resume safely. + with pytest.raises(UserError, match="schema version is not supported"): + await RunState.from_json(agent, payload) + # The 1.27 writer could identify a follow-up but omit a later steer. + payload["$schemaVersion"] = "1.27" + payload["task_input_refs"] = [first] with pytest.raises(UserError, match="schema version is not supported"): await RunState.from_json(agent, payload) payload["$schemaVersion"] = "1.25" + payload.pop("task_input_refs") # The older label alone is valid. It cannot carry a newer task selection. await RunState.from_json(agent, payload) payload["task_input_refs"] = [first, second] @@ -1092,6 +1227,8 @@ async def publish() -> str: ] positions = { "history-missing-items": [0], + "history-missing-context-flag": [0], + "history-invalid-context-flag": [0], "history-empty": [], "history-negative": [-1], "history-boolean": [False], @@ -1100,9 +1237,17 @@ async def publish() -> str: "history-unsorted": [2, 0], "history-non-user": [1], }[invalid] - payload["task_input_refs"] = {"history": positions, "items": []} + payload["task_input_refs"] = { + "history": positions, + "items": [], + "include_non_user_history": False, + } if invalid == "history-missing-items": del payload["task_input_refs"]["items"] + elif invalid == "history-missing-context-flag": + del payload["task_input_refs"]["include_non_user_history"] + elif invalid == "history-invalid-context-flag": + payload["task_input_refs"]["include_non_user_history"] = 1 else: payload["task_input_refs"] = { "unknown-id": ["missing"], @@ -1195,6 +1340,58 @@ def respond_to_resume(call): assert await receipt.wait() == outcome +@pytest.mark.parametrize("clear_pending", [False, True], ids=["retained", "cleared"]) +async def test_steer_after_failed_session_append_preserves_original_task( + clear_pending: bool, +) -> None: + correction = "Wait for my review." + + class Session(SimpleListSession): + failed = False + + async def add_items(self, items): + if not self.failed and correction in messages(items): + self.failed = True + raise RuntimeError("correction append failed") + await super().add_items(items) + + @function_tool + async def review() -> str: + return "Reviewed." + + session = Session() + model = ScriptedModel( + [[function_call("review", "{}", call_id="review")], [assistant_message("Done.")]] + ) + agent = Agent( + name="editor", + model=model, + tools=[review], + instructions=lambda ctx, agent: " | ".join(messages(ctx.turn_input)), + ) + original = "Publish the draft." + stream = Runner.run_streamed( + agent, original, session=session, run_config=RunConfig(tracing_disabled=True) + ) + receipt = stream.steer(correction) + with pytest.raises(RuntimeError, match="correction append failed"): + async for _ in stream.stream_events(): + pass + outcome = await receipt.wait() + assert outcome.status == "not_submitted" and outcome.retained + state = stream.to_state() + assert messages(state.pending_input) == [correction] + if clear_pending: + state.clear_pending_input() + state = await RunState.from_string(agent, state.to_string()) + await drive(False, agent, state, session=session) + expected = [original] if clear_pending else [original, correction] + assert messages(model.calls[-1].input) == expected + assert model.calls[-1].system_instructions == " | ".join(expected) + assert messages(await session.get_items()) == expected + assert await receipt.wait() == outcome + + @pytest.mark.parametrize("resume_streamed", [False, True]) @pytest.mark.parametrize("clear_pending", [False, True], ids=["retained", "cleared"]) async def test_resume_after_stream_filter_failure_respects_pending_task_input( diff --git a/tests/test_tool_text_transforms.py b/tests/test_tool_text_transforms.py index a157fef704..1a8e56d9a5 100644 --- a/tests/test_tool_text_transforms.py +++ b/tests/test_tool_text_transforms.py @@ -940,13 +940,13 @@ async def edit(call, texts): config = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=[(report, edit)])) paused = await Runner.run(agent, "go", run_config=config) snapshot = paused.to_state().to_json() - assert snapshot["$schemaVersion"] == "1.27" + assert snapshot["$schemaVersion"] == "1.28" snapshot["$schemaVersion"] = historical - with pytest.raises(UserError, match="require RunState schema 1.27"): + with pytest.raises(UserError, match="require RunState schema 1.28"): await RunState.from_json(agent, snapshot) del snapshot["context"]["tool_invocations"]["one"]["requires_text_transform"] state = await RunState.from_json(agent, snapshot) - assert not effects and state.to_json()["$schemaVersion"] == "1.27" + assert not effects and state.to_json()["$schemaVersion"] == "1.28" state.approve(state.get_interruptions()[0]) result = await Runner.run(agent, state, run_config=config) assert effects == [True] and RAW not in result.to_state().to_string() @@ -981,14 +981,18 @@ def report(): await RunState.from_json(parent, snapshot) assert not effects - # A 1.26 child has no task references to trigger the required-child check. - snapshot = paused.to_state().to_json() - nested = snapshot["last_processed_response"]["functions"][0]["agent_run_state"] - nested["$schemaVersion"] = "1.26" - del nested["task_input_refs"] - with pytest.raises(UserError, match="schema version is not supported"): - await RunState.from_json(parent, snapshot) - assert not effects + # Intermediate writers could omit a follow-up or a mid-task steer. + for version in ("1.26", "1.27"): + snapshot = paused.to_state().to_json() + nested = snapshot["last_processed_response"]["functions"][0]["agent_run_state"] + nested["$schemaVersion"] = version + if version == "1.26": + del nested["task_input_refs"] + else: + nested["task_input_refs"] = None + with pytest.raises(UserError, match="schema version is not supported"): + await RunState.from_json(parent, snapshot) + assert not effects state = await RunState.from_json(parent, paused.to_state().to_json()) state.approve(state.get_interruptions()[0]) @@ -1116,12 +1120,12 @@ def configure(settings): if route == "child": snapshot = paused.to_state().to_json() child = snapshot["last_processed_response"]["functions"][0]["agent_run_state"] - assert child["$schemaVersion"] == snapshot["$schemaVersion"] == "1.27" + assert child["$schemaVersion"] == snapshot["$schemaVersion"] == "1.28" for node in (child, snapshot): node["$schemaVersion"] = "1.25" - with pytest.raises(UserError, match="require RunState schema 1.27"): + with pytest.raises(UserError, match="require RunState schema 1.28"): await RunState.from_json(agent, snapshot) - node["$schemaVersion"] = "1.27" + node["$schemaVersion"] = "1.28" assert not effects saved = store.records[session.session_id]