diff --git a/src/agents/_run_state_agent_identity.py b/src/agents/_run_state_agent_identity.py index 7ee32b83ec..e06276c3c7 100644 --- a/src/agents/_run_state_agent_identity.py +++ b/src/agents/_run_state_agent_identity.py @@ -15,8 +15,6 @@ from .agent import Agent from .handoffs import Handoff from .logger import logger -from .sandbox.capabilities.capability import Capability -from .sandbox.session.base_sandbox_session import BaseSandboxSession from .tool import ( ApplyPatchTool, ComputerTool, @@ -191,6 +189,8 @@ def _tool_identity_signature(tool: Any) -> dict[str, Any]: def _is_capability_runtime_only_value(value: Any) -> bool: + from .sandbox.session.base_sandbox_session import BaseSandboxSession + return isinstance( value, ( @@ -257,6 +257,8 @@ def _normalize_capability_identity_value( finally: seen.remove(object_id) + from .sandbox.capabilities.capability import Capability + if isinstance(value, Capability): seen.add(object_id) try: diff --git a/src/agents/function_schema.py b/src/agents/function_schema.py index 0bba0d81ed..b2e8ae0d4b 100644 --- a/src/agents/function_schema.py +++ b/src/agents/function_schema.py @@ -8,8 +8,6 @@ from dataclasses import dataclass from typing import Annotated, Any, Literal, cast, get_args, get_origin, get_type_hints -# griffelib exposes the `griffe` package at runtime but currently does not ship typing markers. -from griffe import Docstring, DocstringSectionKind # type: ignore[import-untyped] from pydantic import BaseModel, ConfigDict, Field, create_model from pydantic.fields import FieldInfo @@ -261,6 +259,9 @@ def generate_func_documentation( if not doc: return FuncDocumentation(name=name, description=None, param_descriptions=None) + # Griffe is only needed when the function has documentation to parse. + from griffe import Docstring, DocstringSectionKind # type: ignore[import-untyped] + # Resolve the style against the original docstring before any normalization. resolved_style = style or _detect_docstring_style(doc) if resolved_style == "google": diff --git a/src/agents/lifecycle.py b/src/agents/lifecycle.py index 8b11463ac6..d6c5490a9f 100644 --- a/src/agents/lifecycle.py +++ b/src/agents/lifecycle.py @@ -1,4 +1,6 @@ -from typing import Any, Generic +from collections.abc import Awaitable, Callable +from types import FunctionType, MethodType +from typing import Any, Generic, cast from typing_extensions import TypeVar @@ -6,6 +8,8 @@ from .items import ModelResponse, TResponseInputItem from .run_context import AgentHookContext, RunContextWrapper, TContext from .tool import Tool +from .util import _coro +from .util._asyncio_tasks import gather_with_cancel TAgent = TypeVar("TAgent", bound=AgentBase, default=AgentBase) @@ -231,3 +235,45 @@ async def on_llm_end( AgentHooks = AgentHooksBase[TContext, Agent] """Agent hooks for `Agent`s.""" + + +_DEFAULT_HOOK_CALLBACKS = frozenset( + callback + for base in (RunHooksBase, AgentHooksBase) + for name, callback in vars(base).items() + if name.startswith("on_") +) + + +_SKIP_HOOK = object() + + +def _hook_awaitable(callback: Callable[..., Awaitable[Any]], *args: Any) -> object: + """Invoke a hook factory before resolving the next hook reference.""" + from .run_internal.guardrails import input_guardrail_dispatch_is_preserved + + if ( + not input_guardrail_dispatch_is_preserved() + and type(callback) is MethodType + and type(callback.__func__) is FunctionType + and callback.__func__ in _DEFAULT_HOOK_CALLBACKS + ): + return _SKIP_HOOK + return callback(*args) + + +async def _run_hook_callbacks(*callbacks: object) -> None: + """Gather real hook awaitables while retaining their task and cancellation boundaries.""" + from .run_internal.guardrails import input_guardrail_dispatch_is_preserved + + if input_guardrail_dispatch_is_preserved(): + awaitables = [ + _coro.noop_coroutine() if callback is _SKIP_HOOK else cast(Awaitable[Any], callback) + for callback in callbacks + ] + else: + awaitables = [ + cast(Awaitable[Any], callback) for callback in callbacks if callback is not _SKIP_HOOK + ] + if awaitables: + await gather_with_cancel(*awaitables) diff --git a/src/agents/run.py b/src/agents/run.py index d97112c1e7..283dbc6ab6 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -106,7 +106,10 @@ build_run_error_data, resolve_run_error_handler_result, ) -from .run_internal.guardrails import input_guardrail_tool_gate_scope +from .run_internal.guardrails import ( + input_guardrail_tool_gate_scope, + preserve_parallel_input_guardrail_dispatch, +) from .run_internal.items import ( copy_input_items, ensure_nested_history_run_item_occurrence_key, @@ -168,7 +171,6 @@ serialize_tool_use_tracker, ) from .run_state import RunState -from .sandbox.memory.rollouts import terminal_metadata_for_exception from .sandbox.runtime import SandboxRuntime from .tool import dispose_resolved_computers from .tool_guardrails import ToolInputGuardrailResult, ToolOutputGuardrailResult @@ -1059,6 +1061,8 @@ def _mark_response_hooks_started() -> None: g for g in all_input_guardrails if not g.run_in_parallel ] parallel_guardrails = [g for g in all_input_guardrails if g.run_in_parallel] + if parallel_guardrails: + preserve_parallel_input_guardrail_dispatch() if sandbox_runtime.enabled and sequential_guardrails: # Blocking first-turn guardrails must run before sandbox prep so a tripwire # can prevent session creation, startup, or live-session mutation. @@ -2476,6 +2480,8 @@ def on_tool_error_selected() -> None: input_override=memory_input, ) elif run_exception is not None: + from .sandbox.memory.rollouts import terminal_metadata_for_exception + current_step = getattr(run_state, "_current_step", None) await sandbox_runtime.enqueue_memory_payload( input=memory_input, diff --git a/src/agents/run_internal/agent_tool_configuration.py b/src/agents/run_internal/agent_tool_configuration.py index de6b313f1f..83723ead27 100644 --- a/src/agents/run_internal/agent_tool_configuration.py +++ b/src/agents/run_internal/agent_tool_configuration.py @@ -39,9 +39,12 @@ def _observe_tools(active: list[_ToolResolution], tools: tuple[Tool, ...]) -> No if len(active) > 1 and any( resolution.tools_assigned or len(resolution.initial_tools) != len(tools) - or any( - before is not after - for before, after in zip(resolution.initial_tools, tools, strict=False) + or ( + resolution.initial_tools is not tools + and any( + before is not after + for before, after in zip(resolution.initial_tools, tools, strict=False) + ) ) for resolution in active ): diff --git a/src/agents/run_internal/guardrails.py b/src/agents/run_internal/guardrails.py index dc7bc9b30f..24446c5b6c 100644 --- a/src/agents/run_internal/guardrails.py +++ b/src/agents/run_internal/guardrails.py @@ -37,6 +37,7 @@ class _InputGuardrailToolGate: should_cancel: Callable[[], bool] | None = None rejection: InputGuardrailResult | None = None cancel_tools: set[Callable[[], None]] = field(default_factory=set) + preserve_dispatch: bool = False _input_guardrail_tool_gate: ContextVar[_InputGuardrailToolGate | None] = ContextVar( @@ -56,6 +57,18 @@ def input_guardrail_tool_gate_scope( _input_guardrail_tool_gate.reset(token) +def preserve_parallel_input_guardrail_dispatch() -> None: + """Keep original dispatch checkpoints for a run racing parallel input guardrails.""" + gate = _input_guardrail_tool_gate.get() + if gate is not None: + gate.preserve_dispatch = True + + +def input_guardrail_dispatch_is_preserved() -> bool: + gate = _input_guardrail_tool_gate.get() + return gate is not None and gate.preserve_dispatch + + def _reject_input_guardrail_tools(result: InputGuardrailResult) -> None: gate = _input_guardrail_tool_gate.get() if gate is not None and gate.rejection is None: diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index 029d0d1aa5..2bde082ee1 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -58,7 +58,7 @@ TResponseInputItem, TResponseStreamEvent, ) -from ..lifecycle import RunHooks +from ..lifecycle import _SKIP_HOOK, RunHooks, _hook_awaitable, _run_hook_callbacks from ..logger import ( log_model_action_error, log_model_action_warning, @@ -98,8 +98,7 @@ _requests_for_response_without_usage, _response_usage_to_usage, ) -from ..util import _coro, _error_tracing -from ..util._asyncio_tasks import gather_with_cancel +from ..util import _error_tracing from .agent_bindings import AgentBindings, bind_public_agent from .agent_runner_helpers import ( apply_resumed_conversation_settings, @@ -136,6 +135,7 @@ ) from .guardrails import ( input_guardrail_tripwire_triggered_for_stream, + preserve_parallel_input_guardrail_dispatch, run_input_guardrails, run_input_guardrails_with_queue, run_output_guardrails, @@ -230,6 +230,7 @@ get_model_settings, get_output_schema, maybe_filter_model_input, + resolve_agent_prompts, validate_run_hooks, ) from .turn_resolution import ( @@ -1368,6 +1369,8 @@ async def _save_max_turns_items( ) sequential_guardrails = [g for g in all_input_guardrails if not g.run_in_parallel] parallel_guardrails = [g for g in all_input_guardrails if g.run_in_parallel] + if parallel_guardrails: + preserve_parallel_input_guardrail_dispatch() current_bindings = bind_public_agent(current_agent) execution_agent = current_bindings.execution_agent prepared_turn_input = copy_input_items(streamed_result.input) @@ -2475,13 +2478,11 @@ async def raise_if_input_guardrail_tripwire_known() -> None: tool_input=context_wrapper.tool_input, ) context_wrapper._share_tool_state_with(agent_hook_context) - await gather_with_cancel( - hooks.on_agent_start(agent_hook_context, public_agent), - ( - public_agent.hooks.on_start(agent_hook_context, public_agent) - if public_agent.hooks is not None - else _coro.noop_coroutine() - ), + await _run_hook_callbacks( + _hook_awaitable(hooks.on_agent_start, agent_hook_context, public_agent), + _hook_awaitable(public_agent.hooks.on_start, agent_hook_context, public_agent) + if public_agent.hooks is not None + else _SKIP_HOOK, ) all_tools = await get_all_tools(execution_agent, context_wrapper) @@ -2492,10 +2493,7 @@ async def raise_if_input_guardrail_tripwire_known() -> None: streamed_result.current_agent = public_agent streamed_result._current_agent_output_schema = get_output_schema(public_agent) - system_prompt, prompt_config = await gather_with_cancel( - execution_agent.get_system_prompt(context_wrapper), - execution_agent.get_prompt(context_wrapper), - ) + system_prompt, prompt_config = await resolve_agent_prompts(execution_agent, context_wrapper) handoffs = await get_handoffs(execution_agent, context_wrapper) all_tools, handoffs = resolve_tool_name_collisions( @@ -2566,18 +2564,19 @@ async def raise_if_input_guardrail_tripwire_known() -> None: # explicitly rewind this state before replaying a failed request. server_conversation_tracker.mark_input_as_sent(filtered.input) - await gather_with_cancel( - hooks.on_llm_start(context_wrapper, public_agent, filtered.instructions, filtered.input), - ( - public_agent.hooks.on_llm_start( - context_wrapper, - public_agent, - filtered.instructions, - filtered.input, - ) - if public_agent.hooks is not None - else _coro.noop_coroutine() + await _run_hook_callbacks( + _hook_awaitable( + hooks.on_llm_start, context_wrapper, public_agent, filtered.instructions, filtered.input ), + _hook_awaitable( + public_agent.hooks.on_llm_start, + context_wrapper, + public_agent, + filtered.instructions, + filtered.input, + ) + if public_agent.hooks is not None + else _SKIP_HOOK, ) await _persist_stream_input_if_needed( @@ -2767,13 +2766,13 @@ async def after_invocation_validation( _ensure_stream_event_item_occurrence_key(item) for item in model_items ) stream_step_items_to_queue(model_items, streamed_result._event_queue) - await gather_with_cancel( - ( - public_agent.hooks.on_llm_end(context_wrapper, public_agent, final_response) - if public_agent.hooks is not None - else _coro.noop_coroutine() - ), - hooks.on_llm_end(context_wrapper, public_agent, final_response), + await _run_hook_callbacks( + _hook_awaitable( + public_agent.hooks.on_llm_end, context_wrapper, public_agent, final_response + ) + if public_agent.hooks is not None + else _SKIP_HOOK, + _hook_awaitable(hooks.on_llm_end, context_wrapper, public_agent, final_response), ) return response_accepted @@ -2859,22 +2858,17 @@ async def run_single_turn( tool_input=context_wrapper.tool_input, ) context_wrapper._share_tool_state_with(agent_hook_context) - await gather_with_cancel( - hooks.on_agent_start(agent_hook_context, public_agent), - ( - public_agent.hooks.on_start(agent_hook_context, public_agent) - if public_agent.hooks is not None - else _coro.noop_coroutine() - ), + await _run_hook_callbacks( + _hook_awaitable(hooks.on_agent_start, agent_hook_context, public_agent), + _hook_awaitable(public_agent.hooks.on_start, agent_hook_context, public_agent) + if public_agent.hooks is not None + else _SKIP_HOOK, ) all_tools = await get_all_tools(execution_agent, context_wrapper) all_tools = await initialize_computer_tools(tools=all_tools, context_wrapper=context_wrapper) - system_prompt, prompt_config = await gather_with_cancel( - execution_agent.get_system_prompt(context_wrapper), - execution_agent.get_prompt(context_wrapper), - ) + system_prompt, prompt_config = await resolve_agent_prompts(execution_agent, context_wrapper) handoffs = await get_handoffs(execution_agent, context_wrapper) all_tools, handoffs = resolve_tool_name_collisions( @@ -2927,13 +2921,13 @@ async def after_invocation_validation( on_response_accepted(new_response, _processed_response) if response_accepted and on_response_hooks_started is not None: on_response_hooks_started() - await gather_with_cancel( - ( - public_agent.hooks.on_llm_end(context_wrapper, public_agent, new_response) - if public_agent.hooks is not None - else _coro.noop_coroutine() - ), - hooks.on_llm_end(context_wrapper, public_agent, new_response), + await _run_hook_callbacks( + _hook_awaitable( + public_agent.hooks.on_llm_end, context_wrapper, public_agent, new_response + ) + if public_agent.hooks is not None + else _SKIP_HOOK, + _hook_awaitable(hooks.on_llm_end, context_wrapper, public_agent, new_response), ) return response_accepted @@ -3006,18 +3000,19 @@ async def get_new_response( server_conversation_tracker.validate_pending_input_filter(filtered.input) server_conversation_tracker.mark_input_as_sent(filtered.input) - await gather_with_cancel( - hooks.on_llm_start(context_wrapper, public_agent, filtered.instructions, filtered.input), - ( - public_agent.hooks.on_llm_start( - context_wrapper, - public_agent, - filtered.instructions, - filtered.input, - ) - if public_agent.hooks is not None - else _coro.noop_coroutine() + await _run_hook_callbacks( + _hook_awaitable( + hooks.on_llm_start, context_wrapper, public_agent, filtered.instructions, filtered.input ), + _hook_awaitable( + public_agent.hooks.on_llm_start, + context_wrapper, + public_agent, + filtered.instructions, + filtered.input, + ) + if public_agent.hooks is not None + else _SKIP_HOOK, ) previous_response_id = ( @@ -3111,13 +3106,13 @@ async def rewind_model_request() -> None: context_wrapper.usage.add(new_response.usage) if not defer_llm_end_hooks: - await gather_with_cancel( - ( - public_agent.hooks.on_llm_end(context_wrapper, public_agent, new_response) - if public_agent.hooks is not None - else _coro.noop_coroutine() - ), - hooks.on_llm_end(context_wrapper, public_agent, new_response), + await _run_hook_callbacks( + _hook_awaitable( + public_agent.hooks.on_llm_end, context_wrapper, public_agent, new_response + ) + if public_agent.hooks is not None + else _SKIP_HOOK, + _hook_awaitable(hooks.on_llm_end, context_wrapper, public_agent, new_response), ) return new_response diff --git a/src/agents/run_internal/tool_execution.py b/src/agents/run_internal/tool_execution.py index 70d86d74b8..02777b7937 100644 --- a/src/agents/run_internal/tool_execution.py +++ b/src/agents/run_internal/tool_execution.py @@ -65,6 +65,7 @@ ToolApprovalItem, ToolCallOutputItem, ) +from ..lifecycle import _SKIP_HOOK, _hook_awaitable, _run_hook_callbacks from ..logger import log_tool_action_error as _log_tool_action_error, logger from ..model_settings import ModelSettings from ..run_config import RunConfig, ToolErrorFormatterArgs @@ -100,7 +101,7 @@ ToolOutputGuardrailResult, ) from ..tracing import Span, SpanError, function_span, get_current_trace -from ..util import _coro, _error_tracing +from ..util import _error_tracing from ..util._approvals import evaluate_function_tool_approval from ..util._asyncio_tasks import _consume_future_exception, gather_with_cancel from ..util._custom_data import maybe_extract_custom_data, merge_custom_data @@ -2073,13 +2074,15 @@ async def _execute_single_tool_body( self.schema_bypassed_tool_runs.add(id(task_state.tool_run)) return rejected_message - await gather_with_cancel( - self.hooks.on_tool_start(tool_context, self.public_agent, func_tool), - ( - agent_hooks.on_tool_start(tool_context, self.public_agent, func_tool) - if agent_hooks is not None - else _coro.noop_coroutine() + await _run_hook_callbacks( + _hook_awaitable( + self.hooks.on_tool_start, tool_context, self.public_agent, func_tool ), + _hook_awaitable( + agent_hooks.on_tool_start, tool_context, self.public_agent, func_tool + ) + if agent_hooks is not None + else _SKIP_HOOK, ) raise_if_input_guardrail_rejected() @@ -2218,13 +2221,15 @@ async def _invoke_tool_and_run_post_invoke( self.custom_data_by_tool_run[id(task_state.tool_run)] = custom_data if output_item is not None: output_item.custom_data = custom_data - await gather_with_cancel( - self.hooks.on_tool_end(tool_context, self.public_agent, func_tool, final_result), - ( - agent_hooks.on_tool_end(tool_context, self.public_agent, func_tool, final_result) - if agent_hooks is not None - else _coro.noop_coroutine() + await _run_hook_callbacks( + _hook_awaitable( + self.hooks.on_tool_end, tool_context, self.public_agent, func_tool, final_result ), + _hook_awaitable( + agent_hooks.on_tool_end, tool_context, self.public_agent, func_tool, final_result + ) + if agent_hooks is not None + else _SKIP_HOOK, ) return final_result diff --git a/src/agents/run_internal/tool_planning.py b/src/agents/run_internal/tool_planning.py index b8134d8cef..2ed7a8bc6c 100644 --- a/src/agents/run_internal/tool_planning.py +++ b/src/agents/run_internal/tool_planning.py @@ -1011,6 +1011,8 @@ async def _execute_tool_plan( list[RunItem], ]: """Execute tool runs captured in a ToolExecutionPlan.""" + from .guardrails import input_guardrail_dispatch_is_preserved + public_agent = bindings.public_agent isolate_function_tool_failures = len(plan.function_runs) > 1 or ( parallel @@ -1077,14 +1079,99 @@ def on_category_failure(error: BaseException) -> None: if isinstance(error, asyncio.CancelledError): _mark_tool_local_cancellation(error) - ( - (function_results, tool_input_guardrail_results, tool_output_guardrail_results), - computer_results, - custom_tool_results, - shell_results, - apply_patch_results, - local_shell_results, - ) = await gather_with_cancel( + preserve_dispatch = input_guardrail_dispatch_is_preserved() + native_categories: list[tuple[int, Awaitable[list[RunItem]]]] = [] + if plan.computer_actions or preserve_dispatch: + native_categories.append( + ( + 0, + run_native_category( + partial( + execute_computer_actions, + public_agent=public_agent, + actions=plan.computer_actions, + hooks=hooks, + context_wrapper=context_wrapper, + config=run_config, + tool_output_committer=tool_output_committer, + sibling_category_failure=native_category_failure, + ) + ), + ) + ) + if plan.custom_tool_calls or preserve_dispatch: + native_categories.append( + ( + 1, + run_native_category( + partial( + execute_custom_tool_calls, + public_agent=public_agent, + calls=plan.custom_tool_calls, + hooks=hooks, + context_wrapper=context_wrapper, + config=run_config, + tool_output_committer=tool_output_committer, + sibling_category_failure=native_category_failure, + ) + ), + ) + ) + if plan.shell_calls or preserve_dispatch: + native_categories.append( + ( + 2, + run_native_category( + partial( + execute_shell_calls, + public_agent=public_agent, + calls=plan.shell_calls, + hooks=hooks, + context_wrapper=context_wrapper, + config=run_config, + tool_output_committer=tool_output_committer, + sibling_category_failure=native_category_failure, + ) + ), + ) + ) + if plan.apply_patch_calls or preserve_dispatch: + native_categories.append( + ( + 3, + run_native_category( + partial( + execute_apply_patch_calls, + public_agent=public_agent, + calls=plan.apply_patch_calls, + hooks=hooks, + context_wrapper=context_wrapper, + config=run_config, + tool_output_committer=tool_output_committer, + sibling_category_failure=native_category_failure, + ) + ), + ) + ) + if plan.local_shell_calls or preserve_dispatch: + native_categories.append( + ( + 4, + run_native_category( + partial( + execute_local_shell_calls, + public_agent=public_agent, + calls=plan.local_shell_calls, + hooks=hooks, + context_wrapper=context_wrapper, + config=run_config, + tool_output_committer=tool_output_committer, + sibling_category_failure=native_category_failure, + ) + ), + ) + ) + category_results = await gather_with_cancel( execute_function_tool_calls( bindings=bindings, tool_runs=plan.function_runs, @@ -1098,71 +1185,26 @@ def on_category_failure(error: BaseException) -> None: tool_input_guardrail_results=tool_input_guardrail_results, tool_output_guardrail_results=tool_output_guardrail_results, ), - run_native_category( - partial( - execute_computer_actions, - public_agent=public_agent, - actions=plan.computer_actions, - hooks=hooks, - context_wrapper=context_wrapper, - config=run_config, - tool_output_committer=tool_output_committer, - sibling_category_failure=native_category_failure, - ) - ), - run_native_category( - partial( - execute_custom_tool_calls, - public_agent=public_agent, - calls=plan.custom_tool_calls, - hooks=hooks, - context_wrapper=context_wrapper, - config=run_config, - tool_output_committer=tool_output_committer, - sibling_category_failure=native_category_failure, - ) - ), - run_native_category( - partial( - execute_shell_calls, - public_agent=public_agent, - calls=plan.shell_calls, - hooks=hooks, - context_wrapper=context_wrapper, - config=run_config, - tool_output_committer=tool_output_committer, - sibling_category_failure=native_category_failure, - ) - ), - run_native_category( - partial( - execute_apply_patch_calls, - public_agent=public_agent, - calls=plan.apply_patch_calls, - hooks=hooks, - context_wrapper=context_wrapper, - config=run_config, - tool_output_committer=tool_output_committer, - sibling_category_failure=native_category_failure, - ) - ), - run_native_category( - partial( - execute_local_shell_calls, - public_agent=public_agent, - calls=plan.local_shell_calls, - hooks=hooks, - context_wrapper=context_wrapper, - config=run_config, - tool_output_committer=tool_output_committer, - sibling_category_failure=native_category_failure, - ) - ), + *(coroutine for _, coroutine in native_categories), on_child_failure=on_category_failure, cancelled_children=cancelled_native_tasks, # Preserve both the finalization wait and its cancellation-cleanup window. cancelled_children_timeout=2 * tool_execution._FUNCTION_TOOL_POST_INVOKE_WAIT_SECONDS, ) + function_results, tool_input_guardrail_results, tool_output_guardrail_results = cast( + tuple[list[Any], list[ToolInputGuardrailResult], list[ToolOutputGuardrailResult]], + category_results[0], + ) + native_results: list[list[RunItem]] = [[], [], [], [], []] + for (index, _), result in zip(native_categories, category_results[1:], strict=True): + native_results[index] = cast(list[RunItem], result) + ( + computer_results, + custom_tool_results, + shell_results, + apply_patch_results, + local_shell_results, + ) = native_results else: ( function_results, diff --git a/src/agents/run_internal/turn_preparation.py b/src/agents/run_internal/turn_preparation.py index e67658dc06..c089e5098e 100644 --- a/src/agents/run_internal/turn_preparation.py +++ b/src/agents/run_internal/turn_preparation.py @@ -97,6 +97,8 @@ async def maybe_filter_model_input( async def get_handoffs(agent: Agent[Any], context_wrapper: RunContextWrapper[Any]) -> list[Handoff]: """Return enabled handoffs for the agent.""" + from .guardrails import input_guardrail_dispatch_is_preserved + handoffs = [] for handoff_item in agent.handoffs: if isinstance(handoff_item, Handoff): @@ -104,6 +106,9 @@ async def get_handoffs(agent: Agent[Any], context_wrapper: RunContextWrapper[Any elif isinstance(handoff_item, Agent): handoffs.append(handoff(handoff_item)) + if not handoffs and not input_guardrail_dispatch_is_preserved(): + return [] + async def check_handoff_enabled(handoff_obj: Handoff) -> bool: attr = handoff_obj.is_enabled if isinstance(attr, bool): @@ -186,3 +191,30 @@ def get_model_settings( return model._get_request_settings( settings, prompt=prompt, has_tools=has_tools, implicit_fields=implicit_fields ) + + +_DEFAULT_SYSTEM_PROMPT_GETTER = Agent.get_system_prompt +_DEFAULT_PROMPT_GETTER = Agent.get_prompt + + +async def resolve_agent_prompts( + agent: Agent[TContext], context_wrapper: RunContextWrapper[TContext] +) -> tuple[str | None, ResponsePromptParam | None]: + """Return static prompts directly and isolate dynamic prompt callbacks in tasks.""" + from .guardrails import input_guardrail_dispatch_is_preserved + + if ( + not input_guardrail_dispatch_is_preserved() + and type(agent) is Agent + and Agent.get_system_prompt is _DEFAULT_SYSTEM_PROMPT_GETTER + and Agent.get_prompt is _DEFAULT_PROMPT_GETTER + and "get_system_prompt" not in agent.__dict__ + and "get_prompt" not in agent.__dict__ + ): + instructions = agent.instructions + prompt = agent.prompt + if (instructions is None or isinstance(instructions, str)) and prompt is None: + return instructions, None + return await gather_with_cancel( + agent.get_system_prompt(context_wrapper), agent.get_prompt(context_wrapper) + ) diff --git a/src/agents/run_internal/turn_resolution.py b/src/agents/run_internal/turn_resolution.py index e557588b55..2735e7fdc4 100644 --- a/src/agents/run_internal/turn_resolution.py +++ b/src/agents/run_internal/turn_resolution.py @@ -99,7 +99,7 @@ coerce_tool_search_call_raw_item, coerce_tool_search_output_raw_item, ) -from ..lifecycle import RunHooks +from ..lifecycle import _SKIP_HOOK, RunHooks, _hook_awaitable, _run_hook_callbacks from ..logger import log_tool_action_error, logger from ..run_config import RunConfig, ToolErrorFormatterArgs from ..run_context import AgentHookContext, RunContextWrapper, TContext @@ -363,11 +363,11 @@ async def run_final_output_hooks( ) context_wrapper._share_tool_state_with(agent_hook_context) - await gather_with_cancel( - hooks.on_agent_end(agent_hook_context, agent, final_output), - agent.hooks.on_end(agent_hook_context, agent, final_output) + await _run_hook_callbacks( + _hook_awaitable(hooks.on_agent_end, agent_hook_context, agent, final_output), + _hook_awaitable(agent.hooks.on_end, agent_hook_context, agent, final_output) if agent.hooks is not None - else _coro.noop_coroutine(), + else _SKIP_HOOK, ) @@ -1441,13 +1441,13 @@ async def resolve_interrupted_turn( and not current_step.llm_end_hooks_started ): current_step.llm_end_hooks_started = True - await gather_with_cancel( - ( - public_agent.hooks.on_llm_end(context_wrapper, public_agent, new_response) - if public_agent.hooks is not None - else _coro.noop_coroutine() - ), - hooks.on_llm_end(context_wrapper, public_agent, new_response), + await _run_hook_callbacks( + _hook_awaitable( + public_agent.hooks.on_llm_end, context_wrapper, public_agent, new_response + ) + if public_agent.hooks is not None + else _SKIP_HOOK, + _hook_awaitable(hooks.on_llm_end, context_wrapper, public_agent, new_response), ) if ( diff --git a/src/agents/sandbox/__init__.py b/src/agents/sandbox/__init__.py index 841980ab44..cc979dd8d7 100644 --- a/src/agents/sandbox/__init__.py +++ b/src/agents/sandbox/__init__.py @@ -1,32 +1,74 @@ from __future__ import annotations -from ..run_config import SandboxArchiveLimits, SandboxConcurrencyLimits, SandboxRunConfig -from .capabilities import Capability -from .config import MemoryGenerateConfig, MemoryLayoutConfig, MemoryReadConfig -from .entries import Dir, LocalFile -from .errors import ( - ErrorCode, - ExecTimeoutError, - ExecTransportError, - ExposedPortUnavailableError, - SandboxError, - WorkspaceArchiveReadError, - WorkspaceArchiveWriteError, - WorkspaceReadNotFoundError, - WorkspaceWriteTypeError, -) -from .manifest import Manifest -from .sandbox_agent import SandboxAgent -from .snapshot import ( - LocalSnapshot, - LocalSnapshotSpec, - RemoteSnapshot, - RemoteSnapshotSpec, - SnapshotSpec, - resolve_snapshot, -) -from .types import ExecResult, ExposedPortEndpoint, FileMode, Group, Permissions, User -from .workspace_paths import SandboxPathGrant, SandboxWorkspaceScope +from importlib import import_module +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from ..run_config import SandboxArchiveLimits, SandboxConcurrencyLimits, SandboxRunConfig + from .capabilities import Capability + from .config import MemoryGenerateConfig, MemoryLayoutConfig, MemoryReadConfig + from .entries import Dir, LocalFile + from .errors import ( + ErrorCode, + ExecTimeoutError, + ExecTransportError, + ExposedPortUnavailableError, + SandboxError, + WorkspaceArchiveReadError, + WorkspaceArchiveWriteError, + WorkspaceReadNotFoundError, + WorkspaceWriteTypeError, + ) + from .manifest import Manifest + from .sandbox_agent import SandboxAgent + from .snapshot import ( + LocalSnapshot, + LocalSnapshotSpec, + RemoteSnapshot, + RemoteSnapshotSpec, + SnapshotSpec, + resolve_snapshot, + ) + from .types import ExecResult, ExposedPortEndpoint, FileMode, Group, Permissions, User + from .workspace_paths import SandboxPathGrant, SandboxWorkspaceScope + +_LAZY_EXPORTS = { + "SandboxArchiveLimits": "..run_config", + "SandboxConcurrencyLimits": "..run_config", + "SandboxRunConfig": "..run_config", + "Capability": ".capabilities", + "MemoryGenerateConfig": ".config", + "MemoryLayoutConfig": ".config", + "MemoryReadConfig": ".config", + "Dir": ".entries", + "LocalFile": ".entries", + "ErrorCode": ".errors", + "ExecTimeoutError": ".errors", + "ExecTransportError": ".errors", + "ExposedPortUnavailableError": ".errors", + "SandboxError": ".errors", + "WorkspaceArchiveReadError": ".errors", + "WorkspaceArchiveWriteError": ".errors", + "WorkspaceReadNotFoundError": ".errors", + "WorkspaceWriteTypeError": ".errors", + "Manifest": ".manifest", + "SandboxAgent": ".sandbox_agent", + "LocalSnapshot": ".snapshot", + "LocalSnapshotSpec": ".snapshot", + "RemoteSnapshot": ".snapshot", + "RemoteSnapshotSpec": ".snapshot", + "SnapshotSpec": ".snapshot", + "resolve_snapshot": ".snapshot", + "ExecResult": ".types", + "ExposedPortEndpoint": ".types", + "FileMode": ".types", + "Group": ".types", + "Permissions": ".types", + "User": ".types", + "SandboxPathGrant": ".workspace_paths", + "SandboxWorkspaceScope": ".workspace_paths", +} + __all__ = [ "Capability", @@ -64,3 +106,16 @@ "User", "resolve_snapshot", ] + + +def __getattr__(name: str) -> Any: + module_name = _LAZY_EXPORTS.get(name) + if module_name is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + value = getattr(import_module(module_name, __name__), name) + globals()[name] = value + return value + + +def __dir__() -> list[str]: + return sorted(set(globals()) | set(__all__)) diff --git a/src/agents/sandbox/_run_state.py b/src/agents/sandbox/_run_state.py new file mode 100644 index 0000000000..de4c59876f --- /dev/null +++ b/src/agents/sandbox/_run_state.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +import copy +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from ..run_state import RunState + + +def copy_sandbox_resume_state(run_state: RunState[Any] | None) -> dict[str, object] | None: + if run_state is None or not isinstance(run_state._sandbox, dict): + return None + return copy.deepcopy(run_state._sandbox) diff --git a/src/agents/sandbox/runtime.py b/src/agents/sandbox/runtime.py index 5e10527d13..adaf7e698c 100644 --- a/src/agents/sandbox/runtime.py +++ b/src/agents/sandbox/runtime.py @@ -5,7 +5,7 @@ from contextlib import nullcontext from dataclasses import dataclass from pathlib import Path -from typing import Any, Generic, cast +from typing import TYPE_CHECKING, Any, Generic, TypeGuard, cast from ..agent import Agent from ..exceptions import UserError @@ -23,23 +23,18 @@ from ..run_state import RunState from ..tracing import custom_span, get_current_trace from ..tracing.context import TraceCtxManager -from .capabilities import Capability -from .capabilities.memory import Memory -from .memory.manager import SandboxMemoryGenerationManager, get_or_create_memory_generation_manager -from .memory.rollouts import ( - RolloutTerminalMetadata, - build_rollout_payload, -) -from .runtime_agent_preparation import ( - clone_capabilities, - prepare_sandbox_agent, - prepare_sandbox_input, -) -from .runtime_session_manager import SandboxRuntimeSessionManager -from .sandbox_agent import SandboxAgent -from .session.base_sandbox_session import BaseSandboxSession -from .types import User -from .workspace_paths import SandboxWorkspaceScope, sandbox_path_str +from ._run_state import copy_sandbox_resume_state + +if TYPE_CHECKING: + from .capabilities import Capability + from .capabilities.memory import Memory + from .memory.manager import SandboxMemoryGenerationManager + from .memory.rollouts import RolloutTerminalMetadata + from .runtime_session_manager import SandboxRuntimeSessionManager + from .sandbox_agent import SandboxAgent + from .session.base_sandbox_session import BaseSandboxSession + from .types import User + from .workspace_paths import SandboxWorkspaceScope logger = logging.getLogger(__name__) @@ -86,27 +81,31 @@ def __init__( self._sandbox_config = run_config.sandbox if run_config is not None else None self._tracing_disabled = run_config.tracing_disabled if run_config is not None else False self._run_config_model = run_config.model if run_config is not None else None - self._workspace_scope = SandboxWorkspaceScope.from_cwd( - self._sandbox_config.cwd if self._sandbox_config is not None else None - ) - # The runner resolves this before constructing the runtime. It can be None only when - # sandbox is disabled or tests instantiate the runtime directly. + self._run_state = run_state + # Disabled runs do not own sandbox resources. + self._workspace_scope: SandboxWorkspaceScope | None = None + self._session_manager: SandboxRuntimeSessionManager[TContext] | None = None + if self._sandbox_config is not None: + from .runtime_session_manager import SandboxRuntimeSessionManager + from .workspace_paths import SandboxWorkspaceScope + + self._workspace_scope = SandboxWorkspaceScope.from_cwd(self._sandbox_config.cwd) + self._session_manager = SandboxRuntimeSessionManager( + starting_agent=starting_agent, + sandbox_config=self._sandbox_config, + run_state=run_state, + ) self._rollout_id = rollout_id self._active_memory_capability: Memory | None = None - self._session_manager = SandboxRuntimeSessionManager( - starting_agent=starting_agent, - sandbox_config=self._sandbox_config, - run_state=run_state, - ) self._prepared_agents: dict[int, _SandboxPreparedAgentCache[TContext]] = {} @property def enabled(self) -> bool: - return self._session_manager.enabled + return self._session_manager is not None and self._session_manager.enabled @property def current_session(self) -> BaseSandboxSession | None: - return self._session_manager.current_session + return self._session_manager.current_session if self._session_manager is not None else None def apply_result_metadata(self, result: RunResult | RunResultStreaming) -> None: session = self.current_session @@ -147,7 +146,7 @@ async def _cleanup_and_store() -> None: result._sandbox_cleanup = _cleanup_and_store def assert_agent_supported(self, agent: Agent[TContext]) -> None: - if isinstance(agent, SandboxAgent) and self._sandbox_config is None: + if _is_sandbox_agent(agent) and self._sandbox_config is None: raise UserError("SandboxAgent execution requires `RunConfig(sandbox=...)`") async def enqueue_memory_result( @@ -179,6 +178,8 @@ async def enqueue_memory_payload( manager = self._memory_generation_manager() if manager is None or self._rollout_id is None: return + from .memory.rollouts import build_rollout_payload + payload = build_rollout_payload( input=input, new_items=new_items, @@ -199,6 +200,8 @@ def _memory_generation_manager(self) -> SandboxMemoryGenerationManager | None: or self._active_memory_capability.generate is None ): return None + from .memory.manager import get_or_create_memory_generation_manager + return get_or_create_memory_generation_manager( session=session, memory=self._active_memory_capability, @@ -217,12 +220,21 @@ async def prepare_agent( ) -> _SandboxPreparedAgent[TContext]: self.assert_agent_supported(current_agent) self._set_active_memory_capability(current_agent) - if not isinstance(current_agent, SandboxAgent): + if not _is_sandbox_agent(current_agent): return _SandboxPreparedAgent( bindings=bind_public_agent(current_agent), input=current_input, ) + from .runtime_agent_preparation import ( + clone_capabilities, + prepare_sandbox_agent, + prepare_sandbox_input, + ) + from .sandbox_agent import SandboxAgent + + assert self._session_manager is not None + assert self._workspace_scope is not None span_cm = ( custom_span( "sandbox.prepare_agent", @@ -314,6 +326,8 @@ async def prepare_agent( ) async def cleanup(self) -> dict[str, object] | None: + if self._session_manager is None: + return copy_sandbox_resume_state(self._run_state) should_trace_cleanup = self.current_session is not None or bool(self._prepared_agents) span_cm = ( custom_span("sandbox.cleanup", data={}) @@ -327,9 +341,19 @@ async def cleanup(self) -> dict[str, object] | None: self._prepared_agents.clear() +def _is_sandbox_agent(agent: Agent[TContext]) -> TypeGuard[SandboxAgent[TContext]]: + if type(agent) is Agent: + return False + from .sandbox_agent import SandboxAgent + + return isinstance(agent, SandboxAgent) + + def _get_memory_capability(agent: Agent[TContext]) -> Memory | None: - if not isinstance(agent, SandboxAgent): + if not _is_sandbox_agent(agent): return None + from .capabilities.memory import Memory + for capability in agent.capabilities: if isinstance(capability, Memory): return capability @@ -339,6 +363,8 @@ def _get_memory_capability(agent: Agent[TContext]) -> Memory | None: def _coerce_run_as_user(run_as: User | str | None) -> User | None: if run_as is None: return None + from .types import User + if isinstance(run_as, User): return run_as return User(name=run_as) @@ -359,6 +385,8 @@ async def _validate_workspace_scope( if cwd is None: return + from .workspace_paths import sandbox_path_str + resolved_cwd = sandbox_path_str(session.normalize_path(cast(Path | str, scope.anchor(".")))) for test_flag in ("-d", "-x"): result = await session.exec( diff --git a/src/agents/sandbox/runtime_session_manager.py b/src/agents/sandbox/runtime_session_manager.py index 4378c29cbf..49c98377a6 100644 --- a/src/agents/sandbox/runtime_session_manager.py +++ b/src/agents/sandbox/runtime_session_manager.py @@ -25,6 +25,7 @@ redact_mount_error_data, validate_manifest_mount_credential_boundaries, ) +from ._run_state import copy_sandbox_resume_state from .capabilities import Capability from .entries import BaseEntry, Dir, Mount, resolve_workspace_path from .manifest import Manifest @@ -229,11 +230,7 @@ async def ensure_session( return resources.session def serialize_resume_state(self) -> dict[str, object] | None: - existing_payload = ( - copy.deepcopy(self._run_state._sandbox) - if self._run_state is not None and isinstance(self._run_state._sandbox, dict) - else None - ) + existing_payload = copy_sandbox_resume_state(self._run_state) if self._sandbox_config is None: return existing_payload if self._sandbox_config.session is not None: diff --git a/src/agents/testing/__init__.py b/src/agents/testing/__init__.py index 93f1be19f6..32a3b70e19 100644 --- a/src/agents/testing/__init__.py +++ b/src/agents/testing/__init__.py @@ -1,5 +1,8 @@ """Deterministic test doubles for Agents SDK workflows.""" +from importlib import import_module +from typing import TYPE_CHECKING, Any + from .model import ( InvalidModelStep, ModelCall, @@ -12,17 +15,32 @@ assistant_message, function_call, ) -from .sandbox import ( - InvalidSandboxStep, - SandboxCall, - SandboxCallMatcherError, - SandboxScriptError, - SandboxStepSpec, - ScriptedSandboxSession, - UnconsumedSandboxSteps, - UnexpectedSandboxCall, - scripted_sandbox_session, -) + +if TYPE_CHECKING: + from .sandbox import ( + InvalidSandboxStep, + SandboxCall, + SandboxCallMatcherError, + SandboxScriptError, + SandboxStepSpec, + ScriptedSandboxSession, + UnconsumedSandboxSteps, + UnexpectedSandboxCall, + scripted_sandbox_session, + ) + +_LAZY_EXPORTS = { + "InvalidSandboxStep": ".sandbox", + "SandboxCall": ".sandbox", + "SandboxCallMatcherError": ".sandbox", + "SandboxScriptError": ".sandbox", + "SandboxStepSpec": ".sandbox", + "ScriptedSandboxSession": ".sandbox", + "UnconsumedSandboxSteps": ".sandbox", + "UnexpectedSandboxCall": ".sandbox", + "scripted_sandbox_session": ".sandbox", +} + __all__ = [ "InvalidModelStep", @@ -45,3 +63,16 @@ "function_call", "scripted_sandbox_session", ] + + +def __getattr__(name: str) -> Any: + module_name = _LAZY_EXPORTS.get(name) + if module_name is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + value = getattr(import_module(module_name, __name__), name) + globals()[name] = value + return value + + +def __dir__() -> list[str]: + return sorted(set(globals()) | set(__all__)) diff --git a/src/agents/tool.py b/src/agents/tool.py index 671e46f308..1e38db45c3 100644 --- a/src/agents/tool.py +++ b/src/agents/tool.py @@ -2229,6 +2229,16 @@ def _get_function_tool_invoke_context( metadata such as agents or run config into incompatible serializers. When the wrapper explicitly declares `RunContextWrapper`, preserve only the base context state. """ + # SDK-owned invokers declare ToolContext unless callers override reflection metadata. + invoker = function_tool.on_invoke_tool + if ( + type(invoker) is _FailureHandlingFunctionToolInvoker + and getattr(invoker, "__signature__", None) is None + and getattr(invoker, "__annotations__", None) is None + and getattr(invoker, "__wrapped__", None) is None + ): + return context + try: parameters = tuple(inspect.signature(function_tool.on_invoke_tool).parameters.values()) except (TypeError, ValueError): diff --git a/tests/sandbox/test_runtime.py b/tests/sandbox/test_runtime.py index 6a6b12be22..7d05f9ee62 100644 --- a/tests/sandbox/test_runtime.py +++ b/tests/sandbox/test_runtime.py @@ -4704,6 +4704,66 @@ async def test_session_manager_rejects_running_injected_session_account_mutation assert live_session.state.manifest.users == [] +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_runner_preserves_saved_sandbox_after_resuming_ordinary_agent_without_config( + streamed: bool, +) -> None: + client = _ManifestSessionClient() + manifest = Manifest() + + @function_tool(needs_approval=True) + def approval_tool() -> str: + return "approved" + + ordinary_model = ScriptedModel( + [ + [get_function_tool_call("approval_tool", "{}", call_id="approval")], + [get_final_output_message("done")], + ] + ) + ordinary = Agent(name="ordinary", model=ordinary_model, tools=[approval_tool]) + sandbox_model = ScriptedModel([[get_handoff_tool_call(ordinary)]]) + sandbox = SandboxAgent( + name="sandbox", + model=sandbox_model, + default_manifest=manifest, + capabilities=[], + handoffs=[ordinary], + ) + config = RunConfig(sandbox=SandboxRunConfig(client=client)) + paused: RunResult | RunResultStreaming + if streamed: + paused = Runner.run_streamed(sandbox, "start", run_config=config) + async for _ in paused.stream_events(): + pass + else: + paused = await Runner.run(sandbox, "start", run_config=config) + + assert paused.last_agent is ordinary + assert len(paused.interruptions) == 1 + state = paused.to_state() + saved_payload = state.to_json()["sandbox"] + assert saved_payload is not None + assert saved_payload["backend_id"] == "manifest" + state.approve(paused.interruptions[0]) + + resumed: RunResult | RunResultStreaming + if streamed: + resumed = Runner.run_streamed(sandbox, state, run_config=RunConfig()) + async for _ in resumed.stream_events(): + pass + else: + resumed = await Runner.run(sandbox, state, run_config=RunConfig()) + + assert resumed.final_output == "done" + assert resumed.last_agent is ordinary + assert resumed.to_state().to_json()["sandbox"] == saved_payload + assert client.created_manifests == [manifest] + sandbox_model.assert_complete() + ordinary_model.assert_complete() + + @pytest.mark.asyncio async def test_session_manager_preserves_existing_payload_when_no_sandbox_session_is_used() -> None: client = _FakeClient(_FakeSession(Manifest())) diff --git a/tests/test_dispatch_guardrail_scheduling.py b/tests/test_dispatch_guardrail_scheduling.py new file mode 100644 index 0000000000..d5dec64982 --- /dev/null +++ b/tests/test_dispatch_guardrail_scheduling.py @@ -0,0 +1,211 @@ +import asyncio +from typing import Any + +import pytest + +from agents import ( + Agent, + GuardrailFunctionOutput, + InputGuardrail, + InputGuardrailTripwireTriggered, + RunConfig, + Runner, +) +from agents.testing import ScriptedModel, assistant_message + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("scope", ["agent", "run"]) +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_immediate_parallel_guardrail_prevents_model_entry_and_side_effects( + streamed: bool, scope: str, asynchronous: bool +) -> None: + entered: list[str] = [] + effects: list[str] = [] + + class RecordingModel(ScriptedModel): + # This double has been recording provider entry before emitting model output. + async def get_response(self, *args: Any, **kwargs: Any) -> Any: + entered.append("response") + effects.append("provider-side-effect") + return await super().get_response(*args, **kwargs) + + async def stream_response(self, *args: Any, **kwargs: Any) -> Any: + entered.append("stream") + effects.append("provider-side-effect") + async for event in super().stream_response(*args, **kwargs): + yield event + + def reject(*args: Any) -> GuardrailFunctionOutput: + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=True) + + async def reject_async(*args: Any) -> GuardrailFunctionOutput: + return reject(*args) + + guardrail = InputGuardrail( + guardrail_function=reject_async if asynchronous else reject, run_in_parallel=True + ) + + model = RecordingModel() + model.enqueue([assistant_message("done")]) + agent = Agent( + name="guarded", + model=model, + input_guardrails=[guardrail] if scope == "agent" else [], + ) + config = RunConfig(input_guardrails=[guardrail] if scope == "run" else []) + with pytest.raises(InputGuardrailTripwireTriggered): + if streamed: + result = Runner.run_streamed(agent, "start", run_config=config) + async for _ in result.stream_events(): + pass + else: + await Runner.run(agent, "start", run_config=config) + assert entered == [] + assert effects == [] + + +async def _complete(agent: Agent[Any], streamed: bool, hooks: Any = None) -> Any: + if streamed: + result = Runner.run_streamed(agent, "start", hooks=hooks) + async for _ in result.stream_events(): + pass + return result.final_output + return (await Runner.run(agent, "start", hooks=hooks)).final_output + + +def _text_agent(name: str, guardrails: Any = ()) -> Agent[Any]: + model = ScriptedModel() + model.enqueue([assistant_message("done")]) + return Agent(name=name, model=model, input_guardrails=list(guardrails)) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_nested_runs_restore_their_guarded_callback_scope(streamed: bool) -> None: + from agents.lifecycle import RunHooks + from agents.run_internal.guardrails import input_guardrail_dispatch_is_preserved + + observed: list[tuple[str, bool]] = [] + nested_done = asyncio.Event() + + def allow(*args: Any) -> GuardrailFunctionOutput: + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=False) + + async def outer_allow(*args: Any) -> GuardrailFunctionOutput: + await nested_done.wait() + return allow() + + class InnerHooks(RunHooks): + async def on_agent_start(self, context: Any, agent: Any) -> None: + observed.append((agent.name, input_guardrail_dispatch_is_preserved())) + + class OuterHooks(RunHooks): + async def on_agent_start(self, *args: Any) -> None: + observed.append(("outer-before", input_guardrail_dispatch_is_preserved())) + assert await _complete(_text_agent("unguarded"), streamed, InnerHooks()) == "done" + guarded = _text_agent("guarded", [InputGuardrail(guardrail_function=allow)]) + assert await _complete(guarded, streamed, InnerHooks()) == "done" + observed.append(("outer-after", input_guardrail_dispatch_is_preserved())) + nested_done.set() + + outer = _text_agent("outer", [InputGuardrail(guardrail_function=outer_allow)]) + assert await _complete(outer, streamed, OuterHooks()) == "done" + assert observed == [ + ("outer-before", True), + ("unguarded", False), + ("guarded", True), + ("outer-after", True), + ] + assert not input_guardrail_dispatch_is_preserved() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_run_spawned_from_guardrail_restores_the_guardrail_scope(streamed: bool) -> None: + from agents.lifecycle import RunHooks + from agents.run_internal.guardrails import input_guardrail_dispatch_is_preserved + + observed: list[tuple[str, bool]] = [] + + class Hooks(RunHooks): + async def on_agent_start(self, *args: Any) -> None: + observed.append(("inner", input_guardrail_dispatch_is_preserved())) + + async def allow(*args: Any) -> GuardrailFunctionOutput: + observed.append(("guard-before", input_guardrail_dispatch_is_preserved())) + assert await _complete(_text_agent("inner"), streamed, Hooks()) == "done" + observed.append(("guard-after", input_guardrail_dispatch_is_preserved())) + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=False) + + outer = _text_agent("outer", [InputGuardrail(guardrail_function=allow)]) + assert await _complete(outer, streamed) == "done" + assert observed == [("guard-before", True), ("inner", False), ("guard-after", True)] + assert not input_guardrail_dispatch_is_preserved() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_cancelled_guarded_run_does_not_leak_dispatch_scope(streamed: bool) -> None: + from agents.lifecycle import RunHooks + from agents.run_internal.guardrails import input_guardrail_dispatch_is_preserved + + started = asyncio.Event() + cancelled = asyncio.Event() + release = asyncio.Event() + observed: list[bool] = [] + + class WaitingHooks(RunHooks): + async def on_agent_start(self, *args: Any) -> None: + observed.append(input_guardrail_dispatch_is_preserved()) + started.set() + try: + await release.wait() + finally: + observed.append(input_guardrail_dispatch_is_preserved()) + cancelled.set() + + async def pending(*args: Any) -> GuardrailFunctionOutput: + await release.wait() + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=False) + + outer = _text_agent("outer", [InputGuardrail(guardrail_function=pending)]) + result = Runner.run_streamed(outer, "start", hooks=WaitingHooks()) if streamed else None + + async def run() -> None: + if result is not None: + async for _ in result.stream_events(): + pass + else: + await Runner.run(outer, "start", hooks=WaitingHooks()) + + task = asyncio.create_task(run()) + try: + await asyncio.wait_for(started.wait(), 2) + if result is not None: + result.cancel() + else: + task.cancel() + settled = await asyncio.gather(task, return_exceptions=True) + if result is None: + assert isinstance(settled[0], asyncio.CancelledError) + else: + assert result.is_complete + await asyncio.wait_for(cancelled.wait(), 2) + assert observed == [True, True] + assert not input_guardrail_dispatch_is_preserved() + + class NextHooks(RunHooks): + async def on_agent_start(self, *args: Any) -> None: + observed.append(input_guardrail_dispatch_is_preserved()) + + assert await _complete(_text_agent("next"), streamed, NextHooks()) == "done" + assert observed == [True, True, False] + finally: + release.set() + if result is not None: + result.cancel() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) diff --git a/tests/test_dispatch_isolation.py b/tests/test_dispatch_isolation.py new file mode 100644 index 0000000000..20c4571bde --- /dev/null +++ b/tests/test_dispatch_isolation.py @@ -0,0 +1,292 @@ +import asyncio +from contextvars import ContextVar +from typing import Any + +import pytest + +from agents import Agent, Runner +from agents.decorators import tool +from agents.exceptions import UserError +from agents.lifecycle import AgentHooks, RunHooks +from agents.testing import ScriptedModel, assistant_message, function_call + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("scope", ["run", "agent", "both"]) +async def test_overridden_hooks_keep_task_context_isolation(streamed: bool, scope: str) -> None: + marker = ContextVar("dispatch_marker", default="caller") + started = {"run": asyncio.Event(), "agent": asyncio.Event()} + observed: list[tuple[str, str, asyncio.Task[Any] | None]] = [] + order: list[str] = [] + caller = asyncio.current_task() + + async def record(name: str) -> None: + observed.append((name, marker.get(), asyncio.current_task())) + marker.set(name) + order.append(name) + started[name].set() + if scope == "both": + await started["agent" if name == "run" else "run"].wait() + + class Hooks(RunHooks): + async def on_llm_start(self, *args: Any) -> None: + await record("run") + + class AgentCallbacks(AgentHooks): + async def on_llm_start(self, *args: Any) -> None: + await record("agent") + + @tool + async def echo() -> str: + assert marker.get() == "caller" + return "ok" + + model = ScriptedModel() + model.extend([[function_call("echo", "{}", call_id="call")], [assistant_message("done")]]) + agent = Agent(name="dispatch", model=model, tools=[echo]) + if scope in ("agent", "both"): + agent.hooks = AgentCallbacks() + hooks = Hooks() if scope in ("run", "both") else None + if streamed: + result = Runner.run_streamed(agent, "start", hooks=hooks) + async for _ in result.stream_events(): + pass + else: + result = await Runner.run(agent, "start", hooks=hooks) + assert result.final_output == "done" + assert marker.get() == "caller" + assert all(value == "caller" and task is not caller for _, value, task in observed) + assert len({task for _, _, task in observed}) == len(observed) + expected = ["run", "agent"] if scope == "both" else [scope] + assert order == expected * 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_failing_hook_cancels_and_drains_sibling_before_tool(streamed: bool) -> None: + waiting = asyncio.Event() + cancelled = asyncio.Event() + invoked = False + + class Hooks(RunHooks): + async def on_tool_start(self, *args: Any) -> None: + waiting.set() + try: + await asyncio.Event().wait() + finally: + cancelled.set() + + class AgentCallbacks(AgentHooks): + async def on_tool_start(self, *args: Any) -> None: + await waiting.wait() + raise ValueError("hook failure") + + @tool + async def echo() -> str: + nonlocal invoked + invoked = True + return "unexpected" + + model = ScriptedModel() + model.enqueue([function_call("echo", "{}", call_id="call")]) + agent = Agent(name="dispatch", model=model, tools=[echo], hooks=AgentCallbacks()) + with pytest.raises(UserError, match="hook failure"): + if streamed: + result = Runner.run_streamed(agent, "start", hooks=Hooks()) + async for _ in result.stream_events(): + pass + else: + await Runner.run(agent, "start", hooks=Hooks()) + assert cancelled.is_set() + assert not invoked + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("overridden", [False, True]) +async def test_dynamic_prompt_callbacks_keep_concurrency_and_context( + streamed: bool, overridden: bool +) -> None: + marker = ContextVar("prompt_marker", default="caller") + started = {"instructions": asyncio.Event(), "prompt": asyncio.Event()} + observed: list[tuple[str, str, asyncio.Task[Any] | None]] = [] + caller = asyncio.current_task() + + async def record(name: str) -> None: + observed.append((name, marker.get(), asyncio.current_task())) + marker.set(name) + started[name].set() + await started["prompt" if name == "instructions" else "instructions"].wait() + + async def instructions(context: Any, agent: Any) -> str: + await record("instructions") + return "Be concise." + + async def prompt(data: Any) -> dict[str, Any]: + await record("prompt") + return {"id": "prompt"} + + class PromptAgent(Agent): + async def get_system_prompt(self, context: Any) -> str: + return await instructions(context, self) + + async def get_prompt(self, context: Any) -> Any: + return await prompt(context) + + model = ScriptedModel() + model.enqueue([assistant_message("done")]) + if overridden: + agent = PromptAgent(name="dispatch", model=model) + else: + agent = Agent(name="dispatch", model=model, instructions=instructions, prompt=prompt) + if streamed: + result = Runner.run_streamed(agent, "start") + async for _ in result.stream_events(): + pass + else: + result = await Runner.run(agent, "start") + assert result.final_output == "done" + assert [name for name, _, _ in observed] == ["instructions", "prompt"] + assert all(value == "caller" and task is not caller for _, value, task in observed) + assert len({task for _, _, task in observed}) == 2 + assert marker.get() == "caller" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("forged", ["unhashable", "base_function"]) +async def test_callable_hook_ignores_forged_function_attribute( + forged: str, monkeypatch: pytest.MonkeyPatch +) -> None: + seen: list[str] = [] + + class Callback: + def __init__(self) -> None: + self.__func__: Any = [] if forged == "unhashable" else RunHooks.on_llm_start + + async def __call__(self, *args: Any) -> None: + seen.append("called") + + hooks = RunHooks() + monkeypatch.setattr(hooks, "on_llm_start", Callback()) + model = ScriptedModel() + model.enqueue([assistant_message("done")]) + result = await Runner.run(Agent(name="dispatch", model=model), "start", hooks=hooks) + assert result.final_output == "done" + assert seen == ["called"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_class_prompt_override_keeps_running( + monkeypatch: pytest.MonkeyPatch, streamed: bool +) -> None: + seen: list[str] = [] + + async def instructions(self: Any, context: Any) -> str: + seen.append("instructions") + return "override" + + async def prompt(self: Any, context: Any) -> Any: + seen.append("prompt") + return None + + monkeypatch.setattr(Agent, "get_system_prompt", instructions) + monkeypatch.setattr(Agent, "get_prompt", prompt) + model = ScriptedModel() + model.enqueue([assistant_message("done")]) + agent = Agent(name="dispatch", model=model) + if streamed: + result = Runner.run_streamed(agent, "start") + async for _ in result.stream_events(): + pass + else: + result = await Runner.run(agent, "start") + assert result.final_output == "done" + assert seen == ["instructions", "prompt"] + + +@pytest.mark.asyncio +async def test_custom_agent_prompt_getter_owns_instruction_reads() -> None: + class CustomAgent(Agent): + guard_instruction_access: bool = False + + def __getattribute__(self, name: str) -> Any: + if name == "instructions" and self.__dict__.get("guard_instruction_access", False): + raise AssertionError("The custom getter has been owning instruction access.") + return super().__getattribute__(name) + + async def get_system_prompt(self, context: Any) -> str: + return "custom instructions" + + model = ScriptedModel() + model.enqueue([assistant_message("done")]) + agent = CustomAgent(name="dispatch", model=model) + agent.guard_instruction_access = True + result = await Runner.run(agent, "start") + assert result.final_output == "done" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_hook_factory_can_replace_later_agent_hook(streamed: bool) -> None: + observed: list[str] = [] + + class Previous(AgentHooks): + async def on_start(self, *args: Any) -> None: + observed.append("previous") + + class Replacement(AgentHooks): + async def on_start(self, *args: Any) -> None: + observed.append("replacement") + + class Hooks(RunHooks): + def on_agent_start(self, context: Any, agent: Any) -> Any: + agent.hooks = Replacement() + + async def finish() -> None: + observed.append("run") + + return finish() + + model = ScriptedModel() + model.enqueue([assistant_message("done")]) + agent = Agent(name="dispatch", model=model, hooks=Previous()) + if streamed: + result = Runner.run_streamed(agent, "start", hooks=Hooks()) + async for _ in result.stream_events(): + pass + else: + result = await Runner.run(agent, "start", hooks=Hooks()) + assert result.final_output == "done" + assert observed == ["run", "replacement"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("scope", ["run", "agent"]) +async def test_explicit_none_hook_keeps_rejecting( + streamed: bool, scope: str, monkeypatch: pytest.MonkeyPatch +) -> None: + class Hooks(RunHooks): + def on_agent_start(self, *args: Any) -> Any: + completed = asyncio.get_running_loop().create_future() + completed.set_result(None) + return completed + + hooks = Hooks() + agent_hooks = AgentHooks() + if scope == "run": + monkeypatch.setattr(hooks, "on_agent_start", None) + else: + monkeypatch.setattr(agent_hooks, "on_start", None) + model = ScriptedModel() + model.enqueue([assistant_message("done")]) + agent = Agent(name="dispatch", model=model, hooks=agent_hooks) + with pytest.raises(TypeError, match="not callable"): + if streamed: + result = Runner.run_streamed(agent, "start", hooks=hooks) + async for _ in result.stream_events(): + pass + else: + await Runner.run(agent, "start", hooks=hooks) diff --git a/tests/test_lazy_docstring_parser.py b/tests/test_lazy_docstring_parser.py new file mode 100644 index 0000000000..4dfdcf6730 --- /dev/null +++ b/tests/test_lazy_docstring_parser.py @@ -0,0 +1,36 @@ +"""Function schemas load the docstring parser only when documentation needs it.""" + +import subprocess +import sys + + +def test_function_without_docstring_defers_docstring_parser() -> None: + subprocess.run( + [ + sys.executable, + "-c", + """ +import sys +from agents import Agent, Model, RunConfig, Runner +from agents.decorators import tool + +async def increment(x: int) -> str: + return str(x + 1) + +function_tool = tool(increment) +assert function_tool.params_json_schema["properties"]["x"]["type"] == "integer" +assert "griffe" not in sys.modules +from agents.function_schema import generate_func_documentation + +def documented(x: int) -> str: + "Describe the increment." + return str(x + 1) + +assert generate_func_documentation(documented).description == "Describe the increment." +assert "griffe" in sys.modules +""", + ], + check=True, + capture_output=True, + text=True, + ) diff --git a/tests/test_run_step_execution.py b/tests/test_run_step_execution.py index 565b0ce229..0ca064c549 100644 --- a/tests/test_run_step_execution.py +++ b/tests/test_run_step_execution.py @@ -2385,7 +2385,15 @@ async def _error_tool() -> str: @pytest.mark.asyncio -async def test_multiple_tool_calls_bound_cancelled_sibling_self_rescheduling_cleanup(): +async def test_multiple_tool_calls_bound_cancelled_sibling_self_rescheduling_cleanup( + monkeypatch: pytest.MonkeyPatch, +): + # Keep the drain deadline beyond the hang guard so only the step limit can end the drain. + monkeypatch.setattr( + tool_execution, + "_FUNCTION_TOOL_CANCELLED_DRAIN_SECONDS", + 2 * _CANCELLATION_HANG_GUARD_SECONDS, + ) sibling_ready = asyncio.Event() cleanup_started = asyncio.Event() cleanup_finished = asyncio.Event() @@ -2428,13 +2436,18 @@ async def _error_tool() -> str: response_id=None, ) - with pytest.raises(UserError, match="Error running tool error_tool: boom"): - await asyncio.wait_for(get_execute_result(agent, response), timeout=0.2) - - assert cleanup_started.is_set() + try: + with pytest.raises(UserError, match="Error running tool error_tool: boom"): + await asyncio.wait_for( + get_execute_result(agent, response), + timeout=_CANCELLATION_HANG_GUARD_SECONDS, + ) + assert cleanup_started.is_set() + assert not cleanup_finished.is_set() + finally: + stop_cleanup.set() - stop_cleanup.set() - await asyncio.wait_for(cleanup_finished.wait(), timeout=0.2) + await asyncio.wait_for(cleanup_finished.wait(), timeout=_CANCELLATION_HANG_GUARD_SECONDS) @pytest.mark.asyncio diff --git a/tests/test_sandbox_lazy_imports.py b/tests/test_sandbox_lazy_imports.py new file mode 100644 index 0000000000..020b4ea1f5 --- /dev/null +++ b/tests/test_sandbox_lazy_imports.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +import os +import subprocess +import sys +import textwrap + + +def _run_fresh_python(source: str) -> None: + env = {key: value for key, value in os.environ.items() if "proxy" not in key.lower()} + result = subprocess.run( + [sys.executable, "-c", textwrap.dedent(source)], + env=env, + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_ordinary_tool_run_does_not_load_sandbox_implementations() -> None: + _run_fresh_python( + """ + import asyncio + import sys + from agents import Agent, Runner, RunConfig + from agents.decorators import tool + from agents.testing import ScriptedModel, assistant_message, function_call + + @tool + def increment(x: int) -> str: + return str(x + 1) + + model = ScriptedModel([ + [function_call("increment", {"x": 1}, call_id="call_1")], + [assistant_message("2")], + ]) + result = asyncio.run(Runner.run( + Agent(name="arithmetic", model=model, tools=[increment]), + "start", + run_config=RunConfig(tracing_disabled=True), + )) + assert result.final_output == "2" + assert len(model.calls) == 2 + model.assert_complete() + assert "agents.sandbox.manifest" not in sys.modules + assert "agents.sandbox.runtime_session_manager" not in sys.modules + assert "agents.sandbox.capabilities" not in sys.modules + assert "agents.testing.sandbox" not in sys.modules + + class CustomAgent(Agent): + pass + + ordinary = asyncio.run(Runner.run( + CustomAgent(name="custom", model=ScriptedModel([[assistant_message("ok")]])), + "start", + run_config=RunConfig(tracing_disabled=True), + )) + assert ordinary.final_output == "ok" + from agents.sandbox import SandboxAgent + from agents.exceptions import UserError + try: + asyncio.run(Runner.run( + SandboxAgent(name="sandbox", model=ScriptedModel([[assistant_message("unused")]])), + "start", + run_config=RunConfig(tracing_disabled=True), + )) + except UserError as error: + assert "requires `RunConfig(sandbox=...)`" in str(error) + else: + raise AssertionError("SandboxAgent ran without sandbox configuration") + """ + ) + + +def test_sandbox_exports_keep_identity_and_concurrent_first_access() -> None: + _run_fresh_python( + """ + from concurrent.futures import ThreadPoolExecutor + import inspect + import pickle + import agents.sandbox as sandbox + + assert set(sandbox.__all__).issubset(dir(sandbox)) + with ThreadPoolExecutor(max_workers=4) as pool: + exported = list(pool.map(lambda _: sandbox.Manifest, range(8))) + from agents.sandbox.manifest import Manifest + assert all(value is Manifest for value in exported) + manifest = Manifest() + assert type(pickle.loads(pickle.dumps(manifest))) is Manifest + assert inspect.getmodule(sandbox.Manifest).__name__ == "agents.sandbox.manifest" + from agents.run_config import SandboxRunConfig + assert sandbox.SandboxRunConfig is SandboxRunConfig + exported = {name: getattr(sandbox, name) for name in sandbox.__all__} + assert exported["Manifest"] is Manifest + + import agents.testing as testing + from agents.testing.sandbox import ScriptedSandboxSession, scripted_sandbox_session + assert testing.ScriptedSandboxSession is ScriptedSandboxSession + assert testing.scripted_sandbox_session is scripted_sandbox_session + """ + ) diff --git a/tests/test_start_hook_tool_concurrency.py b/tests/test_start_hook_tool_concurrency.py index 32e1ded63e..6df9f3ddb5 100644 --- a/tests/test_start_hook_tool_concurrency.py +++ b/tests/test_start_hook_tool_concurrency.py @@ -5,7 +5,7 @@ import pytest -from agents import Agent, AgentHooks, RunConfig, RunHooks, Runner, UserError +from agents import Agent, AgentHooks, FunctionTool, RunConfig, RunHooks, Runner, UserError from agents.decorators import tool from agents.run_context import RunContextWrapper from agents.testing import ScriptedModel @@ -675,3 +675,95 @@ async def on_handoff(self, context, from_agent, to_agent) -> None: assert effects == [] assert target.tools == [privileged] await _run(target, _final_model(), "later", streamed) + + +class _NoEqualityFunctionTool(FunctionTool): + def __eq__(self, other: object) -> bool: + raise AssertionError("Tool configuration must compare identity, not equality.") + + def __ne__(self, other: object) -> bool: + raise AssertionError("Tool configuration must compare identity, not equality.") + + +def _no_equality_tool() -> FunctionTool: + async def invoke(context: RunContextWrapper[Any], arguments: str) -> str: + return "synthetic effect" + + return _NoEqualityFunctionTool( + name="synthetic", + description="Synthetic tool for configuration ownership checks.", + params_json_schema={"type": "object", "properties": {}, "additionalProperties": False}, + on_invoke_tool=invoke, + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("nonempty", [False, True]) +async def test_stable_overlapping_tools_do_not_call_custom_equality( + streamed: bool, nonempty: bool +) -> None: + both_started = asyncio.Event() + started = 0 + provided = [_no_equality_tool()] if nonempty else [] + agent = Agent(name="shared", tools=provided) + original_tools = agent.tools + + class Hooks(RunHooks): + async def on_agent_start(self, context, current_agent) -> None: + nonlocal started + started += 1 + if started == 2: + both_started.set() + await both_started.wait() + + first_model, second_model = _final_model(), _final_model() + await asyncio.wait_for( + asyncio.gather( + _run(agent, first_model, "first", streamed, Hooks()), + _run(agent, second_model, "second", streamed, Hooks()), + ), + 10, + ) + assert agent.tools is original_tools + for model in (first_model, second_model): + assert len(model.calls[0].tools) == len(provided) + assert all( + before is after for before, after in zip(model.calls[0].tools, provided, strict=True) + ) + model.assert_complete() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("nonempty", [False, True]) +async def test_overlapping_tool_replacements_preserve_identity_conflicts( + streamed: bool, nonempty: bool +) -> None: + first_started = asyncio.Event() + second_finished = asyncio.Event() + agent = Agent(name="shared", tools=[_no_equality_tool()] if nonempty else []) + first_model, second_model = _final_model(), _final_model() + + class Hooks(RunHooks): + async def on_agent_start(self, context, current_agent) -> None: + if context.context == "first": + first_started.set() + await second_finished.wait() + elif nonempty: + current_agent.tools[:] = [_no_equality_tool()] + else: + current_agent.tools = [] + + first = asyncio.create_task(_run(agent, first_model, "first", streamed, Hooks())) + await asyncio.wait_for(first_started.wait(), 10) + + async def second() -> None: + try: + await _run(agent, second_model, "second", streamed, Hooks()) + finally: + second_finished.set() + + outcomes = await asyncio.wait_for(asyncio.gather(first, second(), return_exceptions=True), 10) + assert all(isinstance(outcome, UserError) for outcome in outcomes) + assert not first_model.calls and not second_model.calls diff --git a/tests/test_tool_context.py b/tests/test_tool_context.py index 05f4a8a859..17e3bb4d88 100644 --- a/tests/test_tool_context.py +++ b/tests/test_tool_context.py @@ -418,3 +418,96 @@ async def on_invoke_tool( assert captured_context is not None assert not isinstance(captured_context, ToolContext) assert captured_context.tool_input == {"city": "Tokyo"} + + +@pytest.mark.asyncio +async def test_runner_uses_replaced_invoker_context_contract() -> None: + from agents import RunConfig, Runner + from agents.decorators import tool + from agents.testing import ScriptedModel, assistant_message, function_call + + seen: list[tuple[str, str]] = [] + + @tool + async def lookup(ctx: ToolContext[str]) -> str: + seen.append((ctx.tool_call_id, ctx.context)) + return ctx.context + + model = ScriptedModel( + [ + [function_call("lookup", "{}", call_id="first")], + [assistant_message("done")], + [function_call("lookup", "{}", call_id="second")], + [assistant_message("done")], + ] + ) + agent = Agent(name="agent", model=model, tools=[lookup]) + config = RunConfig(tracing_disabled=True) + first = await Runner.run(agent, "start", context="first context", run_config=config) + assert first.final_output == "done" + + async def replacement(ctx: RunContextWrapper[str], _arguments: str) -> str: + assert type(ctx) is RunContextWrapper + seen.append(("replacement", ctx.context)) + return ctx.context + + lookup.on_invoke_tool = replacement + second = await Runner.run(agent, "start", context="second context", run_config=config) + assert second.final_output == "done" + assert seen == [("first", "first context"), ("replacement", "second context")] + outputs = [ + item for item in second.to_input_list() if item.get("type") == "function_call_output" + ] + assert outputs[0]["call_id"] == "second" + assert outputs[0]["output"] == "second context" + model.assert_complete() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("metadata", ["default", "signature", "annotations", "wrapped", "partial"]) +async def test_sdk_invoker_preserves_context_reflection_overrides(metadata: str) -> None: + import functools + import inspect + + from agents.tool import with_function_tool_failure_error_handler + + captured: list[RunContextWrapper[str]] = [] + + async def invoke(ctx: RunContextWrapper[str], _input: str) -> str: + captured.append(ctx) + return ctx.context + + function_tool = FunctionTool( + name="lookup", + description="Look up context.", + params_json_schema={"type": "object", "properties": {}}, + on_invoke_tool=with_function_tool_failure_error_handler(invoke, lambda *_args: None), + ) + invoker = cast(Any, function_tool.on_invoke_tool) + if metadata == "signature": + invoker.__signature__ = inspect.signature(invoke) + elif metadata == "annotations": + invoker.__annotations__ = {"ctx": RunContextWrapper[str]} + elif metadata == "wrapped": + invoker.__wrapped__ = invoke + elif metadata == "partial": + function_tool.on_invoke_tool = functools.partial(invoke) + + context = ToolContext( + context="value", + tool_name="lookup", + tool_call_id="lookup-1", + tool_arguments="{}", + tool_input={"city": "Tokyo"}, + ) + assert ( + await invoke_function_tool(function_tool=function_tool, context=context, arguments="{}") + == "value" + ) + assert captured[0].context == "value" + assert captured[0].tool_input == {"city": "Tokyo"} + if metadata == "default": + assert captured[0] is context + else: + assert type(captured[0]) is RunContextWrapper + assert captured[0].usage is context.usage