diff --git a/examples/model_providers/mid_run_steering.py b/examples/model_providers/mid_run_steering.py new file mode 100644 index 0000000000..1c8b32ec9d --- /dev/null +++ b/examples/model_providers/mid_run_steering.py @@ -0,0 +1,71 @@ +"""Change a flight search in progress, then ask a separate follow-up. + +Run with Python's default provider or pass --codex to use CodexProvider. +The flight data is fictional. Both providers use a live model. +""" + +import argparse +import asyncio + +from agents import Agent, ItemHelpers, MessageReceipt, RunConfig, Runner +from agents.decorators import tool +from agents.models.codex import CodexProvider + + +async def main(use_codex: bool) -> None: + search_started = asyncio.Event() + finish_search = asyncio.Event() + + @tool + async def search_flights() -> str: + """Search for flights from Seattle to Boston. Prices are per person.""" + search_started.set() + await finish_search.wait() + return "Flight A: $220, one stop. Flight B: $310, nonstop. Flight C: $350, nonstop." + + agent = Agent( + name="Flight assistant", + instructions="Call search_flights once. Use its results for the search and follow-ups.", + tools=[search_flights], + ) + config = RunConfig(model_provider=CodexProvider()) if use_codex else RunConfig() + try: + stream = Runner.run_streamed( + agent, "Find flights from Seattle to Boston.", run_config=config + ) + + async def simulate_ui() -> tuple[MessageReceipt, MessageReceipt]: + # A real UI sends each message from its own event handler. + await search_started.wait() + try: + steering = stream.steer("Only show nonstop flights.") + follow_up = stream.queue("What would two seats on the cheapest nonstop cost?") + return steering, follow_up + finally: + finish_search.set() + + ui = asyncio.create_task(simulate_ui()) + try: + # The stream shows both answers. At the end, stream.final_output holds the last one. + async for event in stream.stream_events(): + if ( + event.type == "run_item_stream_event" + and event.item.type == "message_output_item" + ): + print(ItemHelpers.text_message_output(event.item)) + if search_started.is_set(): + steering, follow_up = await ui + print("Steering:", steering.status) + print("Follow-up:", follow_up.status) + finally: + # The run can finish without calling the search tool. + ui.cancel() + await asyncio.gather(ui, return_exceptions=True) + finally: + 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 27845e1447..0c6289381c 100644 --- a/src/agents/__init__.py +++ b/src/agents/__init__.py @@ -150,6 +150,7 @@ RunErrorHandlerResult, RunErrorHandlers, ) +from .run_inbox import MessageOutcome, MessageReceipt, RunInbox from .run_state import RunState from .stream_events import ( AgentUpdatedStreamEvent, @@ -520,6 +521,9 @@ def enable_verbose_stdout_logging() -> None: "RunBudget", "RunBudgetError", "RunConfig", + "RunInbox", + "MessageOutcome", + "MessageReceipt", "OutputGuardrailBlockedMessageArgs", "OutputGuardrailBlockedMessageFormatter", "ToolNameCollisionPolicy", 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 ad1744c28e..fadd2952d8 100644 --- a/src/agents/result.py +++ b/src/agents/result.py @@ -21,6 +21,7 @@ InputGuardrailTripwireTriggered, MaxTurnsExceeded, RunErrorDetails, + UserError, _await_data_redacted_error_boundary, _detach_data_redacted_error_traceback, _is_error_data_redacted, @@ -29,6 +30,7 @@ ) from .guardrail import InputGuardrailResult, OutputGuardrailResult from .items import ( + InputItem, ItemHelpers, ModelResponse, RunItem, @@ -38,6 +40,7 @@ ) from .logger import log_tool_action_warning, logger from .run_context import RunContextWrapper +from .run_inbox import MessageReceipt, RunInbox from .run_internal._approved_output import Approve, ApprovedOutput from .run_internal.items import ( NestedHistoryOwnedItemRef, @@ -52,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 @@ -136,6 +139,23 @@ def _populate_state_from_result( else: state._generated_items = result.new_items state._session_items = list(result.new_items) + source_state = getattr(result, "_state", None) + state._pending_input_ids = ( + source_state._pending_input_ids + if isinstance(source_state, RunState) + else result._pending_input_ids_for_state + ) + if state._pending_input_ids: + # A stream can fail between staging input and receiving a response. + # Keep those occurrences only in pending_input so a retry sends each + # once and clear_pending_input() really withdraws them. + pending = set(state._pending_input_ids) + + def acknowledged(item: RunItem) -> bool: + return not isinstance(item, InputItem) or item.input_id not in pending + + state._generated_items = [item for item in state._generated_items if acknowledged(item)] + state._session_items = [item for item in state._session_items if acknowledged(item)] snapshot_refs = _state_snapshot_owned_item_refs(result, state._original_input) live_refs = rebase_nested_history_owned_item_refs( state._original_input, @@ -155,10 +175,10 @@ def _populate_state_from_result( state._conversation_id = conversation_id state._previous_response_id = previous_response_id state._auto_previous_response_id = auto_previous_response_id - source_state = getattr(result, "_state", None) if isinstance(source_state, RunState): state._generated_prompt_cache_key = source_state._generated_prompt_cache_key state._pending_input = copy.deepcopy(source_state._pending_input) + state._task_input_ids = source_state._task_input_ids state._pending_session_write = copy.deepcopy(source_state._pending_session_write) state._current_step = source_state._current_step if isinstance(source_state._current_step, NextStepInterruption): @@ -166,12 +186,37 @@ def _populate_state_from_result( # normal resume write. Keep the checkpoint's publication boundary so # recovery does not mistake those outputs for already persisted work. state._session_items = list(source_state._session_items) + if source_state._current_step.response_accepted: + from .run_internal.blocked_output import _synchronize_accepted_run_state + + # Hooks and tools can fail after server acceptance. Resume from + # the checkpoint that owns any committed effects, even if the + # stream has not published them. A response that failed validation + # must still have no processed response. + _synchronize_accepted_run_state( + state, + generated_items=source_state._generated_items, + session_items=source_state._session_items, + model_responses=source_state._model_responses, + tool_input_guardrail_results=source_state._tool_input_guardrail_results, + tool_output_guardrail_results=source_state._tool_output_guardrail_results, + current_turn=source_state._current_turn, + ) + state._current_step = replace(source_state._current_step) + state._last_processed_response = source_state._last_processed_response + state._generated_items_last_processed_marker = ( + source_state._generated_items_last_processed_marker + ) + state._conversation_id = source_state._conversation_id + state._previous_response_id = source_state._previous_response_id + state._auto_previous_response_id = source_state._auto_previous_response_id # A streamed result exists before its terminal append does, so a checkpoint taken from a # failed stream has to keep the fail-closed marker or it would look resumable. state._terminal_unrecoverable = source_state._terminal_unrecoverable else: state._generated_prompt_cache_key = getattr(result, "_generated_prompt_cache_key", None) state._pending_input = copy.deepcopy(getattr(result, "_pending_input_for_state", [])) + state._task_input_ids = result._task_input_ids_for_state state._pending_session_write = copy.deepcopy( getattr(result, "_pending_session_write", None) ) @@ -406,6 +451,21 @@ class RunResultBase(abc.ABC): context_wrapper: RunContextWrapper[Any] """The context wrapper for the agent run.""" + _previous_outputs: tuple[Any, ...] = field(default=(), init=False, repr=False, compare=False) + + @property + def previous_outputs(self) -> tuple[Any, ...]: + """Earlier answers, in order, when an inbox message started another turn. + + The last answer is final_output. These values belong to the caller. A tool + callback can return an answer that never appears in the model's transcript. + Runner copies answer data using Python's copy protocol. Private attributes + on Pydantic models remain shared with the original answer. + Runner does not copy this tuple into messages, sessions, or saved run state. + Existing records, such as output guardrail results, may contain the same values. + """ + return self._previous_outputs + _redact_text: Callable[[str], str] | None = field( default_factory=current_redactor, init=False, repr=False, compare=False ) @@ -437,6 +497,12 @@ class RunResultBase(abc.ABC): 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: _TaskInputRefs = field( + default=None, init=False, repr=False, compare=False + ) + _pending_input_ids_for_state: tuple[str, ...] = field( + default=(), init=False, repr=False, compare=False + ) _pending_session_write: _PendingSessionWrite | None = field( default=None, init=False, repr=False ) @@ -802,6 +868,7 @@ class RunResultStreaming(RunResultBase): ) def __post_init__(self, _run_impl_task: asyncio.Task[Any] | None) -> None: + self._inbox: RunInbox | None = None self._approved_output: ApprovedOutput | None = None self._stream_started = False self._display_driver: asyncio.Task[None] | None = None @@ -973,6 +1040,35 @@ def run_loop_exception(self) -> BaseException | None: _detach_data_redacted_error_traceback(error) return error + def steer(self, text: str) -> MessageReceipt: + """Guide this task after the current model request and its tools finish. + + 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") + return self._inbox.steer(text) + + def queue(self, text: str) -> MessageReceipt: + """Run a follow-up after this task finishes successfully. + + 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") + return self._inbox.queue(text) + def cancel(self, mode: Literal["immediate", "after_turn"] = "immediate") -> None: """Cancel the streaming run. @@ -996,11 +1092,15 @@ def cancel(self, mode: Literal["immediate", "after_turn"] = "immediate") -> None # result.cancel() # Immediate (default) ``` - Note: After calling cancel(), you should continue consuming stream_events() - to allow the cancellation to complete properly. + You can escalate an after_turn cancellation to immediate. Once you request + immediate cancellation, later after_turn requests have no effect. + Continue consuming stream_events() to let cancellation finish. """ - # Store the cancel mode for the background task to check + if self._cancel_mode == "immediate" and mode == "after_turn": + return self._cancel_mode = mode + if self._inbox is not None: + self._inbox._stop_accepting() if self._approved_output is not None: self._approved_output.interrupt_preview() diff --git a/src/agents/run.py b/src/agents/run.py index cb033430d3..3eca7a996a 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 @@ -16,6 +17,7 @@ require_clean, require_clean_agent, require_clean_final_output, + set_final_output_item, ) from .agent import Agent from .agent_tool_state import set_agent_tool_state_scope @@ -81,7 +83,7 @@ ) from .run_context import RunContextWrapper, TContext from .run_error_handlers import RunErrorHandlers -from .run_internal.agent_bindings import bind_public_agent +from .run_inbox import RunInbox, current_inbox, inbox_scope, stop_inbox_intake from .run_internal.agent_runner_helpers import ( append_model_response_if_new, apply_resumed_conversation_settings, @@ -133,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, @@ -145,10 +146,12 @@ from .run_internal.run_grouping import resolve_run_grouping_id from .run_internal.run_loop import ( _safe_redacted_persistence_error, + _stop_inbox_for_terminal_step, _ToolTaskCancellation, 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, @@ -322,6 +325,7 @@ async def run( hooks: RunHooks[TContext] | None = None, run_config: RunConfig | dict[str, Any] | None = None, error_handlers: RunErrorHandlers[TContext] | None = None, + inbox: RunInbox | None = None, previous_response_id: str | None = None, auto_previous_response_id: bool = False, conversation_id: str | None = None, @@ -334,7 +338,7 @@ async def run( 1. The agent is invoked with the given input. 2. If there is a final output (i.e. the agent produces something of type - `agent.output_type`), the loop terminates. + `agent.output_type`), the loop finishes unless user messages are waiting. 3. If there's a handoff, we run the loop again, with the new agent. 4. Else, we run tool calls (if any), and re-run the loop. @@ -345,7 +349,7 @@ async def run( e.g. InputGuardrailTripwireTriggered or OutputGuardrailTripwireTriggered. Note: - Only the first agent's input guardrails are run. + The starting agent checks the initial input. The active agent checks each inbox batch. Args: starting_agent: The starting agent to run. @@ -373,6 +377,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. + inbox: An optional RunInbox for steering the current task or queuing follow-ups. Returns: A run result containing all the inputs, guardrail results and the output of @@ -383,9 +388,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, @@ -396,6 +399,9 @@ async def run( conversation_id=conversation_id, session=session, ) + if inbox is not None: + return await runner.run(starting_agent, input, inbox=inbox, **options) + return await runner.run(starting_agent, input, **options) except BaseException as error: if not _is_error_data_redacted(error): raise @@ -412,6 +418,8 @@ async def run( auto_previous_response_id = cast(Any, None) conversation_id = None session = cast(Any, None) + options = RunOptions() + inbox = None runner = cast(Any, None) assert redacted_error is not None _raise_data_redacted_error(redacted_error) @@ -535,10 +543,14 @@ def run_streamed( session: Session | ResumableSession | None = None, *, error_handlers: RunErrorHandlers[TContext] | None = None, + inbox: RunInbox | None = None, ) -> RunResultStreaming: """ Run a workflow starting at the given agent in streaming mode. + Call result.steer(text) to guide the current task or result.queue(text) to + start a follow-up after it finishes. Both methods work in Python and Codex modes. + The returned result object contains a method you can use to stream semantic events as they are generated. @@ -546,7 +558,7 @@ def run_streamed( 1. The agent is invoked with the given input. 2. If there is a final output (i.e. the agent produces something of type - `agent.output_type`), the loop terminates. + `agent.output_type`), the loop finishes unless user messages are waiting. 3. If there's a handoff, we run the loop again, with the new agent. 4. Else, we run tool calls (if any), and re-run the loop. @@ -557,7 +569,7 @@ def run_streamed( e.g. InputGuardrailTripwireTriggered or OutputGuardrailTripwireTriggered. Note: - Only the first agent's input guardrails are run. + The starting agent checks the initial input. The active agent checks each inbox batch. Args: starting_agent: The starting agent to run. @@ -578,6 +590,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. + inbox: An optional RunInbox for steering the current task or queuing follow-ups. Returns: A result object that contains data about the run, as well as a method to @@ -585,9 +598,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, @@ -598,6 +609,9 @@ def run_streamed( conversation_id=conversation_id, session=session, ) + if inbox is not None: + return runner.run_streamed(starting_agent, input, inbox=inbox, **options) + return runner.run_streamed(starting_agent, input, **options) def _prepare_private_input( @@ -660,8 +674,12 @@ async def run( self, starting_agent: Agent[TContext], input: str | list[TResponseInputItem] | RunState[TContext], + *, + inbox: RunInbox | None = None, **kwargs: Unpack[RunOptions[TContext]], ) -> RunResult: + if inbox is not None: + inbox._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")) @@ -669,6 +687,9 @@ 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: + if inbox is not None: + inbox._bind(owner=asyncio.current_task()) + trace_stack.enter_context(inbox_scope(inbox)) 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) @@ -707,15 +728,24 @@ async def run( require_clean_final_output( result.final_output, result.input, result.new_items ) + if inbox is not None: + inbox._check_final_output(result.final_output) + result._previous_outputs = inbox._previous_outputs if isinstance(session, ResumableRun): await session.finish(result) + if inbox is not None and result.interruptions: + inbox._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 inbox is not None: + inbox._end_reason = "run_failed" redacted_error = error finally: + if inbox is not None: + inbox._stop_accepting() if owns_model_provider: await _close_runner_owned_model_provider(run_config.model_provider) @@ -952,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) @@ -991,6 +1011,10 @@ async def _run_impl( if isinstance(session, ResumableRun): session.bind_state(run_state) + inbox = current_inbox() + if inbox is not None and is_resumed_state: + inbox._started = 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 @@ -1050,6 +1074,8 @@ def _finalize_result(result: RunResult) -> RunResult: run_state._generated_prompt_cache_key ) finalized_result._pending_input_for_state = run_state.pending_input + finalized_result._task_input_ids_for_state = run_state._task_input_ids + finalized_result._pending_input_ids_for_state = run_state._pending_input_ids finalized_result._current_step_for_state = run_state._current_step finalized_result._nested_history_owned_session_item_refs = list( run_state._nested_history_owned_session_item_refs @@ -1081,6 +1107,9 @@ def _commit_pending_server_response( run_state=run_state, tracker=server_conversation_tracker, admission_items=pending_input_admission_items, + prior_responses=model_responses, + tool_input_guardrail_results=tool_input_guardrail_results, + tool_output_guardrail_results=tool_output_guardrail_results, generated_items=generated_items, session_items=session_items, model_response=model_response, @@ -1129,6 +1158,23 @@ def _mark_response_hooks_started() -> None: ) sandbox_runtime.assert_agent_supported(current_agent) should_run_agent_start_hooks = True + + def _start_inbox_turn(step: NextStepFinalOutput) -> bool: + nonlocal should_run_agent_start_hooks + if ( + inbox is None + or step.is_error_handler_output + or not inbox._advance(current_turn, max_turns, context_wrapper._budget) + ): + return False + require_clean_final_output(step.output, original_input, session_items) + inbox._stage_output(step.output) + set_final_output_item(None) + should_run_agent_start_hooks = True + if run_state is not None: + run_state._current_step = NextStepRunAgain() + return True + store_setting = current_agent.model_settings.resolve( run_config.model_settings ).store @@ -1222,32 +1268,20 @@ def _mark_response_hooks_started() -> None: 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 @@ -1339,6 +1373,7 @@ def _mark_response_hooks_started() -> None: error_handlers=error_handlers, ) + _stop_inbox_for_terminal_step(turn_result) store_setting = resumed_response_store( run_state, turn_result.model_response.response_id, store_setting ) @@ -1457,6 +1492,7 @@ def _mark_response_hooks_started() -> None: model_responses=model_responses, current_agent=current_agent, input_guardrail_results=input_guardrail_results, + output_guardrail_results=output_guardrail_results, tool_input_guardrail_results=tool_input_guardrail_results, tool_output_guardrail_results=tool_output_guardrail_results, context_wrapper=context_wrapper, @@ -1506,6 +1542,7 @@ def _mark_response_hooks_started() -> None: except _blocked_output_errors( turn_result.next_step.continue_after_guardrails ) as exc: + stop_inbox_intake() if ( not turn_result.next_step.continue_after_guardrails and not _is_terminal_tool_output_response( @@ -1577,6 +1614,7 @@ def _mark_response_hooks_started() -> None: ) from None raise except (Exception, asyncio.CancelledError) as guardrail_error: + stop_inbox_intake() if retry_terminal_output: # Keep accepted execution private and retryable until # the final guardrails permit delivery. @@ -1651,6 +1689,8 @@ def _mark_response_hooks_started() -> None: pending_feedback = turn_result.feedback run_state._current_step = NextStepRunAgain() continue + if _start_inbox_turn(turn_result.next_step): + continue if session is None: take_held_session_write(run_state) current_step = getattr(run_state, "_current_step", None) @@ -1702,7 +1742,12 @@ 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 = ( + inbox._take(current_turn, max_turns, context_wrapper._budget) + if inbox is not None + else [] + ) + pending_input = run_state.pending_input + deepcopy(live_input) if pending_input: pending_guardrails = current_agent.input_guardrails + ( run_config.input_guardrails or [] @@ -1718,6 +1763,9 @@ def _mark_response_hooks_started() -> None: finally: run_state._input_guardrail_results = list(input_guardrail_results) + if live_input and inbox is not None: + inbox._check_owner_cancellation() + inbox._stage(live_input, run_state) admission_items = await admit_pending_input( run_state=run_state, agent=current_agent, @@ -1733,12 +1781,18 @@ def _mark_response_hooks_started() -> None: pending_input_admission_items = [ item for item in admission_items if isinstance(item, InputItem) ] + if inbox is not None: + inbox._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) + if inbox is not None: + inbox._begin_turn() current_turn += 1 feedback, pending_feedback = pending_feedback, None if max_turns is not None and current_turn > max_turns: + if inbox is not None: + inbox._stop_accepting() _error_tracing.attach_error_to_span( current_span, SpanError( @@ -1894,12 +1948,6 @@ async def _save_max_turns_handler_output( ), ) - items_for_model = ( - pending_server_items - if server_conversation_tracker is not None and pending_server_items - else generated_items - ) - turn_usage_start = snapshot_usage(context_wrapper.usage) current_turn_span = ( turn_span( @@ -1950,7 +1998,8 @@ def on_tool_error_selected() -> None: current_turn=current_turn, bindings=current_bindings, original_input=original_input, - generated_items=items_for_model, + generated_items=generated_items, + pending_server_items=pending_server_items, session_items=session_items, hooks=hooks, context_wrapper=context_wrapper, @@ -2060,7 +2109,8 @@ def on_tool_error_selected() -> None: current_turn=current_turn, bindings=current_bindings, original_input=original_input, - generated_items=items_for_model, + generated_items=generated_items, + pending_server_items=pending_server_items, session_items=session_items, hooks=hooks, context_wrapper=context_wrapper, @@ -2148,7 +2198,8 @@ def on_tool_error_selected() -> None: ) current_turn_span.finish(reset_current=True) - # Start hooks should only run on the first turn unless reset by a handoff. + _stop_inbox_for_terminal_step(turn_result) + # Start hooks run once per task, and again after a handoff. last_saved_input_snapshot_for_rewind = None should_run_agent_start_hooks = False @@ -2168,6 +2219,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 = ( @@ -2279,6 +2334,7 @@ def on_tool_error_selected() -> None: except _blocked_output_errors( turn_result.next_step.continue_after_guardrails ) as exc: + stop_inbox_intake() if ( not turn_result.next_step.continue_after_guardrails and not _is_terminal_tool_output_response( @@ -2342,6 +2398,7 @@ def on_tool_error_selected() -> None: ) from None raise except (Exception, asyncio.CancelledError) as guardrail_error: + stop_inbox_intake() if not isinstance( guardrail_error, asyncio.CancelledError ) or not _is_terminal_tool_output_response( @@ -2397,6 +2454,8 @@ def on_tool_error_selected() -> None: if run_state is not None: run_state._current_step = NextStepRunAgain() continue + if _start_inbox_turn(turn_result.next_step): + continue if session is None and run_state is not None: # A detached completion has no Session to settle against @@ -2540,6 +2599,7 @@ def on_tool_error_selected() -> None: model_responses=model_responses, current_agent=current_agent, input_guardrail_results=input_guardrail_results, + output_guardrail_results=output_guardrail_results, tool_input_guardrail_results=tool_input_guardrail_results, tool_output_guardrail_results=tool_output_guardrail_results, context_wrapper=context_wrapper, @@ -2628,6 +2688,8 @@ def on_tool_error_selected() -> None: ) raise finally: + if inbox is not None: + inbox._stop_accepting() await cleanup_models_after_run(tool_use_tracker) try: try: @@ -2686,6 +2748,8 @@ def run_sync( ) -> RunResult: redacted_error: BaseException | None = None redacted_source: BaseException | None + if "inbox" in kwargs: + raise TypeError("run_sync does not accept inbox. Use run or run_streamed.") try: return self._run_sync_impl(starting_agent, input, **kwargs) except BaseException as error: @@ -2804,6 +2868,8 @@ def run_streamed( self, starting_agent: Agent[TContext], input: str | list[TResponseInputItem] | RunState[TContext], + *, + inbox: RunInbox | None = None, **kwargs: Unpack[RunOptions[TContext]], ) -> RunResultStreaming: context = kwargs.get("context") @@ -2814,6 +2880,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") + if inbox is None: + inbox = RunInbox() + inbox._reserve() session = prepare_run_session(kwargs.get("session"), input) run_config, owns_model_provider = _normalize_run_config_for_runner(run_config) @@ -2878,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, @@ -3076,6 +3135,7 @@ async def run_loop() -> None: async def stream() -> None: with ( + inbox_scope(inbox), redaction_scope(run_config.redact_text), operation_tracing_scope( run_config.tracing, run_config.trace_include_sensitive_data @@ -3138,9 +3198,29 @@ async def stream() -> None: sandbox_runtime=sandbox_runtime, ) + if streamed_result.interruptions: + inbox._end_reason = "approval_pause" + elif isinstance(streamed_result._stored_exception, InputGuardrailTripwireTriggered): + inbox._end_reason = "guardrail" + elif streamed_result._stored_exception is not None: + inbox._end_reason = "run_failed" + elif streamed_result._cancel_mode != "none": + inbox._end_reason = "cancelled" + + # The caller can send messages as soon as run_streamed returns. + streamed_result._inbox = inbox + inbox._bind() # 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) + producer = _await_data_redacted_error_boundary(run_loop) + try: + streamed_result.run_loop_task = asyncio.create_task(producer) + except BaseException: + inbox._close("run_failed") + producer.close() + raise + # A task cancelled before its first instruction never enters inbox_scope. + streamed_result.run_loop_task.add_done_callback( + lambda task: inbox._close("cancelled") if task.cancelled() else None ) if owns_model_provider: model_provider = run_config.model_provider 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 new file mode 100644 index 0000000000..0772d48b29 --- /dev/null +++ b/src/agents/run_inbox.py @@ -0,0 +1,464 @@ +"""Run-local input for an already active asynchronous Runner invocation.""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +from collections import deque +from collections.abc import Mapping, Sequence, Set +from contextlib import contextmanager +from contextvars import ContextVar +from copy import deepcopy +from dataclasses import dataclass, fields, is_dataclass +from typing import TYPE_CHECKING, Any, Literal +from uuid import uuid4 + +from pydantic import BaseModel + +from .exceptions import InputGuardrailTripwireTriggered, UserError +from .run_budget import RunBudgetError, _BudgetState + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + from .items import InputItem, TResponseInputItem + from .run_internal.oai_conversation import OpenAIServerConversationTracker + from .run_state import RunState + +__all__ = ["RunInbox", "MessageReceipt", "MessageOutcome"] + + +def _snapshot_answer(answer: Any) -> Any: + """Copy answer data using Python's copy protocol, leaving private model state alone.""" + # A Pydantic model may own a private client or lock. Seed deepcopy with + # shallow model copies, then detach their public fields using the same memo. + memo: dict[int, Any] = {} + models: list[BaseModel] = [] + seen: set[int] = set() + + def stored_fields(model: BaseModel) -> dict[str, Any]: + # Reading the stored values preserves cached aliases without calling getters. + cls = type(model) + return { + key: value + for key, value in vars(model).items() + if key in cls.model_fields or key in cls.model_computed_fields + } + + def find_models(value: Any) -> None: + if id(value) in seen: + return + seen.add(id(value)) + if isinstance(value, BaseModel): + memo[id(value)] = value.model_copy() + models.append(value) + for item in stored_fields(value).values(): + find_models(item) + find_models(value.model_extra) + elif isinstance(value, Mapping): + for key, item in value.items(): + find_models(key) + find_models(item) + elif isinstance(value, (Sequence, Set)) and not isinstance( + value, (str, bytes, bytearray, memoryview) + ): + for item in value: + find_models(item) + elif is_dataclass(value) and not isinstance(value, type): + for field in fields(value): + find_models(getattr(value, field.name)) + + find_models(answer) + for model in models: + clone = memo[id(model)] + for name, value in stored_fields(model).items(): + vars(clone)[name] = deepcopy(value, memo) + if model.model_extra is not None: + clone.model_extra.update(deepcopy(model.model_extra, memo)) + return deepcopy(answer, memo) + + +@dataclass(frozen=True) +class MessageOutcome: + """What happened on the first turn that tried to send this message. + + Submission means the SDK passed the message to the adapter. A filter can + omit a message on this turn and a later request can still include it. + Check retained before resending. Later turns do not update this receipt. + """ + + status: Literal["submitted", "not_submitted", "unknown"] + reason: str + turn_number: int | None + retained: bool + """Whether the run retained the item in history or staged it for possible later delivery.""" + + +class MessageReceipt: + """Track SDK submission without retaining the message text or assuming provider acceptance.""" + + def __init__(self) -> None: + self.id = uuid4().hex + self._future: asyncio.Future[MessageOutcome] = 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) -> MessageOutcome: + """Wait for the outcome of the first attempt to submit this message to the adapter. + + 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) + + +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 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. + 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. + + 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. 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 + 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. + """ + + 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._cancelling: Callable[[], int] | None = None + self._initial_cancellations = 0 + self._used = False + self._end_reason = "run_ended" + self._started = False + self._previous_outputs: tuple[Any, ...] = () + self._pending_output: tuple[Any, ...] = () + self._steers: list[tuple[str, MessageReceipt]] = [] + self._queued: deque[tuple[str, MessageReceipt]] = deque() + self._batch: list[MessageReceipt] = [] + self._turn: int | None = None + self._retained = False + self._items: list[InputItem] = [] + self._before: list[tuple[TResponseInputItem, bytes | None]] = [] + self._instructions: str | None = None + self._targets: list[tuple[TResponseInputItem | None, bytes | 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. + """ + receipt = self._new_receipt(text) + self._steers.append((text, receipt)) + return receipt + + 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. + """ + receipt = self._new_receipt(text) + self._queued.append((text, receipt)) + return receipt + + def _new_receipt(self, text: str) -> MessageReceipt: + if self._loop is None: + raise UserError("RunInbox 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("RunInbox requires non-empty user text") + if len(self._steers) + len(self._queued) >= self._limit: + raise UserError("RunInbox input queue is full") + return MessageReceipt() + + def _reserve(self) -> None: + if self._used: + raise UserError("RunInbox belongs to a single run. Use a fresh inbox.") + self._used = True + + def _bind(self, *, owner: asyncio.Task[Any] | None = None) -> None: + self._loop = asyncio.get_running_loop() + # Only an awaited run belongs to the calling task. Python 3.10 has no + # public cancellation count, so it relies on CancelledError propagating. + self._cancelling = getattr(owner, "cancelling", None) + if self._cancelling is not None: + self._initial_cancellations = self._cancelling() + + def _check_owner_cancellation(self) -> None: + if self._cancelling is not None and self._cancelling() > self._initial_cancellations: + raise asyncio.CancelledError + + @property + def _has_pending(self) -> bool: + return bool(self._steers or self._queued) + + def _stop_accepting(self) -> None: + self._loop = None + + def _can_admit_input( + self, current_turn: int, max_turns: int | None, budget: _BudgetState | None + ) -> bool: + """Check limits before admitting optional input. Dispatch charges the budget.""" + if max_turns is not None and current_turn >= max_turns: + self._end_reason = "max_turns" + self._stop_accepting() + return False + if budget is not None: + try: + budget.check() + except RunBudgetError as error: + self._end_reason = error.code + self._stop_accepting() + return False + return True + + def _advance( + self, current_turn: int, max_turns: int | None, budget: _BudgetState | None + ) -> bool: + """Select the next task only after the current answer has passed its guardrails.""" + 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: + self._steers.append(self._queued.popleft()) + return True + + def _stage_output(self, output: Any) -> None: + # Tool callbacks can return private values that do not belong in model + # input or session history. Keep a caller-only snapshot after guardrails. + from ._redaction import require_clean + + self._pending_output = (_snapshot_answer(output),) + require_clean([*self._previous_outputs, *self._pending_output]) + + def _begin_turn(self) -> tuple[Any, ...]: + if self._batch: + self._check_owner_cancellation() + # Cancellation during admission leaves the answer as final_output. + if self._pending_output: + self._previous_outputs += self._pending_output + self._pending_output = () + return self._previous_outputs + + def _check_final_output(self, output: Any) -> None: + if self._previous_outputs: + from ._redaction import require_clean + + require_clean([*self._previous_outputs, output]) + + def _take( + self, current_turn: int, max_turns: int | None, budget: _BudgetState | None + ) -> list[TResponseInputItem]: + from ._redaction import redact_items + from .items import ItemHelpers + + if not self._started or not self._steers: + return [] + if not self._can_admit_input(current_turn, max_turns, budget): + return [] + self._check_owner_cancellation() + pending, self._steers = self._steers, [] + self._batch = [receipt for _, receipt in pending] + self._turn = current_turn + 1 + items = [item for text, _ in pending for item in ItemHelpers.input_to_new_input_list(text)] + return redact_items(items) + + def _stage(self, items: list[TResponseInputItem], run_state: RunState[Any]) -> None: + run_state._stage_inbox_input(items, new_task=bool(self._pending_output)) + self._retained = True + + def _admitted(self, items: list[InputItem]) -> None: + if self._batch: + self._items = items[-len(self._batch) :] + + @staticmethod + def _item_digest(item: TResponseInputItem) -> bytes | None: + # Replay fingerprints normalize fields and stringify opaque values. Receipts + # need the exact content, without invoking caller-defined serializers. + from .run_state import _validate_run_state_json_value + + try: + _validate_run_state_json_value(item) + encoded = json.dumps(item, ensure_ascii=False, allow_nan=False).encode() + return hashlib.sha256(encoded).digest() + except (TypeError, ValueError, RecursionError): + return None + + def _before_filter( + self, + items: list[TResponseInputItem], + tracker: OpenAIServerConversationTracker | None, + *, + filter_input: list[TResponseInputItem] | None, + instructions: str | None, + ) -> None: + if not self._batch: + return + self._targets.clear() + self._before.clear() + 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 + } + targets = [by_id.get(item.input_id) for item in self._items] + else: + # Live items form the final, ordered suffix before policy feedback. + count = len(self._items) + targets = [items[i - count] if len(items) >= count else None for i in range(count)] + for target, admitted in zip(targets, self._items, strict=True): + expected = self._item_digest(admitted.raw_item) + if target is None or expected is None or self._item_digest(target) != expected: + self._targets.append((None, None)) + else: + self._targets.append((target, expected)) + if filter_input is not None: + self._before = [(item, self._item_digest(item)) for item in filter_input] + self._instructions = instructions + + def _dispatch(self, items: list[TResponseInputItem], instructions: str | None) -> None: + # A retry is another dispatch, even after the first attempt settled the receipts. + self._check_owner_cancellation() + self._started = True + if not self._batch: + return + target_ids = {id(target) for target, _ in self._targets if target is not None} + present = {id(item) for item in items if id(item) in target_ids} + # A missing occurrence proves omission only when the request is an + # unchanged subsequence, including any synthetic policy feedback. + omission_only = False + same_instructions = ( + type(instructions) is type(self._instructions) + and (instructions is None or type(instructions) is str) + and instructions == self._instructions + ) + if self._before and present != target_ids and same_instructions: + before = iter(self._before) + for item in items: + digest = next((digest for old, digest in before if old is item), None) + if digest is None or digest != self._item_digest(item): + break + else: + omission_only = True + for receipt, (target, expected) in zip(self._batch, self._targets, strict=True): + outcome: MessageOutcome + if ( + target is not None + and id(target) in present + and self._item_digest(target) == expected + ): + outcome = MessageOutcome("submitted", "adapter_dispatch", self._turn, True) + elif target is not None and id(target) not in present and omission_only: + outcome = MessageOutcome("not_submitted", "filtered", self._turn, True) + else: + outcome = MessageOutcome("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._instructions = None + self._targets.clear() + self._turn = None + self._retained = False + + def _close(self, reason: str) -> None: + for receipt in self._batch: + if not receipt._future.done(): + receipt._future.set_result( + MessageOutcome("not_submitted", reason, self._turn, self._retained) + ) + for _, receipt in (*self._steers, *self._queued): + receipt._future.set_result(MessageOutcome("not_submitted", reason, None, False)) + self._previous_outputs = self._pending_output = () + self._steers.clear() + self._queued.clear() + self._clear_batch() + self._loop = None + self._cancelling = None + + +_current: ContextVar[RunInbox | None] = ContextVar("agents_run_inbox", default=None) + + +def current_inbox() -> RunInbox | None: + return _current.get() + + +def stop_inbox_intake() -> None: + """Reject new messages while the runner saves results or cleans up a terminal turn.""" + if (inbox := current_inbox()) is not None: + inbox._stop_accepting() + + +@contextmanager +def inbox_scope(inbox: RunInbox | None) -> Iterator[None]: + # Always mask the parent handle, including when Agent.as_tool starts a nested run. + token = _current.set(inbox) + 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 inbox is not None: + inbox._close(inbox._end_reason if reason == "run_ended" else reason) diff --git a/src/agents/run_internal/agent_runner_helpers.py b/src/agents/run_internal/agent_runner_helpers.py index 79df6b2369..08c3224f2a 100644 --- a/src/agents/run_internal/agent_runner_helpers.py +++ b/src/agents/run_internal/agent_runner_helpers.py @@ -17,7 +17,7 @@ set_agent_tool_state_scope, ) from ..exceptions import UserError -from ..guardrail import InputGuardrailResult +from ..guardrail import InputGuardrailResult, OutputGuardrailResult from ..items import ModelResponse, RunItem, ToolApprovalItem, TResponseInputItem from ..memory import Session from ..models.interface import Model @@ -399,6 +399,8 @@ async def validate_resumed_agent_tools( ) -> tuple[bool, bool]: """Check required delegate bindings once for both budgets and text editors.""" budgeted = _check_resumed_budget(state, limits) + # Delegated tools can have a different context from the specialist check. + state._restore_task_input(context) edited = False for action in getattr(state._last_processed_response, "functions", ()): if not action.function_tool._is_agent_tool: @@ -574,6 +576,7 @@ def build_interruption_result( model_responses: list[ModelResponse], current_agent: Agent[Any], input_guardrail_results: list[InputGuardrailResult], + output_guardrail_results: list[OutputGuardrailResult], tool_input_guardrail_results: list[ToolInputGuardrailResult], tool_output_guardrail_results: list[ToolOutputGuardrailResult], context_wrapper: RunContextWrapper[TContext], @@ -601,7 +604,7 @@ def build_interruption_result( final_output=None, _last_agent=current_agent, input_guardrail_results=input_guardrail_results, - output_guardrail_results=[], + output_guardrail_results=output_guardrail_results, tool_input_guardrail_results=tool_input_guardrail_results, tool_output_guardrail_results=tool_output_guardrail_results, context_wrapper=context_wrapper, diff --git a/src/agents/run_internal/guardrails.py b/src/agents/run_internal/guardrails.py index a80691948a..9e81803540 100644 --- a/src/agents/run_internal/guardrails.py +++ b/src/agents/run_internal/guardrails.py @@ -14,6 +14,7 @@ from ..items import TResponseInputItem from ..result import RunResultStreaming from ..run_context import RunContextWrapper, TContext +from ..run_inbox import stop_inbox_intake from ..tracing import Span, SpanError, guardrail_span from ..util import _error_tracing from .run_steps import QueueCompleteSentinel @@ -101,6 +102,8 @@ async def run_input_guardrails_with_queue( ) ) streamed_result._triggered_input_guardrail_result = result + if streamed_result._inbox is not None: + streamed_result._inbox._stop_accepting() queue.put_nowait(result) for t in guardrail_tasks: t.cancel() @@ -120,6 +123,8 @@ async def run_input_guardrails_with_queue( break queue.put_nowait(result) except BaseException as error: + if streamed_result._inbox is not None: + streamed_result._inbox._stop_accepting() for t in guardrail_tasks: if not t.done(): t.cancel() @@ -168,6 +173,7 @@ def record(result: InputGuardrailResult) -> None: for done in asyncio.as_completed(guardrail_tasks): result = await done if result.output.tripwire_triggered: + stop_inbox_intake() record(result) for sibling in _unreported_guardrail_results(guardrail_tasks, guardrail_results): record(sibling) @@ -183,6 +189,7 @@ def record(result: InputGuardrailResult) -> None: raise InputGuardrailTripwireTriggered(result) record(result) except BaseException: + stop_inbox_intake() # On any error (including a guardrail raising or the caller being cancelled), # cancel and await siblings so they don't leak past this function's return. for t in guardrail_tasks: @@ -226,6 +233,7 @@ def record(result: OutputGuardrailResult) -> None: for done in asyncio.as_completed(guardrail_tasks): result = await done if result.output.tripwire_triggered: + stop_inbox_intake() record(result) for sibling in _unreported_guardrail_results(guardrail_tasks, guardrail_results): record(sibling) @@ -241,6 +249,7 @@ def record(result: OutputGuardrailResult) -> None: raise OutputGuardrailTripwireTriggered(result) record(result) except BaseException: + stop_inbox_intake() # On any error (including a guardrail raising or the caller being cancelled), # cancel and await siblings so they don't leak past this function's return. for t in guardrail_tasks: diff --git a/src/agents/run_internal/model_retry.py b/src/agents/run_internal/model_retry.py index 82ddf6ffeb..13d1c531be 100644 --- a/src/agents/run_internal/model_retry.py +++ b/src/agents/run_internal/model_retry.py @@ -874,17 +874,19 @@ async def stream_response_with_retry( except _StreamAttemptSkipped as skipped: raise skipped.reason from None except BaseException as error: - if isinstance(error, ModelTimeoutError): - # The timed owner has already been cancelled and drained. Do not retain its - # task, result queues, or previous event in the public timeout traceback frame. - stream = None - stream_owner = None - stream_requests = None - stream_results = None - event = None - result_value = None - if stream_owner is None: - await _close_async_iterator_quietly(stream) + try: + if stream_owner is None: + await _close_async_iterator_quietly(stream) + finally: + if isinstance(error, ModelTimeoutError): + # Cancellation can interrupt close and chain the original timeout. + # Drop the retry frame's references even on that path. + stream = None + stream_owner = None + stream_requests = None + stream_results = None + event = None + result_value = None if isinstance(error, asyncio.CancelledError | GeneratorExit): raise if not isinstance(error, Exception): diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index cbce2f8feb..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 ( @@ -84,8 +85,10 @@ from ..run_config import ReasoningItemIdPolicy, RunConfig from ..run_context import AgentHookContext, RunContextWrapper, TContext from ..run_error_handlers import RunErrorHandlers +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, @@ -154,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, @@ -247,6 +250,8 @@ validate_run_hooks, ) from .turn_resolution import ( + _get_turn_input, + _HandoffTaskInputs, _snapshot_function_calls, check_for_final_output_from_tools, execute_final_output, @@ -349,6 +354,12 @@ def _ensure_stream_event_item_occurrence_key(item: RunItem) -> str: return key +def _stop_inbox_for_terminal_step(turn_result: SingleStepResult) -> None: + """An approval pause ends this invocation before its checkpoint is saved.""" + if isinstance(turn_result.next_step, NextStepInterruption): + stop_inbox_intake() + + async def cleanup_models_after_run(tool_use_tracker: AgentToolUseTracker) -> None: """Notify every model resolved during the run that its owning run has ended.""" for model in tool_use_tracker.models: @@ -374,22 +385,34 @@ async def _should_persist_stream_items( return should_skip_session_save is False -def _with_feedback( +def _prepare_request_input( items: list[TResponseInputItem], - message: str | None, + feedback: str | None, tracker: OpenAIServerConversationTracker | None, session: Session | None, + run_config: RunConfig, + system_prompt: str | None, ) -> list[TResponseInputItem]: - if message is None: - return items - if tracker is not None or ( - is_openai_responses_compaction_aware_session(session) - and getattr(session, "compaction_mode", None) != "input" - ): - raise UserError("ContinueWithFeedback requires SDK-managed input without response IDs") - # Keep the extra item out of replay and check it before exposing it to the filter. - request: list[TResponseInputItem] = [*items, {"role": "user", "content": message}] - require_clean(request) + request = items + if feedback is not None: + if tracker is not None or ( + is_openai_responses_compaction_aware_session(session) + and getattr(session, "compaction_mode", None) != "input" + ): + raise UserError("ContinueWithFeedback requires SDK-managed input without response IDs") + # Keep the extra item out of replay and check it before exposing it to the filter. + request = [*items, {"role": "user", "content": feedback}] + require_clean(request) + inbox = current_inbox() + if inbox is not None: + # Identify live occurrences in the original input. The filter sees the + # complete request, which can include one additional feedback message. + inbox._before_filter( + items, + tracker, + filter_input=request if run_config.call_model_input_filter is not None else None, + instructions=system_prompt, + ) return request @@ -603,6 +626,17 @@ def _retained_items_for_blocked_output( ) +async def _await_initial_input_guardrails(streamed_result: RunResultStreaming) -> None: + """Only admit live input after the initial parallel guardrails have passed.""" + task = streamed_result._input_guardrails_task + if task is not None: + # This task can cancel the producer on failure. Wait without linking their cancellation. + await streamed_result._await_task_safely(task) + task.result() + if (tripwire := streamed_result._triggered_input_guardrail_result) is not None: + raise InputGuardrailTripwireTriggered(tripwire) + + async def _finalize_streamed_final_output( *, streamed_result: RunResultStreaming, @@ -622,7 +656,9 @@ async def _finalize_streamed_final_output( stream_items_after_guardrails: bool = False, retry_on_guardrail_error: bool = False, continued_step: SingleStepResult | None = None, -) -> None: + allow_inbox_advance: bool = False, +) -> Callable[[], Awaitable[None]] | None: + """Guard and persist the answer. Defer completion while admitting an inbox message.""" output_guardrail_result_start = len(streamed_result.output_guardrail_results) redacted_persistence_error: BaseException | None = None continue_after_guardrails = continued_step is not None @@ -639,6 +675,7 @@ async def _finalize_streamed_final_output( if continued_step is not None: continued_step.check_continued_output() except _blocked_output_errors(continue_after_guardrails) as exc: + stop_inbox_intake() if not continue_after_guardrails and not _is_terminal_tool_output_response( items, processed_response, @@ -697,12 +734,13 @@ async def _finalize_streamed_final_output( streamed_result._stored_exception = safe_error streamed_result.is_complete = True streamed_result._event_queue.put_nowait(QueueCompleteSentinel()) - return + return None raise safe_error from None if isinstance(exc, asyncio.CancelledError) and streamed_result._cancel_mode != "immediate": streamed_result._stored_exception = exc raise except Exception as guardrail_error: + stop_inbox_intake() guardrail_error_is_redacted = _is_error_data_redacted(guardrail_error) if guardrail_error_is_redacted: _detach_data_redacted_error_traceback(guardrail_error) @@ -730,9 +768,9 @@ async def _finalize_streamed_final_output( streamed_result._stored_exception = safe_persistence_error streamed_result.is_complete = True streamed_result._event_queue.put_nowait(QueueCompleteSentinel()) - return + return None if isinstance(safe_persistence_error, asyncio.CancelledError): - return + return None redacted_persistence_error = safe_persistence_error if ( isinstance(persistence_error, asyncio.CancelledError) @@ -777,7 +815,7 @@ async def _finalize_streamed_final_output( streamed_result._stored_exception = persistence_error streamed_result.is_complete = True streamed_result._event_queue.put_nowait(QueueCompleteSentinel()) - return + return None # The append and any post-append maintenance both succeeded, so the turn is durable and the # state is open again. if streamed_result._state is not None: @@ -786,18 +824,44 @@ async def _finalize_streamed_final_output( if stream_items_after_guardrails: _publish_stream_items(items, streamed_result) if continue_after_guardrails: - return - await checkpoint_streamed_result(streamed_result) - # A fallback or a recovered tool turn can still be missing from new_items. - require_clean_final_output(output, streamed_result.input, *final_history) - streamed_result.final_output = output - if streamed_result._approved_output is not None: - streamed_result._approved_output.accepted = True - if on_persisted_after_guardrails is not None: - on_persisted_after_guardrails(True) - streamed_result.is_complete = True + return None + inbox = current_inbox() + + async def finish_answer() -> None: + if inbox is not None: + inbox._stop_accepting() + await checkpoint_streamed_result(streamed_result) + # A fallback or a recovered tool turn can still be missing from new_items. + require_clean_final_output(output, streamed_result.input, *final_history) + if inbox is not None: + inbox._check_final_output(output) + streamed_result.final_output = output + if streamed_result._approved_output is not None: + streamed_result._approved_output.accepted = True + if on_persisted_after_guardrails is not None: + on_persisted_after_guardrails(True) + streamed_result.is_complete = True + streamed_result._event_queue.put_nowait(QueueCompleteSentinel()) - streamed_result._event_queue.put_nowait(QueueCompleteSentinel()) + if inbox is not None: + if allow_inbox_advance and inbox._has_pending and streamed_result._cancel_mode == "none": + # A run without a local session may still be checking its initial input. + await _await_initial_input_guardrails(streamed_result) + # Let a consumer cancel after this turn while its answer can still finish the run. + if ( + streamed_result.max_turns is None + or streamed_result.current_turn < streamed_result.max_turns + ): + await streamed_result._wait_for_turn_event_consumption() + require_clean_final_output(output, streamed_result.input, *final_history) + if streamed_result._cancel_mode == "none" and inbox._advance( + streamed_result.current_turn, streamed_result.max_turns, context_wrapper._budget + ): + inbox._stage_output(output) + # Until the next turn starts, graceful cancellation can still return this answer. + return finish_answer + await finish_answer() + return None async def finalize_max_turns_handler_output( @@ -847,6 +911,7 @@ async def finalize_max_turns_handler_output( take_held_session_write(run_state) raise except Exception as guardrail_error: + stop_inbox_intake() guardrail_error_is_redacted = _is_error_data_redacted(guardrail_error) if guardrail_error_is_redacted: _detach_data_redacted_error_traceback(guardrail_error) @@ -962,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, @@ -982,6 +1096,9 @@ async def start_streaming( sandbox_runtime: SandboxRuntime[TContext] | None = None, ): """Run the streaming loop for a run result.""" + inbox = current_inbox() + if inbox is not None and is_resumed_state: + inbox._started = 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 @@ -1136,6 +1253,38 @@ def _sync_conversation_tracking_from_tracker() -> None: pending_server_items: list[RunItem] | None = None pending_input_admission_items: list[InputItem] = [] session_input_items_for_persistence: list[TResponseInputItem] | None = None + finish_previous_answer: Callable[[], Awaitable[None]] | None = None + + async def _stop_before_turn_if_cancelled(*, during_admission: bool = False) -> bool: + if streamed_result.is_complete or streamed_result._cancel_mode == "immediate": + return True + if streamed_result._cancel_mode != "after_turn": + return False + if finish_previous_answer is not None: + await finish_previous_answer() + if session is None: + take_held_session_write(run_state) + if run_state is not None: + run_state._current_step = None + return True + if during_admission: + # A steer can follow a tool turn that has no final answer. + await checkpoint_streamed_result(streamed_result, interruptions=[]) + streamed_result.is_complete = True + streamed_result._event_queue.put_nowait(QueueCompleteSentinel()) + return 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( + completed_turn.tool_input_guardrail_results + ) + accepted_tool_output_guardrail_results.extend( + completed_turn.tool_output_guardrail_results + ) def _commit_pending_server_response( model_response: ModelResponse, @@ -1151,6 +1300,9 @@ def _commit_pending_server_response( run_state=run_state, tracker=server_conversation_tracker, admission_items=pending_input_admission_items, + prior_responses=streamed_result.raw_responses, + tool_input_guardrail_results=accepted_tool_input_guardrail_results, + tool_output_guardrail_results=accepted_tool_output_guardrail_results, generated_items=streamed_result._model_input_items, session_items=streamed_result.new_items, model_response=model_response, @@ -1186,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 ) @@ -1393,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 @@ -1525,6 +1663,7 @@ def on_resumed_policy_error() -> None: )[:result_start] raise + _stop_inbox_for_terminal_step(turn_result) tool_use_tracker.record_processed_response( current_agent, run_state._last_processed_response ) @@ -1642,11 +1781,12 @@ def on_resumed_policy_error() -> None: if turn_result.processed_response is not None else run_state._last_processed_response ) - await _finalize_streamed_final_output( + finish_previous_answer = await _finalize_streamed_final_output( streamed_result=streamed_result, agent=current_agent, run_config=run_config, output=turn_result.next_step.output, + allow_inbox_advance=not turn_result.next_step.is_error_handler_output, continued_step=turn_result if turn_result.next_step.continue_after_guardrails else None, @@ -1679,10 +1819,13 @@ def on_resumed_policy_error() -> None: streamed_result.tool_output_guardrail_results.extend( turn_result.tool_output_guardrail_results ) + if finish_previous_answer is not None: + _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 ): @@ -1712,18 +1855,22 @@ def on_resumed_policy_error() -> None: run_state._current_step = None - if streamed_result._cancel_mode == "after_turn": - streamed_result.is_complete = True - streamed_result._event_queue.put_nowait(QueueCompleteSentinel()) - break - - if streamed_result.is_complete: + if await _stop_before_turn_if_cancelled(): break - if run_state is not None and run_state._pending_input: + live_input = ( + inbox._take(current_turn, max_turns, context_wrapper._budget) + if inbox is not None + else [] + ) + if live_input: + await _await_initial_input_guardrails(streamed_result) + if await _stop_before_turn_if_cancelled(during_admission=True): + break + 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 [] ) @@ -1754,9 +1901,14 @@ def on_resumed_policy_error() -> None: if tripping_result is not None: raise InputGuardrailTripwireTriggered(tripping_result) + if await _stop_before_turn_if_cancelled(during_admission=True): + break + store_setting = current_agent.model_settings.resolve( run_config.model_settings ).store + if live_input and inbox is not None: + inbox._stage(live_input, run_state) admission_items = await admit_pending_input( run_state=run_state, agent=current_agent, @@ -1772,10 +1924,20 @@ def on_resumed_policy_error() -> None: pending_input_admission_items = [ item for item in admission_items if isinstance(item, InputItem) ] + if inbox is not None: + inbox._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) + if await _stop_before_turn_if_cancelled(during_admission=True): + # The session append completed. Keep the admitted input in history. + break + if finish_previous_answer is not None: + if inbox is not None: + streamed_result._previous_outputs = inbox._begin_turn() + finish_previous_answer = None + set_final_output_item(None) current_turn += 1 feedback, pending_feedback = pending_feedback, None streamed_result.current_turn = current_turn @@ -1784,6 +1946,8 @@ def on_resumed_policy_error() -> None: run_state._current_turn_persisted_item_count = 0 if max_turns is not None and current_turn > max_turns: + if inbox is not None: + inbox._stop_accepting() _error_tracing.attach_error_to_span( current_span, SpanError( @@ -2130,6 +2294,7 @@ def _record_max_turns_handler_output( usage_delta(turn_usage_start, context_wrapper.usage), ) current_turn_span.finish(reset_current=True) + _stop_inbox_for_terminal_step(turn_result) logger.debug( "Turn %s complete, next_step type=%s", current_turn, @@ -2246,11 +2411,12 @@ def _record_max_turns_handler_output( if await _wait_for_streamed_turn_events_and_stop_if_cancelled(streamed_result): break elif isinstance(turn_result.next_step, NextStepFinalOutput): - await _finalize_streamed_final_output( + finish_previous_answer = await _finalize_streamed_final_output( streamed_result=streamed_result, agent=current_agent, run_config=run_config, output=turn_result.next_step.output, + allow_inbox_advance=not turn_result.next_step.is_error_handler_output, continued_step=turn_result if turn_result.next_step.continue_after_guardrails else None, @@ -2266,6 +2432,10 @@ def _record_max_turns_handler_output( ) if streamed_result._stored_exception is not None: break + if finish_previous_answer is not None: + _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 streamed_result._model_input_items = model_input_items @@ -2273,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 ): @@ -2419,6 +2588,8 @@ def _record_max_turns_handler_output( else: streamed_result.is_complete = True finally: + if inbox is not None: + inbox._stop_accepting() await cleanup_models_after_run(tool_use_tracker) _sync_conversation_tracking_from_tracker() if streamed_result._input_guardrails_task: @@ -2489,7 +2660,13 @@ async def run_single_turn_streamed( public_agent = bindings.public_agent execution_agent = bindings.execution_agent - async def raise_if_input_guardrail_tripwire_known() -> None: + def check_immediate_cancellation() -> None: + # A provider or application callback can return after catching CancelledError. + if streamed_result._cancel_mode == "immediate": + raise asyncio.CancelledError + + async def check_before_side_effects() -> None: + check_immediate_cancellation() tripwire_result = streamed_result._triggered_input_guardrail_result if tripwire_result is not None: raise InputGuardrailTripwireTriggered(tripwire_result) @@ -2506,10 +2683,9 @@ async def raise_if_input_guardrail_tripwire_known() -> None: if tripwire_result is not None: raise InputGuardrailTripwireTriggered(tripwire_result) - try: - turn_input = ItemHelpers.input_to_new_input_list(streamed_result.input) - except Exception: - turn_input = [] + turn_input = _get_turn_input( + run_state, streamed_result.input, streamed_result._model_input_items + ) context_wrapper.turn_input = list(turn_input) with guard_agent_tool_configuration(public_agent): @@ -2607,11 +2783,14 @@ async def raise_if_input_guardrail_tripwire_known() -> None: reasoning_item_id_policy, ) + inbox = current_inbox() filtered = await maybe_filter_model_input( agent=public_agent, run_config=run_config, context_wrapper=context_wrapper, - input_items=_with_feedback(input, feedback, server_conversation_tracker, session), + input_items=_prepare_request_input( + input, feedback, server_conversation_tracker, session, run_config, system_prompt + ), system_instructions=system_prompt, ) redact_model_input(filtered, prompt_config) @@ -2692,6 +2871,9 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: tripwire = streamed_result._triggered_input_guardrail_result if tripwire is not None: raise _StreamAttemptSkipped(InputGuardrailTripwireTriggered(tripwire)) + check_immediate_cancellation() + if inbox is not None: + inbox._dispatch(filtered.input, filtered.instructions) return model.stream_response( filtered.instructions, filtered.input, @@ -2853,12 +3035,15 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: response_accepted = False if on_response_accepted is not None: response_accepted = on_response_accepted(final_response, None) + # Account for the completed request before stopping any new local work. + check_immediate_cancellation() async def after_invocation_validation( processed_response: ProcessedResponse | None, ) -> bool: if response_accepted and on_response_accepted is not None: on_response_accepted(final_response, processed_response) + check_immediate_cancellation() if response_accepted and on_response_hooks_started is not None: on_response_hooks_started() if processed_response is not None: @@ -2891,9 +3076,6 @@ async def after_invocation_validation( ) return response_accepted - async def check_input_guardrails_before_side_effects() -> None: - await raise_if_input_guardrail_tripwire_known() - def on_tool_error_selected() -> None: # The category has selected its failure, before draining native finalization. streamed_result._tool_error_selected = True @@ -2915,7 +3097,7 @@ def on_tool_error_selected() -> None: tool_use_tracker=tool_use_tracker, server_manages_conversation=server_conversation_tracker is not None, after_invocation_validation=after_invocation_validation, - before_side_effects=check_input_guardrails_before_side_effects, + before_side_effects=check_before_side_effects, run_state=run_state, on_tool_execution_error=on_tool_execution_error, on_tool_error_selected=on_tool_error_selected, @@ -2944,6 +3126,7 @@ async def run_single_turn( should_run_agent_start_hooks: bool, tool_use_tracker: AgentToolUseTracker, server_conversation_tracker: OpenAIServerConversationTracker | None = None, + pending_server_items: list[RunItem] | None = None, session: Session | None = None, session_items_to_rewind: list[TResponseInputItem] | None = None, reasoning_item_id_policy: ReasoningItemIdPolicy | None = None, @@ -2959,10 +3142,7 @@ async def run_single_turn( """Run a single non-streaming turn of the agent loop.""" public_agent = bindings.public_agent execution_agent = bindings.execution_agent - try: - turn_input = ItemHelpers.input_to_new_input_list(original_input) - except Exception: - turn_input = [] + turn_input = _get_turn_input(run_state, original_input, generated_items) context_wrapper.turn_input = list(turn_input) with guard_agent_tool_configuration(public_agent): @@ -3013,14 +3193,18 @@ async def run_single_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) + input = server_conversation_tracker.prepare_input( + original_input, pending_server_items or generated_items + ) else: input = _prepare_turn_input_items(original_input, generated_items, reasoning_item_id_policy) new_response = await get_new_response( bindings, system_prompt, - _with_feedback(input, feedback, server_conversation_tracker, session), + _prepare_request_input( + input, feedback, server_conversation_tracker, session, run_config, system_prompt + ), output_schema, model_tools, handoffs, @@ -3042,6 +3226,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, @@ -3050,6 +3238,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( @@ -3060,6 +3250,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( @@ -3110,6 +3302,7 @@ 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 + inbox = current_inbox() filtered = await maybe_filter_model_input( agent=public_agent, run_config=run_config, @@ -3216,10 +3409,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 inbox is not None: + inbox._dispatch(filtered.input, filtered.instructions) + return await model.get_response( system_instructions=filtered.instructions, input=filtered.input, model_settings=model_settings, @@ -3232,7 +3426,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/src/agents/run_internal/run_steps.py b/src/agents/run_internal/run_steps.py index d443480168..a16beabef5 100644 --- a/src/agents/run_internal/run_steps.py +++ b/src/agents/run_internal/run_steps.py @@ -172,6 +172,7 @@ class NextStepHandoff: class NextStepFinalOutput: output: Any continue_after_guardrails: bool = False + is_error_handler_output: bool = False @dataclass diff --git a/src/agents/run_internal/session_persistence.py b/src/agents/run_internal/session_persistence.py index dbe52ca41f..9303b1231f 100644 --- a/src/agents/run_internal/session_persistence.py +++ b/src/agents/run_internal/session_persistence.py @@ -51,10 +51,12 @@ from ..run_config import RunConfig from ..run_context import RunContextWrapper from ..run_state import RunState, _PendingSessionWrite, _SessionCompactionModelExchange +from ..tool_guardrails import ToolInputGuardrailResult, ToolOutputGuardrailResult from .blocked_output import ( _current_response_boundary, _identity_sequence_start, _should_defer_interrupted_session_items, + _synchronize_accepted_run_state, ) from .items import ( _TOOL_CALL_TO_OUTPUT_TYPE, @@ -197,12 +199,13 @@ async def admit_pending_input( before the model call, while server-managed conversations keep it pending until a model response confirms that the server accepted the request. """ - pending_input = run_state.pending_input - if not pending_input: + if not run_state._pending_input: return [] + input_ids = run_state._track_pending_input() admission_items: list[RunItem] = [ - InputItem(agent=agent, raw_item=item) for item in pending_input + InputItem(agent=agent, raw_item=item, input_id=input_id) + for item, input_id in zip(run_state.pending_input, input_ids, strict=True) ] require_clean_run_items(run_state._original_input, run_state._session_items, admission_items) @@ -216,7 +219,8 @@ async def admit_pending_input( wrapper=wrapper, ) if server_conversation_tracker is None: - run_state.clear_pending_input() + # Successful admission keeps these messages in the current task. + run_state._consume_pending_input() return admission_items @@ -226,6 +230,9 @@ def commit_server_pending_input( run_state: RunState[Any], tracker: OpenAIServerConversationTracker, admission_items: list[InputItem], + prior_responses: list[ModelResponse], + tool_input_guardrail_results: list[ToolInputGuardrailResult], + tool_output_guardrail_results: list[ToolOutputGuardrailResult], generated_items: list[RunItem], session_items: list[RunItem], model_response: ModelResponse, @@ -252,9 +259,9 @@ def retain_accepted_admissions(items: list[RunItem]) -> None: retain_accepted_admissions(generated_items) retain_accepted_admissions(session_items) - run_state._pending_input = copy.deepcopy( - [item.raw_item for item in admission_items if item.input_id not in accepted_ids] - ) + unacknowledged = [item for item in admission_items if item.input_id not in accepted_ids] + run_state._pending_input = copy.deepcopy([item.raw_item for item in unacknowledged]) + run_state._pending_input_ids = tuple(item.input_id for item in unacknowledged) # A model input filter may omit every staged occurrence. In that case the response does not # acknowledge pending input, so normal turn processing owns the response and the input remains @@ -262,13 +269,18 @@ def retain_accepted_admissions(items: list[RunItem]) -> None: if not accepted_ids: return False - state_generated_items = list(generated_items) - state_session_items = list(session_items) - - run_state._generated_items = state_generated_items - run_state._session_items = state_session_items - if not run_state._model_responses or run_state._model_responses[-1] is not model_response: - run_state._model_responses.append(model_response) + # Acceptance and validation checkpoint the same request. Snapshot completed + # turns first so recording this response never mutates the stream's list. + _synchronize_accepted_run_state( + run_state, + generated_items=generated_items, + session_items=session_items, + model_responses=prior_responses, + tool_input_guardrail_results=tool_input_guardrail_results, + tool_output_guardrail_results=tool_output_guardrail_results, + current_turn=current_turn, + ) + run_state._model_responses.append(model_response) run_state._last_processed_response = processed_response run_state._current_step = NextStepInterruption( interruptions=( @@ -277,13 +289,17 @@ def retain_accepted_admissions(items: list[RunItem]) -> None: response_accepted=True, llm_end_hooks_started=False, ) - run_state._current_turn = current_turn run_state._conversation_id = tracker.conversation_id run_state._previous_response_id = tracker.previous_response_id run_state._auto_previous_response_id = tracker.auto_previous_response_id - # The accepted model response is durable, but its processed items have not yet been merged - # because local hooks and tool work can still fail. Preserve that distinction across retries. run_state._clear_generated_items_last_processed_marker() + if processed_response is not None and processed_response.has_tools_or_approvals_to_run(): + # A tool can commit its output before a hook fails. Its validated call must + # precede that output in both checkpoint histories, just as on approval. + # Text-only responses still go through normal final-output processing on resume. + run_state._generated_items.extend(processed_response.new_items) + run_state._session_items.extend(processed_response.new_items) + run_state._mark_generated_items_merged_with_last_processed() return True diff --git a/src/agents/run_internal/turn_resolution.py b/src/agents/run_internal/turn_resolution.py index 23549ad573..7ec5d7dab5 100644 --- a/src/agents/run_internal/turn_resolution.py +++ b/src/agents/run_internal/turn_resolution.py @@ -92,6 +92,7 @@ CompactionItem, HandoffCallItem, HandoffOutputItem, + InputItem, ItemHelpers, MCPApprovalRequestItem, MCPListToolsItem, @@ -106,6 +107,7 @@ ToolSearchOutputItem, TResponseInputItem, TResponseOutputItem, + _observe_input_copies, coerce_tool_search_call_raw_item, coerce_tool_search_output_raw_item, ) @@ -121,7 +123,8 @@ from ..run_config import RunConfig, ToolErrorFormatterArgs from ..run_context import AgentHookContext, RunContextWrapper, TContext from ..run_error_handlers import RunErrorHandlers -from ..run_state import RunState +from ..run_inbox import stop_inbox_intake +from ..run_state import RunState, _user_message_key, _user_message_keys from ..tool import ( ApplyPatchTool, CodeInterpreterTool, @@ -160,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, @@ -388,6 +393,37 @@ async def _build_tool_not_found_output_items( return items +def _get_turn_input( + run_state: RunState[Any, Any] | None, + original_input: str | list[TResponseInputItem], + generated_items: list[RunItem], +) -> list[TResponseInputItem]: + 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) + 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) + except Exception: + return [] + + async def run_final_output_hooks( agent: Agent[TContext], hooks: RunHooks[TContext], @@ -412,6 +448,7 @@ async def run_final_output_hooks( async def execute_final_output_step( *, + is_error_handler_output: bool = False, public_agent: Agent[Any], original_input: str | list[TResponseInputItem], new_response: ModelResponse, @@ -428,6 +465,9 @@ async def execute_final_output_step( | None = None, ) -> SingleStepResult: """Finalize a turn once final output is known and run end hooks.""" + if is_error_handler_output: + # A fallback ends the run. Ordinary end hooks can still steer or queue. + stop_inbox_intake() final_output_hooks = ( run_final_output_hooks_fn if run_final_output_hooks_fn is not None @@ -441,7 +481,9 @@ async def execute_final_output_step( model_response=new_response, pre_step_items=pre_step_items, new_step_items=new_step_items, - next_step=NextStepFinalOutput(final_output), + next_step=NextStepFinalOutput( + final_output, is_error_handler_output=is_error_handler_output + ), tool_input_guardrail_results=tool_input_guardrail_results, tool_output_guardrail_results=tool_output_guardrail_results, output_guardrail_results=[], @@ -516,6 +558,9 @@ def on_policy_failure(error: BaseException) -> None: 'final_output_policy must return "continue", "finish" or ContinueWithFeedback' ) except (Exception, asyncio.CancelledError) as exc: + # A guarded tool defers this error until its effect has been saved. + # Both paths end the run, so neither can accept another message. + stop_inbox_intake() if not guarded_tool: raise # Let the blocked-output path record the effect without its unchecked result. @@ -535,6 +580,7 @@ def on_policy_failure(error: BaseException) -> None: ) return await execute_final_output_step( + is_error_handler_output=kind is None, public_agent=public_agent, original_input=original_input, new_response=new_response, @@ -651,6 +697,207 @@ 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] | None], + 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] + state._replace_task_input_refs(refs, (ref for ref in task if isinstance(ref, str))) + + async def execute_handoffs( *, public_agent: Agent[TContext], @@ -667,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.""" @@ -812,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) @@ -841,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, @@ -872,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) @@ -899,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._replace_task_input_refs(history_refs, item_refs) + return SingleStepResult( original_input=original_input, model_response=new_response, @@ -1188,8 +1494,14 @@ def _commit_accepted_response_tool_output(item: RunItem) -> None: *tool_output_guardrail_results, ] + def _on_tool_error_selected() -> None: + stop_inbox_intake() + if on_tool_error_selected is not None: + on_tool_error_selected() + def _publish_completed_tools() -> None: nonlocal accepting_outputs + stop_inbox_intake() accepting_outputs = False # Server-managed continuation retains its separate recovery path. if ( @@ -1234,7 +1546,7 @@ def _publish_completed_tools() -> None: context_wrapper=context_wrapper, run_config=run_config, tool_output_committer=_commit_accepted_response_tool_output, - on_tool_error_selected=on_tool_error_selected, + on_tool_error_selected=_on_tool_error_selected, tool_input_guardrail_results=tool_input_guardrail_results, tool_output_guardrail_results=tool_output_guardrail_results, ) @@ -1301,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, @@ -1745,11 +2058,7 @@ async def _function_requires_approval(run: ToolRunFunction) -> FunctionToolAppro except Exception: return pending - try: - context_wrapper.turn_input = ItemHelpers.input_to_new_input_list(original_input) - except Exception: - context_wrapper.turn_input = [] - + context_wrapper.turn_input = _get_turn_input(run_state, original_input, original_pre_step_items) pending_approval_items = _pending_approvals_from_state() def _allow_legacy_name_agent_match() -> bool: @@ -3066,11 +3375,13 @@ def _commit_tool_output(item: RunItem) -> None: hooks=hooks, context_wrapper=context_wrapper, run_config=run_config, + on_tool_error_selected=stop_inbox_intake, tool_output_committer=_commit_tool_output, tool_input_guardrail_results=tool_input_guardrail_results, tool_output_guardrail_results=tool_output_guardrail_results, ) except BaseException: + stop_inbox_intake() accepting_outputs = False if run_state is not None and not server_manages_conversation: run_state._generated_items = _snapshot_tool_outputs( @@ -3270,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 232740bff7..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 @@ -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 ( @@ -266,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.26" +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" @@ -335,7 +338,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.", + # 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) @@ -875,6 +882,30 @@ def _copy_tool_approval_raw_item(raw_item: Any) -> Any: raise TypeError("Unsupported tool approval raw item") +# 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 + + +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. @@ -929,6 +960,13 @@ class RunState(Generic[TContext, TAgent]): _pending_input: list[TResponseInputItem] = field(default_factory=list) """Input staged for admission immediately before the next resumed model call.""" + # 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. + _pending_input_ids: tuple[str, ...] = field(default=(), init=False, repr=False, compare=False) + _nested_history_owned_session_item_refs: list[NestedHistoryOwnedItemRef] = field( default_factory=list ) @@ -1068,6 +1106,144 @@ def unavailable() -> Exception: previous = agent return protected + def _restore_task_input(self, context: RunContextWrapper[Any]) -> None: + """Give resume checks the current task input, excluding any cleared messages.""" + if self._task_input_ids is not None: + from .run_internal.turn_resolution import _get_turn_input + + context.turn_input = _get_turn_input(self, self._original_input, self._generated_items) + + 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], + 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 = { + 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.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): + 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] | 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)} + 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 or None in task: + self._validate_task_history(self._original_input) + return { + "history": [i for i, _ in history], + "items": items, + "include_non_user_history": None in task, + } + return items + + 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) + + ids: list[_TaskInputRef] = [] + 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 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)) + ): + 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_inputs( + {ref for ref in refs if isinstance(ref, str)}, + self._generated_items, + validation_error_factory, + ) + 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) + and _user_message_key(self._pending_input[ref]) is not None + ): + 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: @@ -1078,6 +1254,7 @@ async def _check_pending_specialists( from .agent_tool_state import get_agent_tool_resume_state, peek_agent_tool_run_result from .tool import FunctionTool, _function_tool_enabled + self._restore_task_input(context) protected = self._check_specialist(root, context) for action in getattr(self._last_processed_response, "functions", ()): delegate = action.function_tool @@ -1258,9 +1435,52 @@ 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) + if missing: + self._pending_input_ids += tuple(uuid4().hex for _ in range(missing)) + if self._task_input_ids == (): + self._task_input_ids = self._pending_input_ids + return self._pending_input_ids + + def _consume_pending_input(self) -> None: + self._pending_input = [] + self._pending_input_ids = () + def clear_pending_input(self) -> None: """Remove all input staged for the next resumed model call.""" - self._pending_input = [] + 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 + ) + self._consume_pending_input() def get_interruptions(self) -> list[ToolApprovalItem]: """Return detached copies of pending interruptions for the current step.""" @@ -1661,7 +1881,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: @@ -1805,7 +2025,11 @@ def _current_response_generated_item_ownership( processed_items = self._last_processed_response.new_items interruptions = self._current_step.interruptions - if not processed_items or not interruptions or len(processed_items) > len(generated_items): + if not processed_items or len(processed_items) > len(generated_items): + return None + # An accepted response can need recovery after a hook fails, even + # when no tool requested approval. + if not interruptions and not self._current_step.response_accepted: return None candidate_starts = [ @@ -2215,6 +2439,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), @@ -2818,8 +3043,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 @@ -2847,26 +3075,37 @@ 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 + # 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_editor and schema < (1, 26): + if requires_task and schema < (1, 28): + raise validation_error_factory( + "Active task input requires RunState schema 1.28.", UserError + ) + if requires_editor and schema < (1, 28): raise validation_error_factory( - "Tool text transforms require RunState schema 1.26.", 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.") - return requires_budget, requires_editor + return requires_budget, requires_editor, requires_task def _validate_run_state_json_value(value: object) -> None: @@ -4859,11 +5098,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, @@ -4872,6 +5106,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 ( @@ -5967,7 +6210,9 @@ def _restore_current_response_item_identities( if not isinstance(current_step_payload, Mapping): return serialized_interruptions = current_step_payload.get("interruptions") - if not isinstance(serialized_interruptions, list) or not serialized_interruptions: + if not isinstance(serialized_interruptions, list): + return + if not serialized_interruptions and not current_step.response_accepted: return if len(current_step.interruptions) != len(serialized_interruptions): return @@ -6081,6 +6326,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.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.", @@ -6121,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.26.", + "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/fixtures/released_api_contract_policy.json b/tests/fixtures/released_api_contract_policy.json index e99f7ad363..256cc1de7c 100644 --- a/tests/fixtures/released_api_contract_policy.json +++ b/tests/fixtures/released_api_contract_policy.json @@ -574,6 +574,34 @@ } ], "public_properties": [ + { + "class_name": "RunResultBase", + "module": "agents.result", + "names": [ + "previous_outputs" + ] + }, + { + "class_name": "RunResult", + "module": "agents.result", + "names": [ + "previous_outputs" + ] + }, + { + "class_name": "RunResultStreaming", + "module": "agents.result", + "names": [ + "previous_outputs" + ] + }, + { + "class_name": "MessageReceipt", + "module": "agents.run_inbox", + "names": [ + "status" + ] + }, { "class_name": "RunState", "module": "agents.run_state", diff --git a/tests/models/test_codex_run_inbox.py b/tests/models/test_codex_run_inbox.py new file mode 100644 index 0000000000..fa246a6254 --- /dev/null +++ b/tests/models/test_codex_run_inbox.py @@ -0,0 +1,164 @@ +import asyncio + +import pytest +from openai import AsyncOpenAI + +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 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True], ids=["run", "streamed"]) +@pytest.mark.parametrize("follow_ups", [False, True], ids=["steer", "steer-and-queue"]) +async def test_codex_inbox_during_final_answer(tmp_path, threads, streamed, follow_ups): + # Only the native thread is scripted. Capture the inputs and replay history Codex receives. + release = asyncio.Event() + first = FakeThread(text="A draft.", gate=release) + requests = [(first, "Write a draft."), (FakeThread(text="Shorter draft."), "Shorten it.")] + if follow_ups: + requests.extend( + [ + (FakeThread(text="Title."), "Give it a title."), + (FakeThread(text="Summary."), "Summarize it."), + ] + ) + threads[0].extend(thread for thread, _ in requests) + agent = Agent(name="editor") + run_config = config(tmp_path) + + async def send_during_request(inbox): + try: + await asyncio.wait_for(first.started.wait(), 5) + # Submit queued tasks first so arrival order alone cannot satisfy the test. + queued = [inbox.queue(prompt) for _, prompt in requests[2:]] + receipts = [inbox.steer("Shorten it."), *queued] + assert all(receipt.status == "queued" for receipt in receipts) + return receipts + finally: + release.set() + + if streamed: + stream = Runner.run_streamed(agent, "Write a draft.", run_config=run_config) + sender = asyncio.create_task(send_during_request(stream)) + else: + inbox = RunInbox() + sender = asyncio.create_task(send_during_request(inbox)) + try: + if streamed: + async for _ in stream.stream_events(): + pass + result = stream + else: + result = await Runner.run(agent, "Write a draft.", inbox=inbox, run_config=run_config) + receipts = await sender + outcomes = await asyncio.wait_for(asyncio.gather(*(r.wait() for r in receipts)), 5) + assert [(outcome.status, outcome.turn_number) for outcome in outcomes] == [ + ("submitted", turn) for turn in range(2, len(requests) + 1) + ] + assert result.final_output == requests[-1][0].text + history = [] + for thread, prompt in requests: + assert thread.inputs == [{"type": "text", "text": prompt, "text_elements": []}] + assert [ + (item["role"], item["content"][0]["text"]) for item in thread.history + ] == history + history.extend([("user", prompt), ("assistant", thread.text)]) + assert thread.closed and not thread.interrupted + assert not threads[0] + finally: + 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/models/test_model_retry.py b/tests/models/test_model_retry.py index ff4c796918..2b857930c8 100644 --- a/tests/models/test_model_retry.py +++ b/tests/models/test_model_retry.py @@ -284,8 +284,10 @@ async def iterator() -> AsyncIterator[TResponseStreamEvent]: @pytest.mark.asyncio @pytest.mark.parametrize("payload_kind", ["text", "tool_arguments"]) +@pytest.mark.parametrize("timeout", [0.05, None], ids=["sdk_deadline", "provider_timeout"]) async def test_stream_timeout_discards_previous_event_from_retry_traceback( payload_kind: str, + timeout: float | None, ) -> None: sensitive_payload = "synthetic-sensitive-stream-payload" event: TResponseStreamEvent @@ -308,17 +310,20 @@ async def test_stream_timeout_discards_previous_event_from_retry_traceback( sequence_number=0, ) closed = asyncio.Event() + provider_timeout = ModelTimeoutError(3) async def stream_events(_call: ModelCall) -> AsyncIterator[TResponseStreamEvent]: try: yield event + if timeout is None: + raise provider_timeout await asyncio.Event().wait() finally: closed.set() model = ScriptedModel([ModelStep.stream(stream_events)]) result = Runner.run_streamed( - Agent(name="test", model=model, model_settings=ModelSettings(timeout=0.05)), + Agent(name="test", model=model, model_settings=ModelSettings(timeout=timeout)), "synthetic-input", run_config=RunConfig(trace_include_sensitive_data=False), ) @@ -331,11 +336,71 @@ async def stream_events(_call: ModelCall) -> AsyncIterator[TResponseStreamEvent] assert delivered == [event] assert event.delta == sensitive_payload assert closed.is_set() - assert exc_info.value.timeout_seconds == 0.05 + if timeout is None: + assert exc_info.value is provider_timeout + else: + assert exc_info.value.timeout_seconds == timeout assert exc_info.value.__cause__ is None assert exc_info.value.__context__ is None + _assert_timeout_retry_frame_cleared(exc_info.value) + + +@pytest.mark.asyncio +async def test_cancel_during_provider_timeout_close_clears_retry_frame() -> None: + closing = asyncio.Event() + timeout = ModelTimeoutError(3) + + class Stream: + sent = False + close_calls = 0 + + def __aiter__(self) -> AsyncIterator[TResponseStreamEvent]: + return self + + async def __anext__(self) -> TResponseStreamEvent: + if self.sent: + raise timeout + self.sent = True + return ResponseTextDeltaEvent( + type="response.output_text.delta", + delta="synthetic-private-text", + content_index=0, + output_index=0, + item_id="synthetic-item", + sequence_number=0, + logprobs=[], + ) + + async def aclose(self) -> None: + self.close_calls += 1 + closing.set() + await asyncio.Event().wait() + + stream = Stream() + events = stream_response_with_retry( + get_stream=lambda: stream, + rewind=lambda: asyncio.sleep(0), + retry_settings=None, + get_retry_advice=lambda _request: None, + previous_response_id=None, + conversation_id=None, + ) + await anext(events) + pull = asyncio.create_task(anext(events)) + try: + await asyncio.wait_for(closing.wait(), timeout=3) + finally: + pull.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(pull, timeout=3) + + assert stream.close_calls == 1 + _assert_timeout_retry_frame_cleared(timeout) + + +def _assert_timeout_retry_frame_cleared(error: ModelTimeoutError) -> None: retry_frames = [] - traceback = exc_info.value.__traceback__ + traceback = error.__traceback__ while traceback is not None: if traceback.tb_frame.f_code is stream_response_with_retry.__code__: retry_frames.append(traceback.tb_frame) @@ -345,7 +410,9 @@ async def stream_events(_call: ModelCall) -> AsyncIterator[TResponseStreamEvent] # Only the retry wrapper's aliases are covered, not caller-owned run state. assert frame.f_locals.get("event") is None assert frame.f_locals.get("result_value") is None + assert frame.f_locals.get("stream") is None assert frame.f_locals.get("stream_owner") is None + assert frame.f_locals.get("stream_requests") is None assert frame.f_locals.get("stream_results") is None 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 a71b527d4c..1685962eab 100644 --- a/tests/test_agent_hooks.py +++ b/tests/test_agent_hooks.py @@ -2,18 +2,33 @@ import json from collections import defaultdict +from copy import copy +from dataclasses import replace from typing import Any import pytest from typing_extensions import TypedDict -from agents.agent import Agent +from agents.agent import Agent, AgentBase +from agents.exceptions import UserError +from agents.guardrail import GuardrailFunctionOutput, output_guardrail +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 +from agents.run_config import CallModelData, ModelInputData, RunConfig from agents.run_context import AgentHookContext, RunContextWrapper, TContext -from agents.testing import ScriptedModel -from agents.tool import Tool +from agents.run_inbox import MessageReceipt, RunInbox +from agents.run_state import RunState +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, @@ -477,14 +492,1207 @@ async def test_base_agent_hooks_dont_crash(): class AgentHooksWithTurnInput(AgentHooks): - """Agent hooks that capture turn_input from on_start.""" + """Agent hooks that capture turn_input at the start and end of each task.""" def __init__(self): self.captured_turn_inputs: list[list[Any]] = [] + self.end_inputs: list[list[Any]] = [] async def on_start(self, context: AgentHookContext[TContext], agent: Agent[TContext]) -> None: self.captured_turn_inputs.append(list(context.turn_input)) + async def on_end( + self, context: AgentHookContext[TContext], agent: Agent[TContext], output: Any + ) -> None: + self.end_inputs.append(list(context.turn_input)) + + +async def _run_with_inbox( + agent: Agent[Any], + inbox: RunInbox, + streamed: bool, + *, + value: str | list[TResponseInputItem] | RunState[Any] = "first task", + server_managed: bool = False, + run_config: RunConfig | None = None, + context: RunContextWrapper[Any] | None = None, +) -> RunResult | RunResultStreaming: + if not streamed: + return await Runner.run( + agent, + value, + context=context, + inbox=inbox, + auto_previous_response_id=server_managed, + run_config=run_config, + ) + stream = Runner.run_streamed( + agent, + value, + context=context, + inbox=inbox, + auto_previous_response_id=server_managed, + run_config=run_config, + ) + async for _ in stream.stream_events(): + pass + return stream + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("queued", [False, True]) +@pytest.mark.parametrize("server_managed", [False, True]) +async def test_follow_up_turn_input_survives_tool_continuation( + streamed: bool, queued: bool, server_managed: bool +) -> None: + inbox = RunInbox() + hooks = AgentHooksWithTurnInput() + first = [{"role": "user", "content": "first task"}] + second = [{"role": "user", "content": "second task"}] + + def first_answer(call: ModelCall) -> list[Any]: + if queued: + inbox.queue("second task") + else: + inbox.steer("second task") + return [get_text_message("first answer")] + + def instructions(context: RunContextWrapper[Any], agent: Agent[Any]) -> str: + 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 + + @function_tool(is_enabled=enabled) + async def work() -> str: + inbox.steer("clarification") + return "done" + + model = ScriptedModel( + [ + ModelStep.respond(first_answer), + [get_function_tool_call("work", "{}")], + [get_text_message("second answer")], + ] + ) + 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 == [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 | clarification", + ] + 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 [ + item.get("content") for item in history if item.get("role") == "user" + ] == all_messages + transmitted = [ + item.get("content") for item in model.calls[-1].input if item.get("role") == "user" + ] + assert transmitted == (["clarification"] if server_managed else all_messages) + assert (model.calls[-1].previous_response_id is not None) == server_managed + if server_managed: + assert [item.get("type") or item.get("role") for item in model.calls[-1].input] == [ + "function_call_output", + "user", + ] + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("also_admitted", [None, "other instruction", "second task"]) +async def test_filtered_follow_up_keeps_task_input_on_server_retry( + streamed: bool, also_admitted: str | None +) -> None: + inbox = RunInbox() + hooks = AgentHooksWithTurnInput() + task = ["second task"] + ([also_admitted] if also_admitted else []) + expected = [{"role": "user", "content": text} for text in task] + + def first_answer(call: ModelCall) -> list[Any]: + if also_admitted: + for message in task: + inbox.steer(message) + else: + inbox.queue(task[0]) + return [get_text_message("first answer")] + + def instructions(context: RunContextWrapper[Any], agent: Agent[Any]) -> str: + 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 == expected + + @function_tool(is_enabled=enabled) + async def work() -> str: + # A new steer with identical text belongs to the ongoing tool turn. + inbox.steer(task[0]) + return "done" + + model = ScriptedModel( + [ + ModelStep.respond(first_answer), + [get_function_tool_call("work", "{}")], + [get_text_message("second answer")], + ] + ) + + def omit_first_occurrence(data: CallModelData[Any]) -> ModelInputData: + if len(model.calls) == 1: + data.model_data.input.pop(0) + return data.model_data + + agent = Agent(name="test", model=model, hooks=hooks, tools=[work], instructions=instructions) + await _run_with_inbox( + agent, + inbox, + streamed, + server_managed=True, + run_config=RunConfig(call_model_input_filter=omit_first_occurrence), + ) + assert [item.get("content") for item in model.calls[1].input] == task[1:] + assert [item.get("content") for item in model.calls[2].input if item.get("role") == "user"] == [ + task[0], + task[0], + ] + 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]) +async def test_cleared_pending_input_cannot_rejoin_follow_up_by_position(streamed: bool) -> None: + inbox = RunInbox() + hooks = AgentHooksWithTurnInput() + + def first_answer(call: ModelCall) -> list[Any]: + inbox.steer("kept") + inbox.steer("withheld") + return [get_text_message("first answer")] + + @function_tool(needs_approval=True) + async def work() -> str: + return "done" + + model = ScriptedModel( + [ + ModelStep.respond(first_answer), + [get_function_tool_call("work", "{}")], + [get_text_message("second answer")], + ] + ) + + def omit_last_occurrence(data: CallModelData[Any]) -> ModelInputData: + if len(model.calls) == 1: + data.model_data.input.pop() + return data.model_data + + agent = Agent(name="test", model=model, hooks=hooks, tools=[work]) + paused = await _run_with_inbox( + agent, + inbox, + streamed, + server_managed=True, + run_config=RunConfig(call_model_input_filter=omit_last_occurrence), + ) + state = paused.to_state() + assert [item.get("content") for item in state.pending_input] == ["withheld"] + state.clear_pending_input() + state.add_input("replacement") + state.approve(state.get_interruptions()[0]) + await _run_with_inbox(agent, RunInbox(), streamed, value=state) + assert [ + item.get("content") for item in model.calls[-1].input if item.get("role") == "user" + ] == ["replacement"] + assert hooks.end_inputs[-1] == [{"role": "user", "content": "kept"}] + + +@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, serialize: bool, server_managed: bool, omission: str | None +) -> None: + inbox = RunInbox() + hooks = AgentHooksWithTurnInput() + task = ["second task"] + if omission == "partial": + task.append("second instruction") + second = [{"role": "user", "content": text} for text in task] + effects: list[str] = [] + receipts: list[MessageReceipt] = [] + + def first_answer(call: ModelCall) -> list[Any]: + if omission == "partial": + receipts.extend(inbox.steer(text) for text in task) + else: + receipts.append(inbox.queue(task[0])) + return [get_text_message("first answer")] + + def omit_first(data: CallModelData[Any]) -> ModelInputData: + if len(model.calls) == 1: + data.model_data.input.pop(0) + return data.model_data + + def enabled(context: RunContextWrapper[Any], agent: AgentBase[Any]) -> bool: + return context.turn_input == second + + @function_tool(is_enabled=enabled, needs_approval=True) + async def work() -> str: + effects.append("approved") + return "done" + + model = ScriptedModel( + [ + ModelStep.respond(first_answer), + [get_function_tool_call("work", "{}")], + [get_text_message("second answer")], + ] + ) + agent = Agent(name="test", model=model, hooks=hooks, tools=[work]) + config = RunConfig(call_model_input_filter=omit_first) if omission else None + paused = await _run_with_inbox( + agent, inbox, streamed, server_managed=server_managed, run_config=config + ) + 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] + assert [item.get("content") for item in model.calls[1].input] == task[1:] + assert outcomes[0].status == "not_submitted" and outcomes[0].retained + assert all(outcome.status == "submitted" for outcome in outcomes[1:]) + state.approve(state.get_interruptions()[0]) + resumed = await _run_with_inbox(agent, RunInbox(), streamed, value=state) + assert resumed.final_output == "second answer" + assert effects == ["approved"] + assert hooks.end_inputs[-1] == second + assert model.calls[-1].tools + assert (model.calls[-1].previous_response_id is not None) == server_managed + if omission: + assert [ + item.get("content") for item in model.calls[-1].input if item.get("role") == "user" + ] == task[:1] + assert not state.pending_input + assert [await receipt.wait() for receipt in receipts] == outcomes + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_follow_up_keeps_output_guardrail_history_across_approval_pauses( + streamed: bool, +) -> None: + inbox = RunInbox() + + def first_answer(call: ModelCall) -> list[Any]: + inbox.queue("second task") + return [get_text_message("first answer")] + + @output_guardrail + def check( + ctx: RunContextWrapper[Any], agent: Agent[Any], output: Any + ) -> GuardrailFunctionOutput: + return GuardrailFunctionOutput(output_info=output, tripwire_triggered=False) + + @function_tool(needs_approval=True) + async def work() -> str: + return "done" + + model = ScriptedModel( + [ + ModelStep.respond(first_answer), + [get_function_tool_call("work", "{}", call_id=key) for key in ("one", "two")], + [get_text_message("second answer")], + ] + ) + agent = Agent(name="test", model=model, tools=[work], output_guardrails=[check]) + result = await _run_with_inbox(agent, inbox, streamed) + for remaining in (2, 1): + assert len(result.interruptions) == remaining + assert [r.output.output_info for r in result.output_guardrail_results] == ["first answer"] + state = result.to_state() + if remaining == 1: + state = await RunState.from_json(agent, state.to_json()) + state.approve(state.get_interruptions()[0]) + result = await _run_with_inbox(agent, RunInbox(), streamed, value=state) + + assert result.final_output == "second answer" + assert [r.output.output_info for r in result.output_guardrail_results] == [ + "first answer", + "second answer", + ] + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_delayed_approval_checkpoint_isolated_from_reused_context(streamed: bool) -> None: + context = RunContextWrapper(context=None) + hooks = AgentHooksWithTurnInput() + effects: list[str] = [] + + @function_tool(needs_approval=True) + async def work() -> str: + effects.append("approved") + return "done" + + first_model = ScriptedModel( + [ + [get_function_tool_call("work", "{}")], + [get_text_message("finished")], + ] + ) + first = Agent(name="first", model=first_model, tools=[work], hooks=hooks) + paused = await _run_with_inbox(first, RunInbox(), streamed, context=context) + assert len(paused.interruptions) == 1 and not effects + + inbox = RunInbox() + + def other_answer(call: ModelCall) -> list[Any]: + inbox.steer("other instruction") + inbox.steer("another instruction") + return [get_text_message("other answer")] + + other_model = ScriptedModel([ModelStep.respond(other_answer), [get_text_message("done")]]) + + def withhold_both(data: CallModelData[Any]) -> ModelInputData: + if len(other_model.calls) == 1: + data.model_data.input.clear() + return data.model_data + + await _run_with_inbox( + Agent(name="other", model=other_model), + inbox, + streamed, + value="other task", + context=context, + server_managed=True, + run_config=RunConfig(call_model_input_filter=withhold_both), + ) + + assert other_model.calls[-1].input == [] + + # The caller saves the paused run only after reusing the wrapper for another invocation. + state = paused.to_state() + state.approve(state.get_interruptions()[0]) + state.add_input("first clarification") + resumed = await _run_with_inbox(first, RunInbox(), streamed, value=state) + assert resumed.final_output == "finished" + assert effects == ["approved"] + assert [ + item.get("content") for item in first_model.calls[-1].input if item.get("role") == "user" + ] == ["first task", "first clarification"] + assert hooks.end_inputs[-1] == [{"role": "user", "content": "first task"}] + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize( + "filter_mode,serialize", + [ + ("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 +) -> None: + 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: + 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(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])) + 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", + model=ScriptedModel( + [ModelStep.respond(first_answer), [get_handoff_tool_call(destination, args="{}")]] + ), + handoffs=[ + 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 follow_up + expected = [[{"role": "user", "content": content}]] + 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 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"] + 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.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(): diff --git a/tests/test_approved_output.py b/tests/test_approved_output.py index cf84a2032d..c08a954f5d 100644 --- a/tests/test_approved_output.py +++ b/tests/test_approved_output.py @@ -552,7 +552,8 @@ async def test_hosted_child_raw_text_never_reaches_approval(previews): @pytest.mark.parametrize("ending", ["eof", "error", "cancel", "timeout"]) -async def test_pending_approval_expires_before_attempt_cleanup(ending): +@pytest.mark.parametrize("with_followup", [False, True]) +async def test_pending_approval_expires_before_attempt_cleanup(ending, with_followup): entered, closing, finish = asyncio.Event(), asyncio.Event(), asyncio.Event() reply = asyncio.get_running_loop().create_future() @@ -606,6 +607,7 @@ def approve(text): model_settings=ModelSettings(timeout=1 if ending == "timeout" else None), ) run = Runner.run_streamed(root, "start") + queued = run.queue("follow up") if with_followup else None reading = asyncio.create_task(collect(run.subscribe_approved_output(approve))) try: await asyncio.wait_for(entered.wait(), 5) @@ -628,6 +630,8 @@ def approve(text): error = {"eof": ModelBehaviorError, "error": ConnectionError, "timeout": ModelTimeoutError} with pytest.raises(error[ending]): await collect(run.stream_events()) + if queued is not None: + assert (await asyncio.wait_for(queued.wait(), 3)).status == "not_submitted" @pytest.mark.parametrize("timeout", [None, 30]) @@ -877,3 +881,22 @@ def approve(text): await collect(run.stream_events()) await asyncio.gather(reading, return_exceptions=True) assert thread.closed and run.final_output == thread.text + + +async def test_queued_task_emits_one_completion_after_the_last_guarded_answer(): + guarded = [] + + @output_guardrail + def check(ctx, agent, output): + guarded.append(output) + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=False) + + model = ScriptedModel([[assistant_message("first")], [assistant_message("second")]]) + run = Runner.run_streamed(Agent(name="root", model=model, output_guardrails=[check]), "start") + receipt = run.queue("follow up") + async with run.stream_approved_output() as reader: + events = await collect(reader) + assert [type(event) for event in events] == [RunCompleted] + assert guarded == ["first", "second"] + assert run.final_output == "second" + assert (await asyncio.wait_for(receipt.wait(), 3)).status == "submitted" diff --git a/tests/test_decisions.py b/tests/test_decisions.py index 3b7171dc9d..35547cd6e2 100644 --- a/tests/test_decisions.py +++ b/tests/test_decisions.py @@ -15,6 +15,7 @@ RunConfig, RunContextWrapper, RunHooks, + RunInbox, Runner, RunState, SQLiteSession, @@ -144,13 +145,13 @@ def source_agent(arguments=None): ) -async def run(source, stream, value="history", **kwargs): +async def run(source, stream, value="history", *, run_config=CONFIG, **kwargs): if stream: - result = Runner.run_streamed(source, value, run_config=CONFIG, **kwargs) + result = Runner.run_streamed(source, value, run_config=run_config, **kwargs) async for _ in result.stream_events(): pass return result - return await Runner.run(source, value, run_config=CONFIG, **kwargs) + return await Runner.run(source, value, run_config=run_config, **kwargs) def test_openai_single_target_suggests_ordinary_handoff(): @@ -714,6 +715,83 @@ def record(ctx: RunContextWrapper[dict[str, str]]) -> str: assert len(effects) == len(provider.requests) == 1 and effects[0] is fresh +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("clear_pending", [False, True], ids=["retained", "cleared"]) +@pytest.mark.parametrize("serialized", [False, True]) +async def test_specialist_resume_checks_current_follow_up_input(stream, clear_pending, serialized): + inbox = RunInbox() + effects = [] + + def first_answer(call): + inbox.steer("second task") + inbox.steer("include blue") + return [assistant_message("first answer")] + + def withhold_selection(data): + items = data.model_data.input + items[:] = [item for item in items if item.get("content") != "include blue"] + return data.model_data + + @tool(needs_approval=True) + def record() -> str: + effects.append("record") + return "done" + + blue = Agent( + name="Blue", + model=ScriptedModel([[function_call("record", {}, call_id="effect")]]), + tools=[record], + tool_use_behavior="stop_on_first_tool", + ) + source = Agent( + name="Source", + model=ScriptedModel( + [ + ModelStep.respond(first_answer), + [function_call("select_specialist", {"input": "evidence"}, call_id="transfer")], + ] + ), + decisions=OpenAIDecisions(client=Peer().client), + ) + source.handoffs.append( + decision_handoff( + source, + question="Which?", + targets={"blue": blue, "red": Agent(name="Red")}, + is_available=lambda ctx, label: ( + label == "red" + or any(item.get("content") == "include blue" for item in ctx.turn_input) + ), + ) + ) + paused = await run( + source, + stream, + inbox=inbox, + auto_previous_response_id=True, + run_config=replace(CONFIG, call_model_input_filter=withhold_selection), + ) + state = paused.to_state() + 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"): + await run(source, stream, state) + assert not effects + else: + assert (await run(source, stream, state)).final_output == "done" + assert effects == ["record"] + + @pytest.mark.parametrize("stream", [False, True]) @pytest.mark.parametrize("mode", ["memory", "loaded", "session"]) @pytest.mark.parametrize("nested", [False, True]) diff --git a/tests/test_guardrails.py b/tests/test_guardrails.py index fa132217cd..d4fb659811 100644 --- a/tests/test_guardrails.py +++ b/tests/test_guardrails.py @@ -16,6 +16,7 @@ OutputGuardrailTripwireTriggered, RunConfig, RunContextWrapper, + RunInbox, Runner, TResponseInputItem, UserError, @@ -28,6 +29,7 @@ from .test_responses import get_function_tool_call, get_text_message from .testing_processor import fetch_events +from .utils.simple_session import SimpleListSession SHORT_DELAY = 0.01 MEDIUM_DELAY = 0.03 @@ -540,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() @@ -559,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() @@ -576,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 @@ -740,6 +747,7 @@ async def test_parallel_guardrail_error_cancels_streaming_model(): model_started = asyncio.Event() model_cancelled = asyncio.Event() model_finished = asyncio.Event() + release_cleanup = asyncio.Event() @input_guardrail(run_in_parallel=True) async def raising_parallel_check( @@ -757,6 +765,7 @@ async def blocking_stream_response(*args, **kwargs): yield except asyncio.CancelledError: model_cancelled.set() + await release_cleanup.wait() raise finally: model_finished.set() @@ -773,14 +782,152 @@ async def consume_stream() -> None: with patch.object(model, "stream_response", side_effect=blocking_stream_response): result = Runner.run_streamed(agent, "trigger guardrail") - with pytest.raises(ValueError, match="guardrail boom"): - await asyncio.wait_for(consume_stream(), timeout=1) + consumer = asyncio.create_task(consume_stream()) + try: + await asyncio.wait_for(model_cancelled.wait(), timeout=1) + with pytest.raises(UserError, match="not accepting input"): + result.steer("too late") + finally: + release_cleanup.set() + with pytest.raises(ValueError, match="guardrail boom"): + await asyncio.wait_for(consumer, timeout=1) await asyncio.wait_for(model_finished.wait(), timeout=1) assert model_started.is_set() is True assert model_cancelled.is_set() is True +@pytest.mark.asyncio +@pytest.mark.parametrize("fails", [False, True]) +async def test_stream_waits_for_initial_guardrails_before_checking_a_steer(fails: bool) -> None: + in_tool, finish_tool, tool_output = asyncio.Event(), asyncio.Event(), asyncio.Event() + sibling_started, cleaning, release = asyncio.Event(), asyncio.Event(), asyncio.Event() + checked_steer = asyncio.Event() + + @function_tool + async def work() -> str: + in_tool.set() + await finish_tool.wait() + return "done" + + @input_guardrail + async def check(ctx, agent, value): + if value[0]["content"] == "start": + await in_tool.wait() + await sibling_started.wait() + if fails: + raise ValueError("initial guardrail failed") + else: + checked_steer.set() + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=False) + + @input_guardrail + async def sibling(ctx, agent, value): + if value[0]["content"] == "start": + sibling_started.set() + try: + await release.wait() + except asyncio.CancelledError: + cleaning.set() + await release.wait() + raise + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=False) + + model = ScriptedModel() + model.enqueue([get_function_tool_call("work", arguments="{}")]) + model.enqueue([get_text_message("finished")]) + agent = Agent(name="worker", model=model, tools=[work], input_guardrails=[check, sibling]) + inbox = RunInbox() + result = Runner.run_streamed( + agent, "start", inbox=inbox, run_config=RunConfig(tracing_disabled=True) + ) + receipt = result.steer("before the verdict") + + async def consume() -> None: + async for event in result.stream_events(): + if event.type == "run_item_stream_event" and event.name == "tool_output": + tool_output.set() + + consumer = asyncio.create_task(consume()) + try: + await asyncio.wait_for((cleaning if fails else in_tool).wait(), timeout=3) + finish_tool.set() + await asyncio.wait_for(tool_output.wait(), timeout=3) + # The tool has completed, but the initial guardrails have not settled. + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for(checked_steer.wait(), timeout=SHORT_DELAY) + if fails: + with pytest.raises(UserError, match="not accepting input"): + inbox.queue("during sibling cleanup") + with pytest.raises(UserError, match="not accepting input"): + result.steer("during sibling cleanup") + release.set() + if fails: + with pytest.raises(ValueError, match="initial guardrail failed"): + await asyncio.wait_for(consumer, timeout=3) + assert not checked_steer.is_set() + assert len(model.calls) == 1 + outcome = await asyncio.wait_for(receipt.wait(), timeout=3) + assert outcome.status == "not_submitted" and not outcome.retained + else: + await asyncio.wait_for(consumer, timeout=3) + assert checked_steer.is_set() + assert len(model.calls) == 2 + assert (await receipt.wait()).status == "submitted" + finally: + finish_tool.set() + release.set() + await asyncio.gather(consumer, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("guard", ["input", "output"]) +async def test_tripwire_closes_inbox_before_sibling_cleanup(streamed: bool, guard: str) -> None: + started = asyncio.Event() + inbox = RunInbox() + rejected = False + + async def trip(ctx, agent, value): + await started.wait() + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=True) + + async def sibling(ctx, agent, value): + nonlocal rejected + started.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + try: + inbox.queue("during sibling cleanup") + except UserError: + rejected = True + raise + + model = ScriptedModel() + model.enqueue([get_text_message("answer")]) + agent = Agent(name="guarded", model=model) + error: type[Exception] + if guard == "input": + agent.input_guardrails = [ + InputGuardrail(guardrail_function=fn, run_in_parallel=False) for fn in (trip, sibling) + ] + error = InputGuardrailTripwireTriggered + else: + agent.output_guardrails = [OutputGuardrail(guardrail_function=fn) for fn in (trip, sibling)] + error = OutputGuardrailTripwireTriggered + config = RunConfig(tracing_disabled=True) + + with pytest.raises(error): + if streamed: + result = Runner.run_streamed(agent, "start", inbox=inbox, run_config=config) + async for _ in result.stream_events(): + pass + else: + await Runner.run(agent, "start", inbox=inbox, run_config=config) + assert rejected + + @pytest.mark.asyncio async def test_model_error_before_guardrail_error_preserves_stream_finalization(): model_cleanup_started = asyncio.Event() @@ -1121,6 +1268,43 @@ async def security_check( assert not model.calls, "Model should not have been called" +@pytest.mark.asyncio +async def test_guardrail_trip_closes_stream_inbox_before_saving_input() -> None: + saving, release = asyncio.Event(), asyncio.Event() + + # Hold the rejected input's session write after the guardrail has decided the run must stop. + class Session(SimpleListSession): + async def add_items(self, items: list[TResponseInputItem]) -> None: + saving.set() + await release.wait() + await super().add_items(items) + + guardrail = InputGuardrail( + guardrail_function=get_sync_guardrail(triggers=True), run_in_parallel=False + ) + model = ScriptedModel() + result = Runner.run_streamed( + Agent(name="guarded", model=model, input_guardrails=[guardrail]), + "start", + session=Session(), + run_config=RunConfig(tracing_disabled=True), + ) + pending = result.queue("before the guardrail decision") + try: + await asyncio.wait_for(saving.wait(), timeout=3) + with pytest.raises(UserError, match="not accepting input"): + result.queue("after the guardrail decision") + finally: + release.set() + with pytest.raises(InputGuardrailTripwireTriggered): + async for _ in result.stream_events(): + pass + + outcome = await asyncio.wait_for(pending.wait(), timeout=3) + assert (outcome.status, outcome.reason) == ("not_submitted", "guardrail") + assert not model.calls + + @pytest.mark.asyncio async def test_parallel_guardrail_passes_agent_continues(): guardrail_executed = False diff --git a/tests/test_released_api_contract.py b/tests/test_released_api_contract.py index b9ead691b8..e3927b7a6e 100644 --- a/tests/test_released_api_contract.py +++ b/tests/test_released_api_contract.py @@ -3688,6 +3688,26 @@ def test_repository_release_policy_declares_v020_contract_surfaces() -> None: "agents.voice.testing", } ) == ( + { + "class_name": "RunResultBase", + "module": "agents.result", + "names": ["previous_outputs"], + }, + { + "class_name": "RunResult", + "module": "agents.result", + "names": ["previous_outputs"], + }, + { + "class_name": "RunResultStreaming", + "module": "agents.result", + "names": ["previous_outputs"], + }, + { + "class_name": "MessageReceipt", + "module": "agents.run_inbox", + "names": ["status"], + }, { "class_name": "RunState", "module": "agents.run_state", diff --git a/tests/test_run_budget.py b/tests/test_run_budget.py index 85b8f300e9..d7f5ad2be8 100644 --- a/tests/test_run_budget.py +++ b/tests/test_run_budget.py @@ -22,6 +22,7 @@ RunBudget, RunBudgetError, RunConfig, + RunInbox, Runner, RunState, ToolExecutionConfig, @@ -140,6 +141,94 @@ async def test_correction_uses_observed_totals(streamed, usage, policy, code): assert (await run(agent, budget, streamed)).final_output == "done" +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize( + "budget,total,operation,reason", + [ + (RunBudget(max_model_calls=1), 1, "queue", "run_budget_exceeded"), + (RunBudget(max_tokens=5), 5, "steer", "run_budget_exceeded"), + (RunBudget(max_tokens=5), None, "queue", "run_budget_usage_unavailable"), + ], +) +async def test_exhausted_budget_keeps_answer_without_admitting_inbox_input( + streamed, budget, total, operation, reason +): + inbox, session = RunInbox(), SimpleListSession() + receipts, guarded = [], [] + + @input_guardrail + def check(ctx, agent, value): + guarded.append(value) + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=False) + + def first(call): + send = inbox.steer if operation == "steer" else inbox.queue + receipts.append(send("over budget")) + return step(get_text_message("completed"), total) + + model = ScriptedModel([ModelStep.respond(first)]) + agent = Agent(name="root", model=model, input_guardrails=[check]) + result = await run(agent, budget, streamed, inbox=inbox, session=session) + + assert result.final_output == "completed" + assert result.previous_outputs == () + assert len(model.calls) == len(guarded) == 1 + outcome = await asyncio.wait_for(receipts[0].wait(), 3) + assert outcome.status == "not_submitted" and outcome.reason == reason + assert outcome.turn_number is None and not outcome.retained + for history in (await session.get_items(), result.to_input_list()): + initial, answer = history + assert initial["role"] == "user" and initial["content"] == "begin" + assert answer["role"] == "assistant" and answer["content"][0]["text"] == "completed" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_required_tool_turn_keeps_budget_error_without_admitting_a_steer(streamed): + inbox, session = RunInbox(), SimpleListSession() + receipts, guarded = [], [] + + @tool + async def work() -> str: + receipts.append(inbox.steer("optional steer")) + return "completed tool work" + + @input_guardrail + def check(ctx, agent, value): + guarded.append(value) + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=False) + + model = ScriptedModel([[get_function_tool_call("work", "{}")]]) + agent = Agent(name="root", model=model, tools=[work], input_guardrails=[check]) + with pytest.raises(RunBudgetError) as exc: + await run(agent, RunBudget(max_model_calls=1), streamed, inbox=inbox, session=session) + assert exc.value.limit == "model_calls" + assert len(model.calls) == len(guarded) == 1 + outcome = await asyncio.wait_for(receipts[0].wait(), 3) + assert outcome.status == "not_submitted" and not outcome.retained + history = await session.get_items() + assert [item["content"] for item in history if item.get("role") == "user"] == ["begin"] + assert history[-1]["output"] == "completed tool work" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_inbox_budget_check_leaves_the_last_call_available(streamed): + inbox = RunInbox() + + def first(call): + inbox.queue("within budget") + return step(get_text_message("first")) + + model = ScriptedModel([ModelStep.respond(first), step(get_text_message("last"), 5)]) + budget = RunBudget(max_model_calls=2, max_tokens=5, missing_usage="continue") + result = await run(Agent(name="root", model=model), budget, streamed, inbox=inbox) + assert len(model.calls) == 2 + assert result.previous_outputs == ("first",) + assert result.final_output == "last" + + @pytest.mark.asyncio @pytest.mark.parametrize("streamed", [False, True]) @pytest.mark.parametrize( @@ -732,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 new file mode 100644 index 0000000000..ccb4cd3289 --- /dev/null +++ b/tests/test_run_inbox.py @@ -0,0 +1,2881 @@ +"""Run inbox behavior at model, tool, and conversation boundaries.""" + +from __future__ import annotations + +import asyncio +import copy +from typing import Any + +import pytest + +from agents import ( + Agent, + AgentHooks, + ContinueWithFeedback, + GuardrailFunctionOutput, + InputGuardrail, + InputGuardrailTripwireTriggered, + ItemHelpers, + MaxTurnsExceeded, + MessageOutputItem, + MessageReceipt, + ModelResponse, + ModelSettings, + ModelTimeoutError, + OutputGuardrailTripwireTriggered, + RunConfig, + RunContextWrapper, + RunHooks, + RunInbox, + Runner, + RunState, + ToolCallOutputItem, + 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 +from agents.result import RunResultBase +from agents.retry import ModelRetrySettings +from agents.run import AgentRunner +from agents.testing import ModelStep, ScriptedModel, assistant_message, function_call +from agents.usage import Usage +from tests.test_responses import get_refusal_message +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 message_text(item: Any, role: str = "user") -> str | None: + if not isinstance(item, dict) or item.get("role") != role: + 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 := message_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]) + inbox = RunInbox() + task = asyncio.create_task(drive(streamed, agent, inbox=inbox)) + try: + await asyncio.gather(*(wait(event) for event in entered)) + first = inbox.steer("Explain the failure.") + second = inbox.steer("Then suggest a fix.") + assert first.status == second.status == "queued" + release[1].set() + await wait(completed[1]) + calls_while_waiting = model.calls + assert len(calls_while_waiting) == 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 message_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) + inbox = RunInbox() + task = asyncio.create_task(drive(streamed, agent, inbox=inbox, max_turns=1)) + try: + await wait(entered) + receipt = inbox.steer("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): + inbox.steer("too late") + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_steer_continues_after_a_final_model_response(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), [assistant_message("revised")]]) + inbox = RunInbox() + task = asyncio.create_task(drive(streamed, Agent(name="final", model=model), inbox=inbox)) + try: + await wait(entered) + receipt = inbox.steer("Revise that answer.") + release.set() + result = await asyncio.wait_for(task, 3) + assert result.final_output == "revised" + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert outcome.status == "submitted" and outcome.turn_number == 2 + assert len(model.calls) == 2 + assert messages(model.calls[0].input) == ["start"] + assert messages(model.calls[1].input) == ["start", "Revise that answer."] + assert model.calls[1].input[-2]["role"] == "assistant" + 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() + inbox = RunInbox() + with pytest.raises(UserError): + inbox.steer("before binding") + task = asyncio.create_task(drive(streamed, agent, inbox=inbox)) + try: + with pytest.raises(UserError): + inbox.steer("task has not started") + await wait(entered) + with pytest.raises(UserError): + await asyncio.to_thread(inbox.queue, "from a different thread") + release.set() + await asyncio.wait_for(task, 3) + with pytest.raises(UserError): + inbox.steer("after completion") + with pytest.raises(UserError): + await asyncio.wait_for(drive(streamed, agent, inbox=inbox), 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]) + inbox = RunInbox() + task = asyncio.create_task(drive(streamed, agent, inbox=inbox)) + try: + await wait(entered) + receipt = inbox.steer("This does not approve the call.") + queued = inbox.queue("Wait until the action is approved.") + release.set() + result = await asyncio.wait_for(task, 3) + assert len(result.interruptions) == 1 and effects == [] + skipped = await asyncio.wait_for(queued.wait(), 3) + assert skipped.status == "not_submitted" and skipped.retained is False + 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): + inbox.steer("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]) + inbox = RunInbox() + task = asyncio.create_task(drive(streamed, parent, inbox=inbox)) + try: + await wait(nested_entered) + receipt = inbox.steer("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() + inbox = RunInbox(max_pending=2) + task = asyncio.create_task(drive(streamed, agent, inbox=inbox)) + try: + await wait(entered) + first, second = inbox.steer("same"), inbox.steer("same") + with pytest.raises(UserError): + inbox.queue("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() + inbox = RunInbox() + task = asyncio.create_task(drive(streamed, agent, inbox=inbox)) + waiter = None + try: + await wait(entered) + receipt = inbox.steer("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", "merge", "instructions"]) +async def test_filter_outcome_tracks_occurrence_instead_of_equal_text( + streamed: bool, mode: str +) -> None: + agent, model, entered, release, _ = gate_tool() + inbox = RunInbox() + + def filter_input(data): + if mode == "drop": + data.model_data.input = [ + item for item in data.model_data.input if message_text(item) != "correction" + ] + elif mode == "copy": + data.model_data.input = copy.deepcopy(data.model_data.input) + elif "correction" in messages(data.model_data.input): + items = data.model_data.input + correction = items.pop() + if mode == "merge": + items[0].update(correction) + else: + data.model_data.instructions = message_text(correction) + return data.model_data + + task = asyncio.create_task( + drive( + streamed, + agent, + inbox=inbox, + run_config=RunConfig(call_model_input_filter=filter_input, tracing_disabled=True), + ) + ) + try: + await wait(entered) + receipt = inbox.steer("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 in {"copy", "merge"}) + if mode == "instructions": + assert model.calls[1].system_instructions == "correction" + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("queued", [False, True], ids=["steer", "queue"]) +async def test_live_guardrail_rejection_prevents_filter_model_and_session_exposure( + streamed: bool, + queued: 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)] + inbox = RunInbox() + task = asyncio.create_task( + drive( + streamed, + agent, + inbox=inbox, + session=session, + run_config=RunConfig(call_model_input_filter=filter_input, tracing_disabled=True), + ) + ) + try: + await wait(entered) + send = inbox.queue if queued else inbox.steer + receipt = 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) == (2 if queued else 1) + assert "blocked correction" not in filter_inputs + history = await session.get_items() + assert messages(history) == ["start"] + if queued: + assert history[-1].get("role") == "assistant" + assert message_text(history[-1], "assistant") == "done" + 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() + inbox = RunInbox() + task = asyncio.create_task(drive(streamed, agent, inbox=inbox)) + try: + await wait(entered) + receipt = inbox.steer("pending cancellation") + queued = inbox.queue("also pending") + 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 (await asyncio.wait_for(queued.wait(), 3)).status == "not_submitted" + assert len(model.calls) == 1 and not effects + with pytest.raises(UserError): + inbox.steer("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]) + inboxes = {name: RunInbox() for name in entered} + tasks = { + name: asyncio.create_task(drive(streamed, agent, context=name, inbox=inboxes[name])) + for name in entered + } + try: + await asyncio.gather(*(wait(event) for event in entered.values())) + receipts = {name: inboxes[name].steer(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]) +@pytest.mark.parametrize("server_managed", [False, True], ids=["local", "server"]) +@pytest.mark.parametrize( + "terminal", [False, True], ids=["steer-before-next-turn", "queue-after-terminal-tool"] +) +async def test_approved_tool_resume_accepts_input_before_tool_finishes( + streamed: bool, + server_managed: bool, + terminal: bool, +) -> None: + agent, model, entered, release, effects = gate_tool(approval=True, terminal=terminal) + paused = await drive(streamed, agent, auto_previous_response_id=server_managed) + state = paused.to_state() + state.approve(state.get_interruptions()[0]) + inbox = RunInbox() + task = asyncio.create_task(drive(streamed, agent, state, inbox=inbox)) + try: + await wait(entered) + send = inbox.queue if terminal else inbox.steer + receipt = send("Explain before editing again.") + assert receipt.status == "queued" and len(model.calls) == 1 + release.set() + result = await asyncio.wait_for(task, 3) + assert result.final_output == "done" + assert (await receipt.wait()).status == "submitted" + assert effects == ["worked"] + # ScriptedModel reuses the response ID. Keep both calls exactly once. + assert len(model.calls) == 2 + first, second = result.raw_responses + assert first.response_id == second.response_id + assert [first.output[0].type, second.output[0].type] == ["function_call", "message"] + saved = result.to_state().to_json()["model_responses"] + assert [response["output"][0]["type"] for response in saved] == [ + "function_call", + "message", + ] + 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("outcome", ["complete", "failure", "provider_timeout", "cancel"]) +async def test_inbox_closes_provider_stream_without_aclose(outcome: str) -> None: + entered = asyncio.Event() + close_calls = 0 + failure = ( + ModelTimeoutError(3) if outcome == "provider_timeout" else RuntimeError("provider failed") + ) + + # ScriptedModel normally returns an async generator, which always exposes aclose(). + class CloseOnlyModel(ScriptedModel): + def stream_response(self, *args: Any, **kwargs: Any) -> Any: + events = super().stream_response(*args, **kwargs) + + class Stream: + def __aiter__(self) -> Stream: + return self + + async def __anext__(self) -> Any: + entered.set() + if outcome == "cancel": + await asyncio.Event().wait() + return await anext(events) + + def close(self) -> None: + nonlocal close_calls + close_calls += 1 + raise RuntimeError("cleanup failed") + + return Stream() + + model = CloseOnlyModel( + [failure if outcome in ("failure", "provider_timeout") else [assistant_message("done")]] + ) + result = Runner.run_streamed( + Agent(name="worker", model=model), + "start", + inbox=RunInbox(), + run_config=RunConfig(tracing_disabled=True), + ) + + async def consume() -> None: + async for _ in result.stream_events(): + pass + + if outcome in ("failure", "provider_timeout"): + with pytest.raises(type(failure)) as caught: + await consume() + assert caught.value is failure + else: + if outcome == "cancel": + try: + await wait(entered) + finally: + result.cancel() + await consume() + if outcome == "complete": + assert result.final_output == "done" + assert close_calls == 1 + + +@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")], + [assistant_message("revised")], + ] + ) + agent.model = model + inbox = RunInbox() + 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, inbox=inbox, run_config=config)) + try: + await wait(entered) + first = inbox.steer("first correction") + release.set() + await wait(retry_entered) + assert first.status == "submitted" + second = inbox.steer("during retry") + retry_release.set() + await asyncio.wait_for(task, 3) + assert (await first.wait()).status == "submitted" + outcome = await asyncio.wait_for(second.wait(), 3) + assert outcome.status == "submitted" and outcome.turn_number == 3 + 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) + assert messages(model.calls[3].input) == ["start", "first correction", "during retry"] + finally: + await finish(task, release, retry_release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_steer_after_filter_cutoff_waits_for_later_request(streamed: bool) -> None: + agent, model, entered, release, _ = gate_tool() + model.enqueue([assistant_message("revised")]) + 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 + + inbox = RunInbox() + task = asyncio.create_task( + drive( + streamed, + agent, + inbox=inbox, + run_config=RunConfig(call_model_input_filter=filter_input, tracing_disabled=True), + ) + ) + try: + await wait(entered) + first = inbox.steer("before cutoff") + release.set() + await wait(filtering) + second = inbox.steer("after cutoff") + assert first.status == second.status == "queued" + allow_filter.set() + await asyncio.wait_for(task, 3) + assert (await first.wait()).status == "submitted" + outcome = await asyncio.wait_for(second.wait(), 3) + assert outcome.status == "submitted" and outcome.turn_number == 3 + assert messages(model.calls[1].input) == ["start", "before cutoff"] + assert messages(model.calls[2].input) == ["start", "before cutoff", "after cutoff"] + 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, inbox = SimpleListSession(), RunInbox() + task = asyncio.create_task(drive(streamed, agent, inbox=inbox, session=session)) + try: + await wait(entered) + receipt = inbox.steer("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]) + inbox = RunInbox() + task = asyncio.create_task( + drive(streamed, source, inbox=inbox, auto_previous_response_id=server_managed) + ) + try: + await wait(entered) + receipt = inbox.steer("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, inbox = SimpleListSession(), RunInbox() + 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, inbox=inbox, session=session, run_config=config) + ) + try: + await wait(entered) + receipt = inbox.steer("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 message_text(item) != "server correction" + ] + return data.model_data + + inbox = RunInbox() + task = asyncio.create_task( + drive( + streamed, + agent, + inbox=inbox, + auto_previous_response_id=True, + run_config=RunConfig(call_model_input_filter=filter_input, tracing_disabled=True), + ) + ) + try: + await wait(entered) + receipt = inbox.steer("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 message_text(item) != "resume correction" + ] + return data.model_data + + inbox = RunInbox() + task = asyncio.create_task( + drive( + streamed, + agent, + inbox=inbox, + auto_previous_response_id=True, + run_config=RunConfig(call_model_input_filter=omit_correction, tracing_disabled=True), + ) + ) + try: + await wait(entered) + receipt = inbox.steer("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, inbox=RunInbox()) + 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_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( + 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", + "history-missing-items", + "history-missing-context-flag", + "history-invalid-context-flag", + "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", + ], +) +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 == "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) + # 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] + 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-missing-context-flag": [0], + "history-invalid-context-flag": [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": [], + "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"], + "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, serialized: bool +) -> None: + class Session(SimpleListSession): + failed = False + + async def add_items(self, items): + if not self.failed and "second task" in messages(items): + self.failed = True + raise RuntimeError("follow-up append failed") + await super().add_items(items) + + effects: list[str] = [] + + def enabled(ctx, agent): + return messages(ctx.turn_input) == ["first task"] + + @function_tool(is_enabled=enabled) + def first_only() -> str: + effects.append("ran") + return "done" + + def respond_to_resume(call): + if call.tools: + return [function_call("first_only", "{}", call_id="first-only")] + return [assistant_message("done")] + + session = Session() + model = ScriptedModel( + [[assistant_message("first answer")], ModelStep.respond(respond_to_resume)] + ) + agent = Agent( + name="worker", + model=model, + instructions=lambda ctx, agent: " | ".join(messages(ctx.turn_input)), + tools=[first_only], + tool_use_behavior="stop_on_first_tool", + ) + stream = Runner.run_streamed( + agent, "first task", session=session, run_config=RunConfig(tracing_disabled=True) + ) + receipt = stream.queue("second task") + with pytest.raises(RuntimeError, match="follow-up append failed"): + async for _ in stream.stream_events(): + pass + outcome = await receipt.wait() + assert outcome.status == "not_submitted" and outcome.retained + assert len(model.calls) == 1 and model.calls[0].tools + 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" + + result = await drive(resume_streamed, agent, state, session=session) + assert result.final_output == "done" + assert len(model.calls) == 2 + request = model.calls[1] + assert messages(request.input) == ["first task", expected] + assert messages(await session.get_items()) == ["first task", expected] + assert not effects + assert not request.tools + assert request.system_instructions == expected + 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( + resume_streamed: bool, + clear_pending: bool, +) -> None: + effects: list[str] = [] + + def enabled(ctx, agent): + return "second task" in messages(ctx.turn_input) + + @function_tool(is_enabled=enabled) + def restricted() -> str: + effects.append("ran") + return "done" + + def fail_before_dispatch(data): + if "second task" in messages(data.model_data.input): + raise RuntimeError("filter failed") + return data.model_data + + def respond_to_resume(call): + if call.tools: + return [function_call("restricted", "{}", call_id="restricted-1")] + return [assistant_message("done")] + + model = ScriptedModel( + [[assistant_message("first answer")], ModelStep.respond(respond_to_resume)] + ) + agent = Agent( + name="worker", + model=model, + instructions=lambda ctx, agent: " | ".join(messages(ctx.turn_input)), + tools=[restricted], + tool_use_behavior="stop_on_first_tool", + ) + stream = Runner.run_streamed( + agent, + "first task", + auto_previous_response_id=True, + run_config=RunConfig(call_model_input_filter=fail_before_dispatch, tracing_disabled=True), + ) + receipt = stream.queue("second task") + with pytest.raises(RuntimeError, match="filter failed"): + async for _ in stream.stream_events(): + pass + assert len(model.calls) == 1 + outcome = await receipt.wait() + assert outcome.status == "not_submitted" and outcome.retained + + state = stream.to_state() + assert messages(state.pending_input) == ["second task"] + if clear_pending: + state.clear_pending_input() + state.add_input("replacement") + + result = await drive(resume_streamed, agent, state) + assert result.final_output == "done" + assert len(model.calls) == 2 + request = model.calls[1] + assert messages(request.input) == (["replacement"] if clear_pending else ["second task"]) + assert effects == ([] if clear_pending else ["ran"]) + assert bool(request.tools) == (not clear_pending) + 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() + model = ScriptedModel( + [ + [function_call("work", "{}", call_id="first")], + RuntimeError("request failed"), + ] + ) + agent.model = model + inbox = RunInbox() + task = asyncio.create_task(drive(streamed, agent, inbox=inbox, auto_previous_response_id=True)) + try: + await wait(entered) + receipt = inbox.steer("uncertain server acceptance") + queued = inbox.queue("skip after failure") + 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 (await asyncio.wait_for(queued.wait(), 3)).status == "not_submitted" + 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, inbox = SimpleListSession(), RunInbox() + task = asyncio.create_task( + drive( + streamed, + agent, + inbox=inbox, + session=session, + run_config=RunConfig( + model_provider=Provider(), model_selector=select, tracing_disabled=True + ), + ) + ) + try: + await wait(entered) + receipt = inbox.steer("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) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_steers_take_priority_and_each_queued_task_finishes_before_the_next( + streamed: bool, +) -> None: + inbox = RunInbox() + session = SimpleListSession() + receipts: list[MessageReceipt] = [] + guarded: list[str] = [] + + def first_response(call): + receipts.extend( + [ + inbox.queue("first task"), + inbox.steer("shorter"), + inbox.queue("second task"), + inbox.steer("in Spanish"), + ] + ) + return [assistant_message("initial answer")] + + @tool + def work() -> str: + return "first task tool result" + + @output_guardrail + def check_output(ctx, agent, output): + guarded.append(output) + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=False) + + model = ScriptedModel( + [ + ModelStep.respond(first_response), + [assistant_message("revised answer")], + [function_call("work", "{}", call_id="first-task")], + [assistant_message("first answer")], + [assistant_message("second answer")], + ] + ) + agent = Agent(name="worker", model=model, tools=[work], output_guardrails=[check_output]) + result = await drive(streamed, agent, inbox=inbox, session=session) + + steered = ["start", "shorter", "in Spanish"] + assert [messages(call.input) for call in model.calls] == [ + ["start"], + steered, + [*steered, "first task"], + [*steered, "first task"], + [*steered, "first task", "second task"], + ] + assert model.calls[3].input[-1]["output"] == "first task tool result" + assert result.final_output == "second answer" + assert guarded == ["initial answer", "revised answer", "first answer", "second answer"] + history = result.to_input_list() + for items in (history, await session.get_items()): + assert messages(items) == [*steered, "first task", "second task"] + assert [ + message_text(item, "assistant") for item in items if item.get("role") == "assistant" + ] == [ + "initial answer", + "revised answer", + "first answer", + "second answer", + ] + outcomes = await asyncio.wait_for(asyncio.gather(*(r.wait() for r in receipts)), 3) + assert [(o.status, o.turn_number) for o in outcomes] == [ + ("submitted", 3), + ("submitted", 2), + ("submitted", 5), + ("submitted", 2), + ] + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_queued_tasks_share_the_turn_limit_and_preserve_the_last_answer( + streamed: bool, +) -> None: + inbox = RunInbox() + receipts: list[MessageReceipt] = [] + + def respond(call): + receipts.extend([inbox.queue("within budget"), inbox.queue("over budget")]) + return [assistant_message("first")] + + model = ScriptedModel([ModelStep.respond(respond), [assistant_message("last")]]) + result = await drive(streamed, Agent(name="limited", model=model), inbox=inbox, max_turns=2) + assert result.final_output == "last" + assert len(model.calls) == 2 + assert messages(result.to_input_list()) == ["start", "within budget"] + first, skipped = await asyncio.wait_for(asyncio.gather(*(r.wait() for r in receipts)), 3) + assert first.status == "submitted" and first.turn_number == 2 + assert skipped.status == "not_submitted" and not skipped.retained + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_output_guardrail_can_stop_a_queued_followup(streamed: bool) -> None: + inbox = RunInbox() + receipts: list[MessageReceipt] = [] + + @output_guardrail + def reject(ctx, agent, output): + receipts.append(inbox.queue("never start")) + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=True) + + model = ScriptedModel([[assistant_message("blocked")]]) + agent = Agent(name="guarded", model=model, output_guardrails=[reject]) + with pytest.raises(OutputGuardrailTripwireTriggered): + await drive(streamed, agent, inbox=inbox) + assert len(model.calls) == 1 + outcome = await asyncio.wait_for(receipts[0].wait(), 3) + assert outcome.status == "not_submitted" and not outcome.retained + + +@pytest.mark.parametrize("explicit_inbox", [False, True]) +async def test_stream_accepts_immediate_input_and_emits_each_answer(explicit_inbox: bool) -> None: + inbox = RunInbox() if explicit_inbox else None + answers = ["original", "revised", "followup"] + model = ScriptedModel([[assistant_message(answer)] for answer in answers]) + result = Runner.run_streamed( + Agent(name="stream", model=model), + "start", + inbox=inbox, + run_config=RunConfig(tracing_disabled=True), + ) + try: + queued = (inbox or result).queue("next task") + steer = result.steer("revise") + assert queued.status == steer.status == "queued" + seen = [] + async for event in result.stream_events(): + if event.type == "run_item_stream_event" and isinstance(event.item, MessageOutputItem): + seen.append(ItemHelpers.text_message_output(event.item)) + assert seen == answers + assert result.final_output == "followup" + assert [messages(call.input) for call in model.calls] == [ + ["start"], + ["start", "revise"], + ["start", "revise", "next task"], + ] + submitted = await asyncio.wait_for(asyncio.gather(steer.wait(), queued.wait()), 3) + assert [outcome.status for outcome in submitted] == ["submitted", "submitted"] + with pytest.raises(UserError): + result.queue("too late") + finally: + if not result.is_complete: + result.cancel() + + +async def test_immediate_stream_cancellation_settles_receipts_before_first_request() -> None: + model = ScriptedModel() + inbox = RunInbox() + result = Runner.run_streamed( + Agent(name="stream", model=model), + "start", + inbox=inbox, + run_config=RunConfig(tracing_disabled=True), + ) + steer = result.steer("revise") + queued = result.queue("next task") + result.cancel() + try: + with pytest.raises(UserError): + result.steer("after cancel") + with pytest.raises(UserError): + inbox.queue("after cancel") + finally: + async for _ in result.stream_events(): + pass + outcomes = await asyncio.wait_for(asyncio.gather(steer.wait(), queued.wait()), 3) + assert [outcome.status for outcome in outcomes] == ["not_submitted", "not_submitted"] + assert len(model.calls) == 0 + with pytest.raises(UserError): + result.steer("too late") + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_handled_refusal_stops_queued_work(streamed: bool) -> None: + inbox = RunInbox() + receipts: list[MessageReceipt] = [] + + def refuse(call): + receipts.append(inbox.queue("never start")) + return [get_refusal_message("Cannot complete this task.")] + + ended: list[str] = [] + + class Hooks(AgentHooks): + async def on_end(self, context, agent, output): + ended.append(output) + with pytest.raises(UserError, match="not accepting"): + inbox.steer("too late") + with pytest.raises(UserError, match="not accepting"): + inbox.queue("too late") + + model = ScriptedModel([ModelStep.respond(refuse)]) + result = await drive( + streamed, + Agent(name="worker", model=model, hooks=Hooks()), + inbox=inbox, + error_handlers={"model_refusal": lambda data: "safe fallback"}, + ) + assert result.final_output == "safe fallback" + assert ended == ["safe fallback"] + assert len(model.calls) == 1 + assert messages(result.to_input_list()) == ["start"] + outcome = await asyncio.wait_for(receipts[0].wait(), 3) + assert outcome.status == "not_submitted" and not outcome.retained + + +async def test_cancel_after_turn_finishes_the_tool_without_starting_more_work() -> None: + agent, model, entered, release, effects = gate_tool() + result = Runner.run_streamed(agent, "start", run_config=RunConfig(tracing_disabled=True)) + try: + await wait(entered) + steer = result.steer("revise") + queued = result.queue("next task") + result.cancel(mode="after_turn") + release.set() + async for _ in result.stream_events(): + pass + assert effects == ["worked"] + assert len(model.calls) == 1 + outcomes = await asyncio.wait_for(asyncio.gather(steer.wait(), queued.wait()), 3) + assert [outcome.status for outcome in outcomes] == ["not_submitted", "not_submitted"] + finally: + release.set() + if not result.is_complete: + result.cancel() + + +async def test_cancel_after_turn_from_final_message_preserves_answer_and_skips_queue() -> None: + saved = asyncio.Event() + + # Hold the consumer until the first answer is durable so it can cancel at the turn boundary. + class Session(SimpleListSession): + async def add_items(self, items): + await super().add_items(items) + if any(item.get("role") == "assistant" for item in items): + saved.set() + + model = ScriptedModel([[assistant_message("first answer")]]) + result = Runner.run_streamed( + Agent(name="stream", model=model), + "start", + session=Session(), + run_config=RunConfig(tracing_disabled=True), + ) + queued = result.queue("next task") + seen = [] + async for event in result.stream_events(): + if event.type == "run_item_stream_event" and isinstance(event.item, MessageOutputItem): + seen.append(ItemHelpers.text_message_output(event.item)) + await wait(saved) + result.cancel(mode="after_turn") + assert seen == ["first answer"] + assert result.final_output == "first answer" + assert len(model.calls) == 1 + assert messages(result.to_input_list()) == ["start"] + outcome = await asyncio.wait_for(queued.wait(), 3) + assert outcome.status == "not_submitted" and not outcome.retained + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_queued_tasks_send_only_new_input_with_the_previous_response_id( + streamed: bool, +) -> None: + inbox = RunInbox() + receipts: list[MessageReceipt] = [] + + def first_response(call): + receipts.extend([inbox.queue("second task"), inbox.queue("third task")]) + return ModelStep(output=[assistant_message("first answer")], response_id="resp-first") + + model = ScriptedModel( + [ + ModelStep.respond(first_response), + ModelStep(output=[assistant_message("second answer")], response_id="resp-second"), + ModelStep(output=[assistant_message("third answer")], response_id="resp-third"), + ] + ) + result = await drive( + streamed, Agent(name="worker", model=model), inbox=inbox, auto_previous_response_id=True + ) + first, second, third = model.calls + assert first.previous_response_id is None + for call, previous_id, text in ( + (second, "resp-first", "second task"), + (third, "resp-second", "third task"), + ): + assert call.previous_response_id == previous_id + (item,) = call.input + assert message_text(item) == text + assert [receipt.status for receipt in receipts] == ["submitted", "submitted"] + assert result.final_output == "third answer" + assert result.previous_outputs == ("first answer", "second answer") + assert result.last_response_id == "resp-third" + assert result.to_state().pending_input == [] + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize( + "feedback, remove, status", + [ + ("policy feedback", None, "submitted"), + ("correction", "steer", "not_submitted"), + ("correction", "feedback", "submitted"), + ], +) +async def test_policy_feedback_does_not_own_the_steering_receipt( + streamed: bool, + feedback: str, + remove: str | None, + status: str, +) -> None: + inbox = RunInbox() + receipts: list[MessageReceipt] = [] + + def draft(call): + receipts.append(inbox.steer("correction")) + return [assistant_message("draft")] + + def filter_input(data): + items = data.model_data.input + if len(items) > 1: + assert messages(items) == ["start", "correction", feedback] + if remove is not None: + items.pop(-2 if remove == "steer" else -1) + return data.model_data + + model = ScriptedModel([ModelStep.respond(draft), [assistant_message("done")]]) + agent = Agent( + name="worker", + model=model, + hooks=AgentHooks( + final_output_policy=lambda ctx, proposal: ( + ContinueWithFeedback(feedback) if proposal.turn == 1 else "finish" + ) + ), + ) + await drive( + streamed, + agent, + inbox=inbox, + run_config=RunConfig( + tracing_disabled=True, call_model_input_filter=filter_input if remove else None + ), + ) + expected = ["start", "correction"] + if remove is None: + expected.append(feedback) + assert messages(model.calls[1].input) == expected + assert receipts[0].status == status + + +async def test_failed_stream_task_creation_closes_the_inbox() -> None: + loop = asyncio.get_running_loop() + previous_factory = loop.get_task_factory() + inbox = RunInbox() + + # Exercise the synchronous failure before the stream producer starts. + def reject(loop, coro, **kwargs): + raise RuntimeError("task factory rejected the producer") + + loop.set_task_factory(reject) + try: + with pytest.raises(RuntimeError, match="task factory rejected the producer"): + Runner.run_streamed( + Agent(name="worker", model=ScriptedModel()), + "start", + inbox=inbox, + run_config=RunConfig(tracing_disabled=True), + ) + finally: + loop.set_task_factory(previous_factory) + with pytest.raises(UserError): + inbox.steer("no producer") + + +async def test_sync_agent_runner_rejects_inbox_before_dispatch() -> None: + model = ScriptedModel([[assistant_message("unexpected")]]) + options: dict[str, Any] = {"inbox": RunInbox(), "run_config": RunConfig(tracing_disabled=True)} + with pytest.raises(TypeError, match="inbox"): + await asyncio.to_thread( + lambda: AgentRunner().run_sync(Agent(name="worker", model=model), "start", **options) + ) + assert not model.calls + + +@pytest.mark.parametrize("pause", ["guardrail", "persistence", "guardrail-after-tool"]) +async def test_cancel_after_turn_during_message_admission_stops_before_dispatch(pause: str) -> None: + entered, release = asyncio.Event(), asyncio.Event() + after_tool = pause == "guardrail-after-tool" + + async def suspend(): + entered.set() + await release.wait() + + async def check_input(ctx, agent, value): + if pause != "persistence" and isinstance(value, list) and "next" in messages(value): + await suspend() + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=False) + + # Pause the session write after the input guardrail has allowed the follow-up. + class Session(SimpleListSession): + async def add_items(self, items): + if pause == "persistence" and "next" in messages(items): + await suspend() + await super().add_items(items) + + @tool + def work() -> str: + return "tool result" + + session = Session() + first = ( + function_call("work", "{}", call_id="work-1") + if after_tool + else assistant_message("first answer") + ) + model = ScriptedModel([[first], [assistant_message("unexpected")]]) + agent = Agent( + name="worker", + model=model, + tools=[work], + input_guardrails=[InputGuardrail(guardrail_function=check_input)], + ) + result = Runner.run_streamed( + agent, "start", session=session, run_config=RunConfig(tracing_disabled=True) + ) + receipt = result.steer("next") if after_tool else result.queue("next") + try: + await wait(entered) + result.cancel(mode="after_turn") + release.set() + async for _ in result.stream_events(): + pass + assert len(model.calls) == result.current_turn == 1 + assert result.final_output == (None if after_tool else "first answer") + assert result.previous_outputs == () + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert outcome.status == "not_submitted" + assert outcome.retained == (pause == "persistence") + history = await session.get_items() + assert messages(history) == (["start", "next"] if pause == "persistence" else ["start"]) + if after_tool: + assert [ + item.get("output") for item in history if item.get("type") == "function_call_output" + ] == ["tool result"] + checkpoint = result.to_state().to_json() + assert [item["type"] for item in checkpoint["generated_items"]] == [ + "tool_call_item", + "tool_call_output_item", + ] + finally: + release.set() + if not result.is_complete: + result.cancel() + + +async def test_immediate_cancel_during_committed_input_write_never_dispatches() -> None: + saving, committed = asyncio.Event(), asyncio.Event() + effects: list[str] = [] + + # A session can finish a commit even when its caller requests cancellation. + class Session(SimpleListSession): + async def add_items(self, items): + if "next" in messages(items): + saving.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + await super().add_items(items) + committed.set() + return + await super().add_items(items) + + @tool + def work() -> str: + effects.append("unexpected") + return "done" + + session = Session() + model = ScriptedModel( + [[assistant_message("first")], [function_call("work", "{}", call_id="unexpected")]] + ) + result = Runner.run_streamed( + Agent(name="worker", model=model, tools=[work], tool_use_behavior="stop_on_first_tool"), + "start", + session=session, + run_config=RunConfig(tracing_disabled=True), + ) + receipt = result.queue("next") + try: + await wait(saving) + finally: + result.cancel() + async for _ in result.stream_events(): + pass + assert committed.is_set() + assert len(model.calls) == result.current_turn == 1 + assert effects == [] + assert result.previous_outputs == () and result.final_output is None + assert messages(await session.get_items()) == ["start", "next"] + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert (outcome.status, outcome.reason) == ("not_submitted", "cancelled") + assert outcome.retained + + +@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"): + pytest.skip("Python 3.10 cannot observe a cancellation swallowed by a callback") + entered, release = asyncio.Event(), asyncio.Event() + inbox = RunInbox() + receipts: list[MessageReceipt] = [] + + async def pause_before_dispatch() -> None: + entered.set() + try: + await release.wait() + except asyncio.CancelledError: + if mode == "propagate": + raise + if mode == "uncancel": + uncancel = getattr(asyncio.current_task(), "uncancel", None) + assert uncancel is not None + uncancel() + + 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): + if pause == "filter" and "next" in messages(data.model_data.input): + await pause_before_dispatch() + return data.model_data + + def first(call): + receipts.append(inbox.queue("next")) + return [assistant_message("first")] + + 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": + # The caller handled an earlier cancellation before starting this invocation. + owner = asyncio.current_task() + assert owner is not None + owner.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.sleep(0) + return await Runner.run( + agent, + "start", + inbox=inbox, + session=session, + run_config=config, + ) + + task = asyncio.create_task(run()) + try: + await wait(entered) + if mode == "preexisting": + release.set() + else: + task.cancel() + if mode in ("propagate", "swallow"): + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(task, 3) + assert len(model.calls) == 1 + else: + assert (await asyncio.wait_for(task, 3)).final_output == "second" + assert len(model.calls) == 2 + outcome = await asyncio.wait_for(receipts[0].wait(), 3) + if mode in ("propagate", "swallow"): + assert (outcome.status, outcome.reason) == ("not_submitted", "cancelled") + else: + assert outcome.status == "submitted" + 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: + await finish(task, release) + + +@pytest.mark.parametrize( + "queued,pause", + [(False, "model"), (True, "model"), (True, "prepare"), (True, "llm_end")], +) +async def test_immediate_cancel_prevents_effects_from_late_response( + queued: bool, pause: str +) -> None: + entered = asyncio.Event() + effects: list[str] = [] + end_hooks: list[str] = [] + + async def finish_despite_cancellation() -> None: + entered.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + pass + + @tool + async def work() -> str: + effects.append("tool") + return "unexpected" + + async def transfer(ctx: RunContextWrapper[Any]) -> None: + effects.append("handoff") + + async def respond(call): + if pause == "model": + await finish_despite_cancellation() + name = "work" if queued else "transfer_to_destination" + return ModelStep( + output=[function_call(name, "{}", call_id="late-call")], + response_id="resp-late", + usage=Usage(input_tokens=7, total_tokens=7), + ) + + async def prepare(call): + await finish_despite_cancellation() + return call.arguments + + class Hooks(AgentHooks): + async def on_llm_end(self, context, agent, response): + end_hooks.append(response.response_id) + if pause == "llm_end" and response.response_id == "resp-late": + await finish_despite_cancellation() + + model = ScriptedModel() + if queued: + model.enqueue(ModelStep(output=[assistant_message("first")], response_id="resp-first")) + model.enqueue(ModelStep.respond(respond)) + destination = Agent(name="destination", model=ScriptedModel()) + agent = Agent( + name="worker", + model=model, + tools=[work], + handoffs=[] if queued else [handoff(destination, on_handoff=transfer)], + hooks=Hooks(), + tool_use_behavior="stop_on_first_tool", + ) + result = Runner.run_streamed( + agent, + "start", + auto_previous_response_id=queued, + run_config=RunConfig( + tracing_disabled=True, + tool_execution=ToolExecutionConfig(prepare_tool_input=prepare) + if pause == "prepare" + else None, + ), + ) + receipt = result.queue("next") if queued else None + try: + await wait(entered) + finally: + result.cancel() + async for _ in result.stream_events(): + pass + + assert effects == [] + assert result.final_output is None + assert result.context_wrapper.usage.total_tokens == 7 + assert len(model.calls) == (2 if queued else 1) + expected_hooks = ["resp-first"] if queued else [] + if pause == "llm_end": + expected_hooks.append("resp-late") + assert end_hooks == expected_hooks + if receipt is not None: + assert (await receipt.wait()).status == "submitted" + assert result.previous_outputs == ("first",) + state = result.to_state() + assert state.pending_input == [] + assert [response["response_id"] for response in state.to_json()["model_responses"]] == [ + "resp-first", + "resp-late", + ] + + +@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() + + async def filter_input(data): + if "next" in messages(data.model_data.input): + filtering.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + pass + return data.model_data + + model = ScriptedModel([[assistant_message("first")], [assistant_message("unexpected")]]) + result = Runner.run_streamed( + Agent(name="worker", model=model), + "start", + run_config=RunConfig(tracing_disabled=True, call_model_input_filter=filter_input), + ) + receipt = result.queue("next") + try: + await wait(filtering) + finally: + result.cancel() + async for _ in result.stream_events(): + pass + assert len(model.calls) == 1 + assert result.previous_outputs == ("first",) and result.final_output is None + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert (outcome.status, outcome.reason) == ("not_submitted", "cancelled") + assert outcome.retained + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("resumed", [False, True]) +async def test_approval_pause_closes_intake_before_session_write( + streamed: bool, resumed: bool +) -> None: + saving, release = asyncio.Event(), asyncio.Event() + inbox = RunInbox() + receipts: list[MessageReceipt] = [] + + # Hold the append of the new call, or the approved sibling's output on resume. + class Session(SimpleListSession): + async def add_items(self, items): + target = "function_call_output" if resumed else "function_call" + if any(item.get("type") == target for item in items): + saving.set() + await release.wait() + await super().add_items(items) + + @tool(needs_approval=True) + async def protected() -> str: + receipts.append(inbox.queue("during approved tool")) + return "worked" + + def first_response(call): + if not resumed: + receipts.append(inbox.queue("before approval pause")) + return [function_call("protected", "{}", call_id=key) for key in ("one", "two")] + + session = Session() + model = ScriptedModel([ModelStep.respond(first_response)]) + agent = Agent(name="worker", model=model, tools=[protected]) + value: Any = "start" + if resumed: + first = await drive(streamed, agent, session=session) + value = first.to_state() + value.approve(value.get_interruptions()[0]) + task = asyncio.create_task(drive(streamed, agent, value, inbox=inbox, session=session)) + try: + await wait(saving) + with pytest.raises(UserError, match="not accepting input"): + inbox.steer("during approval persistence") + release.set() + result = await asyncio.wait_for(task, 3) + assert len(result.interruptions) == (1 if resumed else 2) + assert len(receipts) == 1 + outcome = await asyncio.wait_for(receipts[0].wait(), 3) + assert (outcome.status, outcome.reason) == ("not_submitted", "approval_pause") + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_tool_failure_closes_inbox_before_saving_completed_sibling(streamed: bool) -> None: + finished, saving, release = asyncio.Event(), asyncio.Event(), asyncio.Event() + inbox = RunInbox() + receipts: list[MessageReceipt] = [] + + @function_tool + async def success() -> str: + receipts.append(inbox.queue("before failure")) + return "completed" + + class Hooks(AgentHooks): + async def on_tool_end(self, context, agent, tool, result): + if tool.name == "success": + finished.set() + + @function_tool(failure_error_function=None) + async def failure() -> str: + await finished.wait() + raise ValueError("terminal tool failure") + + class Session(SimpleListSession): + async def add_items(self, items): + if any(item.get("type") == "function_call_output" for item in items): + saving.set() + await release.wait() + await super().add_items(items) + + model = ScriptedModel( + [[function_call("success", {}, call_id="ok"), function_call("failure", {}, call_id="bad")]] + ) + agent = Agent(name="worker", model=model, tools=[success, failure], hooks=Hooks()) + session = Session() + config = RunConfig(tracing_disabled=True) + stream = ( + Runner.run_streamed(agent, "start", inbox=inbox, session=session, run_config=config) + if streamed + else None + ) + + async def consume(): + if stream is None: + await Runner.run(agent, "start", inbox=inbox, session=session, run_config=config) + else: + async for _ in stream.stream_events(): + pass + + task = asyncio.create_task(consume()) + try: + await wait(saving) + sender = stream or inbox + with pytest.raises(UserError, match="not accepting input"): + sender.steer("too late") + with pytest.raises(UserError, match="not accepting input"): + sender.queue("too late") + release.set() + with pytest.raises(UserError, match="terminal tool failure"): + await asyncio.wait_for(task, 3) + assert len(model.calls) == 1 + history = await session.get_items() + assert [ + item["output"] for item in history if item.get("type") == "function_call_output" + ] == ["completed"] + outcome = await asyncio.wait_for(receipts[0].wait(), 3) + assert (outcome.status, outcome.reason) == ("not_submitted", "run_failed") + finally: + await finish(task, release) + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("ending", ["approval", "failure"]) +async def test_terminal_run_rejects_messages_while_cleanup_waits( + streamed: bool, ending: str +) -> None: + cleaning, release = asyncio.Event(), asyncio.Event() + + # ScriptedModel normally completes run-end cleanup without yielding to the caller. + class Model(ScriptedModel): + async def _cleanup_on_run_end(self, owner: object) -> None: + cleaning.set() + await release.wait() + + @tool(needs_approval=True) + def protected() -> str: + pytest.fail("The pending tool has not been approved.") + + step = ( + [function_call("protected", "{}", call_id="protected-1")] + if ending == "approval" + else RuntimeError("provider failed") + ) + inbox = RunInbox() + receipts: list[MessageReceipt] = [] + + def respond(call): + receipts.append(inbox.queue("before shutdown")) + return step + + agent = Agent(name="worker", model=Model([ModelStep.respond(respond)]), tools=[protected]) + config = RunConfig(tracing_disabled=True) + result = ( + Runner.run_streamed(agent, "start", inbox=inbox, run_config=config) if streamed else None + ) + + async def consume(): + if result is None: + return await Runner.run(agent, "start", inbox=inbox, run_config=config) + async for _ in result.stream_events(): + pass + return result + + task = asyncio.create_task(consume()) + try: + await wait(cleaning) + if result is not None: + assert result.is_complete + assert len(result.interruptions) == (1 if ending == "approval" else 0) + with pytest.raises(UserError): + result.steer("during cleanup") + with pytest.raises(UserError): + inbox.queue("during cleanup") + release.set() + if ending == "failure": + with pytest.raises(RuntimeError, match="provider failed"): + await asyncio.wait_for(task, 3) + else: + assert len((await asyncio.wait_for(task, 3)).interruptions) == 1 + finally: + await finish(task, release) + outcome = await asyncio.wait_for(receipts[0].wait(), 3) + assert outcome.status == "not_submitted" + assert outcome.reason == ("approval_pause" if ending == "approval" else "run_failed") + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_tool_callback_answer_stays_out_of_the_queued_task_transcript( + streamed: bool, +) -> None: + inbox, session = RunInbox(), SimpleListSession() + guarded: list[str] = [] + events: list[tuple[str, str]] = [] + + @tool + def compute() -> str: + return "raw=21" + + @output_guardrail + def check(ctx, agent, output): + guarded.append(output) + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=False) + + def first(call): + inbox.queue("repeat the answer") + return [function_call("compute", "{}", call_id="compute-1")] + + model = ScriptedModel([ModelStep.respond(first), [assistant_message("last answer")]]) + agent = Agent( + name="worker", + model=model, + tools=[compute], + output_guardrails=[check], + tool_use_behavior=lambda ctx, results: ToolsToFinalOutputResult( + is_final_output=True, final_output="Approved answer is 42" + ), + ) + config = RunConfig(tracing_disabled=True) + result: RunResultBase + if streamed: + result = Runner.run_streamed( + agent, "start", inbox=inbox, session=session, run_config=config + ) + async for event in result.stream_events(): + assert "Approved answer is 42" not in repr(event) + if event.type != "run_item_stream_event": + continue + if isinstance(event.item, ToolCallOutputItem): + events.append(("tool", event.item.output)) + elif isinstance(event.item, MessageOutputItem): + events.append(("assistant", ItemHelpers.text_message_output(event.item))) + else: + result = await Runner.run(agent, "start", inbox=inbox, session=session, run_config=config) + + def transcript(items): + entries = [] + for item in items: + if item.get("type") == "function_call_output": + entries.append(("tool", item["output"])) + elif item.get("role") in ("assistant", "user"): + content = item["content"] + text = ( + content + if isinstance(content, str) + else "".join(part["text"] for part in content) + ) + entries.append((item["role"], text)) + return entries + + expected = [ + ("user", "start"), + ("tool", "raw=21"), + ("user", "repeat the answer"), + ("assistant", "last answer"), + ] + assert result.final_output == "last answer" + assert result.previous_outputs == ("Approved answer is 42",) + assert guarded == ["Approved answer is 42", "last answer"] + history = result.to_input_list() + saved = await session.get_items() + assert "Approved answer is 42" not in repr( + ( + model.calls[1].input, + model.calls[1].system_instructions, + history, + saved, + ) + ) + assert transcript(model.calls[1].input) == expected[:-1] + assert transcript(history) == expected + assert transcript(saved) == expected + if streamed: + assert events == [entry for entry in expected if entry[0] != "user"] + + +def agent_with_two_callback_answers(inbox: RunInbox, answer, *, output_type=str): + @tool + def work() -> str: + return "public tool result" + + def first(call): + inbox.queue("next task") + return [function_call("work", "{}", call_id="first")] + + return Agent( + name="worker", + model=ScriptedModel( + [ModelStep.respond(first), [function_call("work", "{}", call_id="second")]] + ), + tools=[work], + output_type=output_type, + tool_use_behavior=lambda ctx, results: ToolsToFinalOutputResult( + is_final_output=True, final_output=answer() + ), + ) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_previous_output_snapshots_a_mutable_callback_answer(streamed: bool) -> None: + inbox = RunInbox() + shared: list[list[str]] = [[]] + + def answer(): + shared[0].append("answer") + return shared + + agent = agent_with_two_callback_answers(inbox, answer, output_type=list[list[str]]) + result = await drive(streamed, agent, inbox=inbox) + assert result.final_output == [["answer", "answer"]] + assert result.previous_outputs == ([["answer"]],) + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_redaction_checks_secrets_spanning_private_callback_answers(streamed: bool) -> None: + inbox = RunInbox() + parts = ["synthetic-", "secret"] + agent = agent_with_two_callback_answers(inbox, lambda: parts.pop(0)) + config = RunConfig( + tracing_disabled=True, + redact_text=lambda text: text.replace("synthetic-secret", "[removed]"), + ) + with pytest.raises(UserError, match="redact_text"): + await drive(streamed, agent, inbox=inbox, run_config=config) + assert parts == [] + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_previous_output_copies_model_fields_without_copying_private_resources( + streamed: bool, +) -> None: + from collections import UserList, deque + from collections.abc import Sequence + from functools import cached_property + from threading import Lock + + from pydantic import BaseModel, PrivateAttr, computed_field, field_serializer + + class Answer(BaseModel): + values: deque[int] + _lock: Any = PrivateAttr(default_factory=Lock) + + @computed_field # type: ignore[prop-decorator] + @cached_property + def displayed_values(self) -> deque[int]: + return self.values + + class Page(BaseModel): + rows: Sequence[Answer] + + @field_serializer("rows") + def serialize_rows(self, rows: Sequence[Answer]) -> list[Answer]: + return list(rows) + + inbox = RunInbox() + shared = Answer(values=deque()) + + page = Page(rows=UserList([shared])) + + def answer() -> Page: + shared.values.append(len(shared.values) + 1) + shared.model_dump() # Materialize the cached field before returning the answer. + return page + + agent = agent_with_two_callback_answers(inbox, answer, output_type=Page) + result = await drive(streamed, agent, inbox=inbox) + (first_page,) = result.previous_outputs + assert isinstance(first_page.rows, UserList) + (first,) = first_page.rows + assert isinstance(first, Answer) + assert list(first.values) == [1] + assert first.displayed_values is first.values + assert first.model_dump(mode="json") == {"values": [1], "displayed_values": [1]} + assert first._lock is shared._lock + assert list(result.final_output.rows[0].values) == [1, 2] + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("failure", ["guardrail", "policy", "redaction"]) +async def test_rejection_closes_intake_before_saving_tool_results( + streamed: bool, failure: str +) -> None: + inbox = RunInbox() + checking_output = False + rejections: list[str] = [] + + class Session(SimpleListSession): + async def add_items(self, items): + if checking_output: + for send in (inbox.queue, inbox.steer): + try: + send("too late") + except UserError as error: + rejections.append(str(error)) + await super().add_items(items) + + @output_guardrail + def check_output(ctx, agent, output): + nonlocal checking_output + checking_output = True + if failure == "redaction": + # The guardrail passes. The subsequent check must reject the changed answer. + output.append("synthetic-secret") + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=False) + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=True) + + def fail_policy(ctx, proposal): + nonlocal checking_output + checking_output = True + raise RuntimeError("policy failed") + + agent, model, _, release, effects = gate_tool(terminal=True) + config = RunConfig(tracing_disabled=True) + error: type[Exception] = OutputGuardrailTripwireTriggered + match = None + if failure == "policy": + agent.hooks = AgentHooks(final_output_policy=fail_policy) + error, match = RuntimeError, "policy failed" + elif failure == "redaction": + agent.output_type = list[str] + agent.tool_use_behavior = lambda ctx, results: ToolsToFinalOutputResult( + is_final_output=True, final_output=["answer"] + ) + agent.hooks = AgentHooks(final_output_policy=lambda ctx, proposal: "continue") + config.redact_text = lambda text: text.replace("synthetic-secret", "[removed]") + error, match = UserError, "redact_text" + agent.output_guardrails = [check_output] + release.set() + session = Session() + with pytest.raises(error, match=match): + await drive(streamed, agent, inbox=inbox, session=session, run_config=config) + assert len(rejections) == 2 + assert all("not accepting" in message for message in rejections) + assert len(model.calls) == 1 + assert effects == ["worked"] + if failure == "redaction": + saved = await session.get_items() + assert saved[-1]["type"] == "function_call_output" + assert "synthetic-secret" not in repr(saved) + + +@pytest.mark.skipif(not hasattr(asyncio.Task, "cancelling"), reason="Requires Task.cancelling") +async def test_awaited_retry_does_not_dispatch_after_owner_cancellation() -> None: + inbox = RunInbox() + entered = asyncio.Event() + receipts: list[MessageReceipt] = [] + + def first(call): + receipts.append(inbox.queue("next")) + return [assistant_message("first")] + + async def retry_policy(ctx): + entered.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + return True + + model = ScriptedModel( + [ + ModelStep.respond(first), + ModelStep.raise_error(RuntimeError("transient")), + [assistant_message("unexpected retry")], + ] + ) + config = RunConfig( + tracing_disabled=True, + model_settings=ModelSettings( + retry=ModelRetrySettings( + max_retries=1, backoff={"initial_delay": 0}, policy=retry_policy + ) + ), + ) + task = asyncio.create_task( + Runner.run(Agent(name="worker", model=model), "start", inbox=inbox, run_config=config) + ) + try: + await wait(entered) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(task, 3) + assert len(model.calls) == 2 + assert (await receipts[0].wait()).status == "submitted" + finally: + await finish(task) 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_run_state_pending_input.py b/tests/test_run_state_pending_input.py index 2f159d9693..f76ff8c01e 100644 --- a/tests/test_run_state_pending_input.py +++ b/tests/test_run_state_pending_input.py @@ -6,13 +6,26 @@ import httpx2 import pytest from openai import AsyncOpenAI, BadRequestError -from openai.types.responses import ResponseReasoningItem +from openai.types.responses import ResponseOutputItem, ResponseReasoningItem from openai.types.responses.response_computer_tool_call import ( ActionScreenshot, ResponseComputerToolCall, ) -from agents import Agent, ComputerTool, InputItem, RunConfig, Runner, function_tool, tool_namespace +from agents import ( + Agent, + ComputerTool, + InputItem, + RunConfig, + Runner, + ToolGuardrailFunctionOutput, + ToolInputGuardrailData, + ToolOutputGuardrailData, + function_tool, + tool_input_guardrail, + tool_namespace, + tool_output_guardrail, +) from agents.exceptions import InputGuardrailTripwireTriggered, ModelBehaviorError, UserError from agents.guardrail import GuardrailFunctionOutput, InputGuardrail from agents.items import ModelResponse, TResponseInputItem @@ -835,6 +848,7 @@ async def on_llm_end( model, agent, state, _calls = await _make_after_turn_state(auto_previous_response_id=True) agent_hooks = CountAgentResponseHook() agent.hooks = agent_hooks + prior_response_count = len(state.to_json()["model_responses"]) state.add_input("Late input") model.enqueue([get_text_message("Accepted")]) @@ -843,6 +857,12 @@ async def on_llm_end( with pytest.raises(RuntimeError, match="after response"): async for _event in failed.stream_events(): pass + # A failed stream still checkpoints the response accepted before the hook ran. + checkpoint = failed.to_state() + saved = checkpoint.to_json()["model_responses"] + assert len(saved) == prior_response_count + 1 + assert saved == state.to_json()["model_responses"] + state = checkpoint else: with pytest.raises(RuntimeError, match="after response"): await Runner.run(agent, state, hooks=FailAfterResponse()) @@ -857,12 +877,139 @@ async def on_llm_end( state = await RunState.from_json(agent, state.to_json()) queued_outputs = model.remaining_steps + calls_before_recovery = len(model.calls) recovered = await Runner.run(agent, state) + assert len(model.calls) == calls_before_recovery assert recovered.final_output == "Accepted" assert agent_hooks.call_count == 1 assert model.remaining_steps == queued_outputs +@pytest.mark.asyncio +async def test_queued_answer_survives_stream_hook_failure() -> None: + class Hooks(RunHooks[Any]): + def __init__(self) -> None: + self.calls = 0 + + async def on_llm_end( + self, context: RunContextWrapper[Any], agent: Agent[Any], response: ModelResponse + ) -> None: + self.calls += 1 + if self.calls == 2: + raise RuntimeError("after queued answer") + + model = ScriptedModel([[get_text_message("First")], [get_text_message("Second")]]) + agent = Agent(name="assistant", model=model) + hooks = Hooks() + stream = Runner.run_streamed(agent, "First task", auto_previous_response_id=True, hooks=hooks) + receipt = stream.queue("Second task") + with pytest.raises(RuntimeError, match="after queued answer"): + async for _event in stream.stream_events(): + pass + + recovered = await Runner.run(agent, stream.to_state(), hooks=hooks) + assert recovered.final_output == "Second" + assert len(model.calls) == len(recovered.raw_responses) == hooks.calls == 2 + assert (await receipt.wait()).status == "submitted" + assert [item.get("role") for item in recovered.to_input_list()] == [ + "user", + "assistant", + "user", + "assistant", + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("serialize", [False, True]) +@pytest.mark.parametrize("streamed_resume", [False, True]) +async def test_queued_tool_recovery_uses_failed_stream_checkpoint( + serialize: bool, streamed_resume: bool +) -> None: + effects: list[str] = [] + ended: 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(tool_input_guardrails=[check_input], tool_output_guardrails=[check_output]) + def record(destination: str) -> str: + effects.append(destination) + return f"recorded:{destination}" + + class Hooks(RunHooks[Any]): + async def on_tool_end( + self, context: RunContextWrapper[Any], agent: Agent[Any], tool: Tool, result: Any + ) -> None: + ended.append(result) + if result == "recorded:Rome": + raise RuntimeError("after recording Rome") + + def record_call(destination: str) -> ResponseOutputItem: + return get_function_tool_call( + "record", json.dumps({"destination": destination}), call_id=f"call-{destination}" + ) + + model = ScriptedModel( + [ + [record_call("Paris")], + [get_text_message("First task done")], + [record_call("Rome")], + [get_text_message("Second task done")], + ] + ) + agent = Agent(name="assistant", model=model, tools=[record]) + hooks = Hooks() + failed = Runner.run_streamed(agent, "Record Paris", auto_previous_response_id=True, hooks=hooks) + receipt = failed.queue("Record Rome") + with pytest.raises(UserError, match="after recording Rome"): + async for _event in failed.stream_events(): + pass + + outcome = await receipt.wait() + assert outcome.status == "submitted" + assert len(model.calls) == 3 + assert effects == ["Paris", "Rome"] + state = failed.to_state() + if serialize: + state = await RunState.from_json(agent, state.to_json()) + if streamed_resume: + recovered = Runner.run_streamed(agent, state, hooks=hooks) + async for _event in recovered.stream_events(): + pass + else: + recovered = await Runner.run(agent, state, hooks=hooks) + assert recovered.final_output == "Second task done" + assert len(model.calls) == len(recovered.raw_responses) == 4 + assert effects == ["Paris", "Rome"] + assert ended == ["recorded:Paris", "recorded:Rome"] + for history in (recovered.to_input_list(), recovered.to_input_list(mode="normalized")): + assert [ + (item.get("type"), item.get("call_id")) for item in history if item.get("call_id") + ] == [ + ("function_call", "call-Paris"), + ("function_call_output", "call-Paris"), + ("function_call", "call-Rome"), + ("function_call_output", "call-Rome"), + ] + assert [r.output.output_info for r in recovered.tool_input_guardrail_results] == [ + "call-Paris", + "call-Rome", + ] + assert [r.output.output_info for r in recovered.tool_output_guardrail_results] == [ + "call-Paris", + "call-Rome", + ] + retry_input = cast(list[TResponseInputItem], model.calls[-1].input) + assert [_item_type(item) for item in retry_input] == ["function_call_output"] + assert cast(dict[str, Any], retry_input[0])["call_id"] == "call-Rome" + assert await receipt.wait() == outcome + + @pytest.mark.asyncio @pytest.mark.parametrize("streamed_failure", [False, True]) async def test_server_acceptance_commits_before_invocation_validation_failure( @@ -885,6 +1032,7 @@ async def test_server_acceptance_commits_before_invocation_validation_failure( with pytest.raises(ModelBehaviorError, match="completed tool call ID"): async for _event in failed.stream_events(): pass + state = failed.to_state() else: with pytest.raises(ModelBehaviorError, match="completed tool call ID"): await Runner.run(agent, state) @@ -952,6 +1100,7 @@ async def on_tool_start( with pytest.raises(RuntimeError, match="computer hook failed"): async for _event in failed.stream_events(): pass + state = failed.to_state() else: with pytest.raises(RuntimeError, match="computer hook failed"): await Runner.run(agent, state, hooks=hooks) @@ -1015,6 +1164,7 @@ async def on_tool_end( with pytest.raises(UserError, match="tool hook failed"): async for _event in failed.stream_events(): pass + state = failed.to_state() else: with pytest.raises(UserError, match="tool hook failed"): await Runner.run(agent, state, hooks=FailToolHook()) diff --git a/tests/test_soft_cancel.py b/tests/test_soft_cancel.py index 1bcfcf121a..09b3b91057 100644 --- a/tests/test_soft_cancel.py +++ b/tests/test_soft_cancel.py @@ -7,7 +7,7 @@ import pytest -from agents import Agent, Runner, SQLiteSession +from agents import Agent, ModelSettings, RunConfig, Runner, SQLiteSession from agents.agent_output import AgentOutputSchema from agents.stream_events import StreamEvent from agents.testing import ScriptedModel @@ -415,6 +415,40 @@ async def test_soft_cancel_mixed_modes(): assert result._event_queue.empty() +@pytest.mark.asyncio +async def test_after_turn_cannot_restart_an_immediately_cancelled_timed_request(): + filtering = asyncio.Event() + model = ScriptedModel([[get_text_message("first")], [get_text_message("unexpected")]]) + + async def filter_input(data): + if model.calls: + filtering.set() + # Finish preparing the request even if the caller cancels during the filter. + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + pass + return data.model_data + + result = Runner.run_streamed( + Agent(name="Assistant", model=model, model_settings=ModelSettings(timeout=5)), + "start", + run_config=RunConfig(tracing_disabled=True, call_model_input_filter=filter_input), + ) + receipt = result.queue("follow-up") + try: + await asyncio.wait_for(filtering.wait(), timeout=3) + finally: + result.cancel() + result.cancel(mode="after_turn") + async for _ in result.stream_events(): + pass + + assert len(model.calls) == 1 + outcome = await asyncio.wait_for(receipt.wait(), timeout=3) + assert (outcome.status, outcome.reason) == ("not_submitted", "cancelled") + + @pytest.mark.asyncio async def test_soft_cancel_explicit_immediate_mode(): """Test explicit immediate mode behaves same as default.""" diff --git a/tests/test_tool_text_transforms.py b/tests/test_tool_text_transforms.py index 680d7c67af..1a8e56d9a5 100644 --- a/tests/test_tool_text_transforms.py +++ b/tests/test_tool_text_transforms.py @@ -940,18 +940,67 @@ 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.28" snapshot["$schemaVersion"] = historical - with pytest.raises(UserError, match="require RunState schema 1.26"): + 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.26" + 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() +@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 + + # 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]) + 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 +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.26" + 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.26"): + with pytest.raises(UserError, match="require RunState schema 1.28"): await RunState.from_json(agent, snapshot) - node["$schemaVersion"] = "1.26" + node["$schemaVersion"] = "1.28" assert not effects saved = store.records[session.session_id]