Backtestsopenai-agents-pythonrun-20261024-184640#4244
Tool approval is not honored on resume when Runner.run is given a context
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches locate the same root cause: `resolve_resumed_context` built a brand-new `RunContextWrapper` whenever `context=` was supplied, discarding the `_approvals` recorded on the state's wrapper by `state.approve()`, so the resumed run re-interrupted. Both fix the plain-context case identically (mutate the restored wrapper's `.context` in place, keep approvals/usage), and the independent tests pass for both across dict, dataclass, wrapper, streamed and in-memory scenarios. They diverge on the wrapper-override path and on scope. Patch B keeps the caller's `RunContextWrapper` as the run's wrapper, merges the state's approvals into it (state decisions win) and carries usage over, explicitly mirroring the existing `RunState.from_json(context_override=wrapper)` convention. Patch A silently discards a caller-supplied wrapper and only lifts its `.context` value, a behaviour change that could break any caller or existing test relying on `result.context_wrapper is override`. Patch A also goes well beyond the issue: it changes `agent.py` so nested `Agent.as_tool()` resumes now pass the parent application context instead of `None`, and aliases the restored nested wrapper's `usage` to the parent `ToolContext.usage`. That is an adjacent redesign of the nested-resume contract with its own correctness surface (shared Usage object, parent context overwriting the deserialized nested context) and is not needed to fix the reported bug; it adds risk rather than credit. On tests, B's parametrized test covers exactly the issue matrix (run vs run_streamed × dict/dataclass/wrapper × approve/reject = 12 cases, with JSON round-trip and `context_deserializer` as in the repro) plus usage-preservation tests for both override kinds, all of which would fail on base. A's tests are also meaningful (in-place unit test, run and streamed JSON resume, nested as_tool), but a chunk of them exercise A's own extra nested/usage behaviour rather than the issue. B is the tighter, lower-risk fix with the more directly issue-aligned tests.
Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.
Solve
5m 47s
Wall-clock time in the container
Full test suite
No new failures
794 passed · 0 skipped · 794 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
147vs 259 merged
Changed lines, ours vs merged
The issue
View on GitHubPlease read this first
- Have you read the docs? [Agents SDK docs](https://openai.github.io/openai-agents-python/) — yes, including [Human-in-the-loop](https://openai.github.io/openai-agents-python/human_in_the_loop/) and [Running agents](https://openai.github.io/openai-agents-python/running_agents/).
- Have you searched for related issues? Yes.
Describe the bug
A tool with needs_approval=True correctly pauses the run and produces an approval interruption. After serializing the RunState, reconstructing it, calling state.approve(item) and resuming through Runner.run, the tool executes only if no context= was passed to Runner.run.
If any context object is supplied — a plain dict or a dataclass — the resumed run re-interrupts and the tool body is never invoked, despite the approval having been recorded on the reconstructed state.
This is not a context-serialization problem. A plain dict context requires no restoration at all and still fails, and none of context_override=, context_deserializer=, or strict_context=True on RunState.from_json changes the outcome. The RunState context was serialized from a dataclass... warning appears in the dataclass case but is a separate concern — silencing it does not fix the resume.
What I ruled out:
- Not tool identity. With
context=Nonethe resumed callback receives the samecall_idand byte-identical arguments as the interruption carried, so the round-trip preserves them. In the failing cases the interruption reloaded from JSON still reports the correctraw_item.call_idandraw_item.arguments— the data survives; the approval is not applied. - Not a wrapper or third-party interference. The repro uses a bare
FunctionToolwith an inlineon_invoke_tool. Originally found through a tool-wrapping library; reproduces identically without it. - Not agent reuse. Fresh
Agentinstances are constructed for the resumed run in every case.
Not investigated: whether Runner.run_streamed is affected, and the internal approval-key derivation — which seems the likeliest place for a context-dependent mismatch, but I did not want to speculate about internals.
Impact: for integrations that carry identity or authorization through the run context, the only configuration in which approval resume currently works is the one that omits the information required to identify the acting user.
Debug information
- Agents SDK version:
v0.19.2andv0.19.4 - Related library versions (optional, e.g.
any-llm,litellm, orpydantic):openai 2.52.0,pydantic 2.12.5 - Python version:
Python 3.12.3 - Operating system: Linux 6.18.5 x86_64
- Model and model provider: none — the repro uses a scripted
Modelsubclass, so no API key, network, or provider is involved. The defect is in the approval/resume path, not in any model backend. - Does the issue reproduce with the latest Agents SDK release? Yes — 0.19.4 (latest at time of writing) behaves identically to 0.19.2.
- Does the issue occur consistently or intermittently? Consistently, 100% of runs.
No exception is raised. The failure is silent: the resumed run returns final_output=None with a fresh interruption for the same tool call, and the tool body is never entered.
Both blocks below are the output of the single script in Repro steps, run under each version:
openai-agents 0.19.2
no context (control) final='done' invoked=['cA'] interrupts=0 OK
dict final=None invoked=[] interrupts=1 BROKEN
dict + context_override final=None invoked=[] interrupts=1 BROKEN
dict + context_override + strict final=None invoked=[] interrupts=1 BROKEN
dataclass + context_deserializer final=None invoked=[] interrupts=1 BROKEN
dataclass + deserializer + strict final=None invoked=[] interrupts=1 BROKEN
openai-agents 0.19.4
no context (control) final='done' invoked=['cA'] interrupts=0 OK
dict final=None invoked=[] interrupts=1 BROKEN
dict + context_override final=None invoked=[] interrupts=1 BROKEN
dict + context_override + strict final=None invoked=[] interrupts=1 BROKEN
dataclass + context_deserializer final=None invoked=[] interrupts=1 BROKEN
dataclass + deserializer + strict final=None invoked=[] interrupts=1 BROKEN
The only log line emitted (dataclass rows only; not the cause — the dict
rows emit nothing and still fail):
RunState context was serialized from a dataclass. Provide
context_deserializer or context_override to restore the original type.
Repro steps
Self-contained: no API key, no network. invoked records ctx.tool_call_id from inside on_invoke_tool, so an empty list means the tool body never ran. Every row above comes from this one script.
"""openai-agents: a tool approval is not honoured on resume when
Runner.run is given a context.
python repro.py
No API key, no network: the model is a deterministic scripted stub.
Exercises every documented way of restoring the run context, so each row
below is produced by this one script.
"""
import asyncio
import json
from dataclasses import dataclass
import agents
from agents import Agent, FunctionTool, Runner
from agents.items import ModelResponse
from agents.models.interface import Model
from agents.run_state import RunState
from agents.usage import Usage
from openai.types.responses import (
ResponseFunctionToolCall,
ResponseOutputMessage,
ResponseOutputText,
)
agents.set_tracing_disabled(True)
def scripted(turns):
class Scripted(Model):
def __init__(self):
self._turns = list(turns)
self.n = 0
async def get_response(self, system_instructions, input,
model_settings, tools, output_schema, handoffs,
tracing, *, previous_response_id=None,
conversation_id=None, prompt=None):
self.n += 1
turn = self._turns.pop(0) if self._turns else "done"
if isinstance(turn, str):
out = [ResponseOutputMessage(
id=f"m{self.n}", role="assistant", status="completed",
type="message",
content=[ResponseOutputText(type="output_text", text=turn,
annotations=[])])]
else:
out = [ResponseFunctionToolCall(
type="function_call", name=n, arguments=a, call_id=c,
id=f"f{self.n}") for (n, a, c) in turn]
return ModelResponse(output=out, usage=Usage(), response_id=None)
def stream_response(self, *a, **k):
raise NotImplementedError
return Scripted()
@dataclass
class Ctx:
principal: str
async def attempt(label, context, **from_json_kwargs):
"""pause on approval -> serialize -> reconstruct -> approve -> resume."""
invoked = []
async def on_invoke(ctx, input_str):
invoked.append(ctx.tool_call_id)
return "tool-ran"
def tool():
return FunctionTool(
name="w", description="d",
params_json_schema={"type": "object", "properties": {},
"additionalProperties": False},
on_invoke_tool=on_invoke, strict_json_schema=False,
needs_approval=True)
run_kwargs = {} if context is None else {"context": context}
first = Agent(name="a", instructions="i", tools=[tool()],
model=scripted([[("w", "{}", "cA")], "unused"]))
paused = await Runner.run(first, "go", **run_kwargs)
assert paused.interruptions, "expected an approval interruption"
blob = json.dumps(paused.to_state().to_json())
second = Agent(name="a", instructions="i", tools=[tool()],
model=scripted(["done"]))
state = await RunState.from_json(second, json.loads(blob),
**from_json_kwargs)
state.approve(state.get_interruptions()[0])
resumed = await Runner.run(second, state, **run_kwargs)
status = "OK" if invoked else "BROKEN"
print(
f"{label:36s} "
f"final={resumed.final_output!r:8s} "
f"invoked={invoked!s:9s} "
f"interrupts={len(resumed.interruptions)} "
f"{status}"
)
async def main():
print(f"openai-agents {getattr(agents, '__version__', '?')}")
dict_ctx = {"principal": "ella"}
obj_ctx = Ctx("ella")
def restore_obj(data):
return Ctx(**data) if isinstance(data, dict) else data
await attempt("no context (control)", None)
await attempt("dict", dict_ctx)
await attempt("dict + context_override", dict_ctx,
context_override=dict_ctx)
await attempt("dict + context_override + strict", dict_ctx,
context_override=dict_ctx, strict_context=True)
await attempt("dataclass + context_deserializer", obj_ctx,
context_deserializer=restore_obj)
await attempt("dataclass + deserializer + strict", obj_ctx,
context_deserializer=restore_obj, strict_context=True)
if __name__ == "__main__":
asyncio.run(main())
Expected behavior
All six rows resume and invoke the tool:
no context (control) final='done' invoked=['cA'] interrupts=0 OK
dict final='done' invoked=['cA'] interrupts=0 OK
dict + context_override final='done' invoked=['cA'] interrupts=0 OK
dict + context_override + strict final='done' invoked=['cA'] interrupts=0 OK
dataclass + context_deserializer final='done' invoked=['cA'] interrupts=0 OK
dataclass + deserializer + strict final='done' invoked=['cA'] interrupts=0 OK
Supplying a run context should not affect whether an approval recorded via state.approve(...) is honoured on resume.
The two patches
src/agents/run_internal/agent_runner_helpers.pyindex 348908b7..21046a26 100644@@ -283,12 +283,24 @@ def resolve_resumed_context( run_state: RunState[TContext], context: RunContextWrapper[TContext] | TContext | None, ) -> RunContextWrapper[TContext]:- """Return the context wrapper for a resumed run, overriding when provided."""- if context is not None:- context_wrapper = ensure_context_wrapper(context)- set_agent_tool_state_scope(context_wrapper, run_state._agent_tool_state_scope_id)- run_state._context = context_wrapper- return context_wrapper+ """Return the context wrapper for a resumed run, overriding when provided.++ Overriding the context must not discard run state recorded on the state's wrapper, such as+ tool approvals made via ``RunState.approve()`` / ``RunState.reject()``.+ """+ state_wrapper = run_state._context+ if isinstance(context, RunContextWrapper):+ if state_wrapper is not None and state_wrapper is not context:+ # Decisions recorded on the state take precedence over the override's own records.+ context._approvals = {**context._approvals, **state_wrapper._approvals}+ # Carry run usage over, matching RunState.from_json(context_override=wrapper).+ context.usage = state_wrapper.usage+ set_agent_tool_state_scope(context, run_state._agent_tool_state_scope_id)+ run_state._context = context+ return context+ if context is not None and state_wrapper is not None:+ # Swap only the user context so approvals, usage, and tool input on the state survive.+ state_wrapper.context = cast(TContext, context) if run_state._context is None: run_state._context = ensure_context_wrapper(context) set_agent_tool_state_scope(run_state._context, run_state._agent_tool_state_scope_id)tests/test_run_state.pyindex a6bad8a4..c22c6c73 100644@@ -3451,6 +3451,129 @@ class TestRunStateResumption: assert result.final_output == "done" assert result.context_wrapper.context == override_context + @pytest.mark.asyncio+ @pytest.mark.parametrize("streamed", [False, True], ids=["run", "run_streamed"])+ @pytest.mark.parametrize("context_kind", ["dict", "dataclass", "wrapper"])+ @pytest.mark.parametrize("decision", ["approve", "reject"])+ async def test_resume_with_context_honors_state_approval_decisions(+ self, streamed: bool, context_kind: str, decision: str+ ):+ """Approvals recorded on a RunState must survive a context passed on resume."""++ @dataclass+ class Principal:+ name: str++ invoked: list[str] = []++ async def sensitive() -> str:+ invoked.append("ran")+ return "tool-ran"++ def build_agent(model: FakeModel) -> Agent[Any]:+ tool = function_tool(sensitive, name_override="sensitive", needs_approval=True)+ return Agent(name="TestAgent", model=model, tools=[tool])++ def make_context() -> Any:+ if context_kind == "dict":+ return {"principal": "ella"}+ if context_kind == "dataclass":+ return Principal("ella")+ return RunContextWrapper(context={"principal": "ella"})++ async def run_once(agent: Agent[Any], run_input: Any, context: Any) -> Any:+ if not streamed:+ return await Runner.run(agent, run_input, context=context)+ streamed_result = Runner.run_streamed(agent, run_input, context=context)+ async for _ in streamed_result.stream_events():+ pass+ return streamed_result++ first_model = FakeModel()+ first_model.set_next_output([get_function_tool_call("sensitive", "{}", call_id="cA")])+ paused = await run_once(build_agent(first_model), "go", make_context())+ assert paused.interruptions+ blob = json.dumps(paused.to_state().to_json())++ second_model = FakeModel()+ second_model.set_next_output([get_text_message("done")])+ second_agent = build_agent(second_model)+ from_json_kwargs: dict[str, Any] = {}+ if context_kind == "dataclass":+ from_json_kwargs["context_deserializer"] = lambda data: Principal(**data)+ state = await RunState.from_json(second_agent, json.loads(blob), **from_json_kwargs)+ interruption = state.get_interruptions()[0]+ if decision == "approve":+ state.approve(interruption)+ else:+ state.reject(interruption, rejection_message="denied by reviewer")++ resume_context = make_context()+ resumed = await run_once(second_agent, state, resume_context)++ assert resumed.final_output == "done"+ assert resumed.interruptions == []+ expected_user_context = (+ resume_context.context+ if isinstance(resume_context, RunContextWrapper)+ else resume_context+ )+ assert resumed.context_wrapper.context == expected_user_context+ tool_outputs = [+ item.output for item in resumed.new_items if isinstance(item, ToolCallOutputItem)+ ]+ if decision == "approve":+ assert invoked == ["ran"]+ assert tool_outputs == ["tool-ran"]+ else:+ assert invoked == []+ assert tool_outputs == ["denied by reviewer"]++ @pytest.mark.asyncio+ async def test_resume_with_context_override_preserves_state_usage(self):+ """Passing a plain context on resume replaces only the user context, not run usage."""+ model = FakeModel()+ agent = Agent(name="TestAgent", model=model)+ state = make_state(+ agent,+ context=RunContextWrapper(context={"key": "value1"}),+ original_input="test",+ max_turns=3,+ )+ assert state._context is not None+ state._context.usage = Usage(requests=2, input_tokens=10, output_tokens=5, total_tokens=15)++ model.set_hardcoded_usage(Usage(requests=1, input_tokens=4, output_tokens=1, total_tokens=5))+ model.set_next_output([get_text_message("done")])+ result = await Runner.run(agent, state, context={"key": "value2"})++ assert result.context_wrapper.context == {"key": "value2"}+ assert result.context_wrapper.usage.requests == 3+ assert result.context_wrapper.usage.input_tokens == 14++ @pytest.mark.asyncio+ async def test_resume_with_wrapper_override_preserves_state_usage(self):+ """Passing a new RunContextWrapper on resume keeps the run usage recorded on the state."""+ model = FakeModel()+ agent = Agent(name="TestAgent", model=model)+ state = make_state(+ agent,+ context=RunContextWrapper(context={"key": "value1"}),+ original_input="test",+ max_turns=3,+ )+ assert state._context is not None+ state._context.usage = Usage(requests=2, input_tokens=10, output_tokens=5, total_tokens=15)++ model.set_hardcoded_usage(Usage(requests=1, input_tokens=4, output_tokens=1, total_tokens=5))+ model.set_next_output([get_text_message("done")])+ override = RunContextWrapper(context={"key": "value2"})+ result = await Runner.run(agent, state, context=override)++ assert result.context_wrapper is override+ assert result.context_wrapper.usage.requests == 3+ assert result.context_wrapper.usage.input_tokens == 14+ @pytest.mark.asyncio async def test_run_result_streaming_to_state_with_interruptions(self): """Test RunResultStreaming.to_state() sets _current_step with interruptions."""
src/agents/agent.pyindex 7768372ce..09dae267d 100644@@ -856,6 +856,11 @@ class Agent(AgentBase, Generic[TContext]): context, pending_run_result.interruptions, )+ # Keep accumulating nested post-resume usage on the parent+ # ToolContext accumulator. resolve_resumed_context only+ # replaces application .context and would otherwise leave+ # the restored nested wrapper on a detached Usage object.+ resume_state._context.usage = context.usage consume_agent_tool_run_result( context.tool_call, scope_id=tool_state_scope_id,@@ -867,7 +872,10 @@ class Agent(AgentBase, Generic[TContext]): run_result_streaming = Runner.run_streamed( starting_agent=cast(Agent[Any], self), input=resume_state or resolved_input,- context=None if resume_state is not None else cast(Any, nested_context),+ # On resume, pass the parent application context so+ # resolve_resumed_context can update the nested restored+ # wrapper's .context without dropping nested approvals.+ context=cast(Any, nested_context), run_config=resolved_run_config, max_turns=resolved_max_turns, hooks=hooks,@@ -936,7 +944,10 @@ class Agent(AgentBase, Generic[TContext]): run_result = await Runner.run( starting_agent=cast(Agent[Any], self), input=resume_state or resolved_input,- context=None if resume_state is not None else cast(Any, nested_context),+ # On resume, pass the parent application context so+ # resolve_resumed_context can update the nested restored+ # wrapper's .context without dropping nested approvals.+ context=cast(Any, nested_context), run_config=resolved_run_config, max_turns=resolved_max_turns, hooks=hooks,src/agents/run_internal/agent_runner_helpers.pyindex 348908b79..2803c4695 100644@@ -283,8 +283,28 @@ def resolve_resumed_context( run_state: RunState[TContext], context: RunContextWrapper[TContext] | TContext | None, ) -> RunContextWrapper[TContext]:- """Return the context wrapper for a resumed run, overriding when provided."""+ """Return the context wrapper for a resumed run, overriding when provided.++ When an override is supplied, the restored ``RunContextWrapper`` stays+ authoritative. Only its application ``context`` value is replaced so+ run-owned wrapper state (approvals, usage, turn input, tool input, ...)+ survives the override instead of being dropped by a fresh wrapper.+ Nested ``Agent.as_tool()`` resumes should pass the parent application+ context into ``Runner.run`` / ``Runner.run_streamed`` so this same path+ applies there.+ """ if context is not None:+ existing_context = run_state._context+ if existing_context is not None:+ application_context = (+ context.context if isinstance(context, RunContextWrapper) else context+ )+ if existing_context is not context:+ existing_context.context = application_context+ set_agent_tool_state_scope(existing_context, run_state._agent_tool_state_scope_id)+ run_state._context = existing_context+ return existing_context+ context_wrapper = ensure_context_wrapper(context) set_agent_tool_state_scope(context_wrapper, run_state._agent_tool_state_scope_id) run_state._context = context_wrappertests/test_run_state.pyindex a6bad8a4b..45cd031ae 100644@@ -68,7 +68,10 @@ from agents.items import ( ) from agents.run_context import RunContextWrapper from agents.run_error_handlers import RunErrorHandlerResult, RunErrorHandlers-from agents.run_internal.agent_runner_helpers import resolve_trace_settings+from agents.run_internal.agent_runner_helpers import (+ resolve_resumed_context,+ resolve_trace_settings,+) from agents.run_internal.items import ( NestedHistoryOwnedItemRef, digest_input_item,@@ -7287,3 +7290,220 @@ async def test_resume_rejected_function_approval_emits_output() -> None: for item in resumed.new_items ) assert calls == []+++def test_resolve_resumed_context_keeps_restored_wrapper_and_replaces_app_context() -> None:+ """Override must mutate the restored wrapper in place, not allocate a replacement."""+ from agents.run_context import _ApprovalRecord++ agent = Agent(name="unit-agent")+ original_context = {"user": "original"}+ restored_wrapper = RunContextWrapper(context=original_context)+ restored_wrapper.tool_input = {"scoped": True}+ restored_wrapper.turn_input = [{"role": "user", "content": "hi"}]+ restored_usage = restored_wrapper.usage+ restored_approvals = restored_wrapper._approvals+ restored_approvals["needs_ok"] = _ApprovalRecord(approved=["1"])++ state = make_state(agent, context=restored_wrapper, original_input="hi")+ override = {"user": "reviewer"}++ resolved = resolve_resumed_context(run_state=state, context=override)++ assert resolved is restored_wrapper+ assert resolved is state._context+ assert resolved.context is override+ assert resolved.context is not original_context+ assert resolved.usage is restored_usage+ assert resolved._approvals is restored_approvals+ assert resolved._approvals["needs_ok"].approved == ["1"]+ assert resolved.turn_input == [{"role": "user", "content": "hi"}]+ assert resolved.tool_input == {"scoped": True}++ # Passing a wrapper only donates its application value; run-owned state stays.+ donor = RunContextWrapper(context={"user": "from-wrapper"})+ donor.tool_input = {"should": "not-win"}+ resolved_again = resolve_resumed_context(run_state=state, context=donor)+ assert resolved_again is restored_wrapper+ assert resolved_again.context == {"user": "from-wrapper"}+ assert resolved_again.tool_input == {"scoped": True}+++async def _interrupted_approval_state_with_tool_input(+ *,+ calls: list[str],+ seen_contexts: list[dict[str, str]],+ seen_tool_inputs: list[object],+) -> tuple[Any, Any, RunState[Any, Agent[Any]]]:+ @function_tool(needs_approval=True)+ async def needs_ok(ctx: RunContextWrapper[dict[str, str]], text: str) -> str:+ seen_contexts.append(dict(ctx.context))+ seen_tool_inputs.append(ctx.tool_input)+ calls.append(text)+ return text++ model, agent = make_model_and_agent(tools=[needs_ok], name="agent")+ model.add_multiple_turn_outputs(+ [+ [get_function_tool_call("needs_ok", json.dumps({"text": "one"}), call_id="1")],+ [get_final_output_message("done")],+ ]+ )++ first = await Runner.run(agent, input="hi", context={"user": "original"})+ assert first.interruptions+ state = first.to_state()+ assert state._context is not None+ state._context.tool_input = {"scoped": True}+ state.approve(first.interruptions[0])+ restored = await RunState.from_json(agent, state.to_json())+ assert restored._context is not None+ assert restored._context.tool_input == {"scoped": True}+ assert restored._context._approvals+ return model, agent, restored+++@pytest.mark.asyncio+async def test_resume_approved_function_approval_via_json_with_context_override() -> None:+ """JSON resume + context= keeps approvals/tool_input and applies the new app context."""+ calls: list[str] = []+ seen_contexts: list[dict[str, str]] = []+ seen_tool_inputs: list[object] = []+ _model, agent, restored = await _interrupted_approval_state_with_tool_input(+ calls=calls, seen_contexts=seen_contexts, seen_tool_inputs=seen_tool_inputs+ )+ restored_wrapper = restored._context+ assert restored_wrapper is not None+ override = {"user": "reviewer"}++ resumed = await Runner.run(agent, input=restored, context=override)++ assert resumed.final_output == "done"+ assert resumed.interruptions == []+ assert calls == ["one"]+ assert seen_contexts == [override]+ assert seen_tool_inputs == [{"scoped": True}]+ assert resumed.context_wrapper is restored_wrapper+ assert resumed.context_wrapper.context == override+ assert resumed.context_wrapper.tool_input == {"scoped": True}+ assert resumed.context_wrapper._approvals is restored_wrapper._approvals+++@pytest.mark.asyncio+async def test_resume_approved_function_approval_streamed_with_context_override() -> None:+ """Streamed resume + context= keeps approvals/tool_input and applies the new app context."""+ calls: list[str] = []+ seen_contexts: list[dict[str, str]] = []+ seen_tool_inputs: list[object] = []+ _model, agent, restored = await _interrupted_approval_state_with_tool_input(+ calls=calls, seen_contexts=seen_contexts, seen_tool_inputs=seen_tool_inputs+ )+ restored_wrapper = restored._context+ assert restored_wrapper is not None+ override = {"user": "reviewer"}++ resumed = Runner.run_streamed(agent, restored, context=override)+ async for _ in resumed.stream_events():+ pass++ assert resumed.final_output == "done"+ assert resumed.interruptions == []+ assert calls == ["one"]+ assert seen_contexts == [override]+ assert seen_tool_inputs == [{"scoped": True}]+ assert resumed.context_wrapper is restored_wrapper+ assert resumed.context_wrapper.context == override+ assert resumed.context_wrapper.tool_input == {"scoped": True}+ assert resumed.context_wrapper._approvals is restored_wrapper._approvals+++@pytest.mark.asyncio+async def test_resume_nested_agent_as_tool_with_context_override() -> None:+ """Nested Agent.as_tool() resume sees context= while keeping nested wrapper-owned state."""+ seen_contexts: list[dict[str, str]] = []+ seen_tool_inputs: list[object] = []+ calls: list[str] = []++ @dataclass+ class NestedParams:+ input: str++ @function_tool(needs_approval=True)+ async def needs_ok(ctx: RunContextWrapper[dict[str, str]], text: str) -> str:+ seen_contexts.append(dict(ctx.context))+ seen_tool_inputs.append(ctx.tool_input)+ calls.append(text)+ return text++ nested_turn_usage = Usage(+ requests=1,+ input_tokens=17,+ output_tokens=3,+ total_tokens=20,+ )+ nested_model = FakeModel()+ nested_model.set_hardcoded_usage(nested_turn_usage)+ nested_agent = Agent(name="nested", tools=[needs_ok], model=nested_model)+ nested_model.add_multiple_turn_outputs(+ [+ [get_function_tool_call("needs_ok", json.dumps({"text": "one"}), call_id="inner-1")],+ [get_final_output_message("nested-done")],+ ]+ )++ outer_model = FakeModel()+ outer = Agent(+ name="outer",+ tools=[+ nested_agent.as_tool(+ tool_name="nested_agent",+ tool_description="Run nested agent",+ parameters=NestedParams,+ )+ ],+ model=outer_model,+ )+ outer_model.add_multiple_turn_outputs(+ [+ [+ get_function_tool_call(+ "nested_agent",+ json.dumps({"input": "hi"}),+ call_id="outer-1",+ )+ ],+ [get_final_output_message("done")],+ ]+ )++ first = await Runner.run(outer, input="hi", context={"user": "original"})+ assert first.interruptions+ assert first.interruptions[0].tool_name == "needs_ok"++ state = first.to_state()+ assert state._context is not None+ state._context.tool_input = {"scoped": True}+ state.approve(first.interruptions[0])+ restored = await RunState.from_json(outer, state.to_json())+ restored_wrapper = restored._context+ assert restored_wrapper is not None+ assert restored_wrapper.tool_input == {"scoped": True}+ assert restored_wrapper._approvals+ usage_before_resume = restored_wrapper.usage.input_tokens+ override = {"user": "reviewer"}++ resumed = await Runner.run(outer, input=restored, context=override)++ assert resumed.final_output == "done"+ assert resumed.interruptions == []+ assert calls == ["one"]+ assert seen_contexts == [override]+ assert seen_tool_inputs == [{"input": "hi"}]+ assert resumed.context_wrapper is restored_wrapper+ assert resumed.context_wrapper.context == override+ assert resumed.context_wrapper.tool_input == {"scoped": True}+ assert resumed.context_wrapper._approvals is restored_wrapper._approvals+ # Nested post-resume model turns must keep accruing on the parent usage object.+ assert resumed.context_wrapper.usage.input_tokens == (+ usage_before_resume + nested_turn_usage.input_tokens+ )