diff --git a/native/codex/src/lib.rs b/native/codex/src/lib.rs index 1bf06b805f..59ae0055f1 100644 --- a/native/codex/src/lib.rs +++ b/native/codex/src/lib.rs @@ -486,6 +486,11 @@ impl Thread { self.lease.operations.buffer.drain() } + #[getter] + fn thread_id(&self) -> String { + self.lease.id.to_string() + } + #[getter] fn model(&self) -> String { self.lease.model.clone() diff --git a/src/agents/__init__.py b/src/agents/__init__.py index 27845e1447..1bd38c52af 100644 --- a/src/agents/__init__.py +++ b/src/agents/__init__.py @@ -6,6 +6,7 @@ from openai import AsyncOpenAI from . import _config, sandbox +from ._plan import update_plan from .agent import ( Agent, AgentBase, @@ -96,6 +97,7 @@ SessionSettings, is_openai_responses_compaction_aware_session, ) +from .memory.resumable_session import Plan, PlanStep from .model_settings import ModelSettings from .models.interface import Model, ModelProvider, ModelTracing from .models.multi_provider import MultiProvider @@ -489,6 +491,9 @@ def enable_verbose_stdout_logging() -> None: "ItemHelpers", "RunHooks", "AgentHooks", + "Plan", + "PlanStep", + "update_plan", "ResumableSession", "ResumableSessionError", "ResumableSessionStore", diff --git a/src/agents/_plan.py b/src/agents/_plan.py new file mode 100644 index 0000000000..0c52cb3c22 --- /dev/null +++ b/src/agents/_plan.py @@ -0,0 +1,32 @@ +from .exceptions import UserError +from .memory.resumable_session import Plan, PlanStep +from .tool import Tool, function_tool +from .tool_context import ToolContext + +_MISSING_SESSION = "update_plan requires a ResumableSession passed to Runner as session." + + +async def _update_plan( + ctx: ToolContext, steps: list[PlanStep], explanation: str | None = None +) -> str: + """Replace the plan with ordered steps and their statuses. Empty steps clear the plan.""" + propose = ctx._propose_plan + if propose is None: + raise UserError(_MISSING_SESSION) + ctx._propose_plan = None + propose(Plan(tool_call_id=ctx.tool_call_id, steps=tuple(steps), explanation=explanation)) + return "Plan updated." + + +update_plan = function_tool(_update_plan, name_override="update_plan", failure_error_function=None) + + +def is_plan_tool(tool: Tool) -> bool: + return getattr(tool, "__wrapped__", None) is _update_plan + + +def validate_plan_session(tools: list[Tool]) -> None: + from .run_internal.agent_tool_configuration import current_plan_session + + if current_plan_session() is None and any(is_plan_tool(tool) for tool in tools): + raise UserError(_MISSING_SESSION) diff --git a/src/agents/memory/resumable_session.py b/src/agents/memory/resumable_session.py index 3eaec617d8..0ec93f6884 100644 --- a/src/agents/memory/resumable_session.py +++ b/src/agents/memory/resumable_session.py @@ -8,11 +8,13 @@ from uuid import uuid4 from pydantic import ( + AliasChoices, BaseModel, ConfigDict, Field, TypeAdapter, ValidationError, + field_serializer, field_validator, model_validator, ) @@ -109,14 +111,61 @@ def _history_adapter() -> TypeAdapter[list[TResponseInputItem]]: return TypeAdapter(list[TResponseInputItem]) +class PlanStep(BaseModel): + """One ordered step with a model-reported status.""" + + model_config = ConfigDict(extra="forbid", frozen=True, strict=True) + + text: str = Field(validation_alias=AliasChoices("text", "step"), repr=False) + status: Literal["pending", "in_progress", "completed"] + + +class Plan(BaseModel): + """A saved snapshot from one SDK tool call or one native thread and turn.""" + + model_config = ConfigDict(extra="forbid", frozen=True, strict=True) + + thread_id: str | None = Field( + default=None, repr=False, min_length=1, exclude_if=lambda v: v is None + ) + turn_id: str | None = Field( + default=None, repr=False, min_length=1, exclude_if=lambda v: v is None + ) + tool_call_id: str | None = Field( + default=None, repr=False, min_length=1, exclude_if=lambda v: v is None + ) + steps: tuple[PlanStep, ...] = Field(validation_alias=AliasChoices("steps", "plan")) + explanation: str | None = Field(default=None, repr=False) + + @model_validator(mode="after") + def _validate_source(self) -> Plan: + if self.tool_call_id is None: + if self.thread_id is None or self.turn_id is None: + raise ValueError("A native plan requires a thread and turn.") + elif self.thread_id is not None or self.turn_id is not None: + raise ValueError("A plan must have a single source.") + return self + + class _Checkpoint(BaseModel): model_config = ConfigDict(extra="forbid", strict=True, frozen=True) - version: Literal[1, 2] + # Versions 3 and 4 include a checklist. Versions 2 and 4 require redaction. + version: Literal[1, 2, 3, 4] revision: str = Field(min_length=1) status: Literal["ready", "paused", "active"] history: list[Any] run_state: str | None + codex_checklist: Plan | None = Field(default=None, exclude_if=lambda v: v is None) + + @field_serializer("codex_checklist", when_used="unless-none") + def _save_plan(self, plan: Plan) -> dict[str, Any]: + # Keep the original checkpoint wire format independent of the Python API. + return { + **plan.model_dump(exclude={"steps", "explanation"}), + "plan": [{"step": step.text, "status": step.status} for step in plan.steps], + "explanation": plan.explanation, + } @field_validator("history") @classmethod @@ -128,6 +177,8 @@ def validate_history(cls, value: list[Any]) -> list[Any]: @model_validator(mode="after") def validate_status(self) -> _Checkpoint: + if self.version in (3, 4) and self.codex_checklist is None: + raise ValueError("Checkpoint version requires a checklist.") if (self.status == "ready" and self.run_state is not None) or ( self.status == "paused" and not self.run_state ): @@ -202,6 +253,50 @@ def __init__( self._checkpoint = _checkpoint self._serialized = _serialized + @property + def plan(self) -> Plan | None: + """Read the last saved plan without starting a run. + + Register `update_plan` on an ordinary agent. With CodexProvider, use + `config_overrides=["tools.update_plan.enabled=true"]` instead of + registering the SDK tool. Bounded native delegation disables this tool. + + ```python + from agents import Agent, ResumableSession, Runner, update_plan + + agent = Agent(name="Planner", tools=[update_plan]) + session = await ResumableSession.create(store) + session_id = session.session_id + await Runner.run(agent, "Plan a reading group", session=session) + + session = await ResumableSession.resume(store, session_id) + plan = session.plan + if plan is not None: + for step in plan.steps: + print(step.text, step.status) + ``` + + Read after the run or stream ends, including a pause for approval. + `None` means no accepted update. Each update replaces the entire plan. + For parallel calls, the last accepted update wins. Empty steps + clear the plan. No update leaves the previous snapshot intact. + The source is an SDK `tool_call_id` or a native `thread_id` and `turn_id`. + + This property reads the loaded checkpoint. Resume again to see another + worker's changes. Active checkpoints raise `ResumableSessionError`. + An agent offering the SDK tool requires a ResumableSession before + its model request. History-only sessions cannot track plans. Child agents cannot write + their parent's plan. A plan grants no authority, does not verify + completed work and does not schedule another run. + + Treat text and explanations as private. `RunConfig.redact_text` covers + saved plans and SDK history, not native execution or existing records. + Older SDK versions may reject checkpoints with a plan. + """ + if self._checkpoint.status == "active": + raise ResumableSessionError("active") + return self._checkpoint.codex_checklist + @property def is_paused(self) -> bool: """Whether this loaded checkpoint contains a pending approval run.""" @@ -331,9 +426,9 @@ async def _begin_run( if current_redactor() is not None: require_clean(tool_hooks.context.context) if not self.is_paused: - from ..models.codex import _validate_static_children + from ..models.codex import _validate_static_tools - _validate_static_children(tool_hooks) + _validate_static_tools(tool_hooks) else: from ..run_internal.native_approvals import validate_native_restore_hooks from ..run_internal.tool_planning import ( @@ -362,7 +457,11 @@ async def _begin_run( await self._replace(active, expected=self._serialized) async def _save_checkpoint( - self, history: list[TResponseInputItem], state: RunState[Any, Any] | None + self, + history: list[TResponseInputItem], + state: RunState[Any, Any] | None, + *, + codex_checklist: Plan | None = None, ) -> _ResumableSessionBinding: if self._checkpoint.status != "active": raise ResumableSessionError("conflict") @@ -373,6 +472,11 @@ async def _save_checkpoint( revision=uuid4().hex, status="paused" if state is not None else "ready", history=copy.deepcopy(history), + codex_checklist=( + codex_checklist + if codex_checklist is not None + else self._checkpoint.codex_checklist + ), run_state=state.to_string() if state is not None else None, ) except Exception: @@ -383,7 +487,12 @@ async def _save_checkpoint( return _ResumableSessionBinding(self, checkpoint.revision) async def _replace(self, checkpoint: _Checkpoint, *, expected: str | None) -> None: - if checkpoint.version == 2 and current_redactor() is None: + # Earlier checklist records used 1 or 2. Upgrade on write, including active claims. + if checkpoint.codex_checklist is not None and checkpoint.version in (1, 2): + checkpoint = checkpoint.model_copy( + update={"version": 4 if checkpoint.version == 2 else 3} + ) + if checkpoint.version in (2, 4) and current_redactor() is None: error = UserError("Continuing this resumable session requires RunConfig.redact_text.") _mark_error_data_redacted(error) raise error diff --git a/src/agents/models/_run_context.py b/src/agents/models/_run_context.py index 116e68bcc1..654bd4416c 100644 --- a/src/agents/models/_run_context.py +++ b/src/agents/models/_run_context.py @@ -13,6 +13,7 @@ from ..lifecycle import RunHooks from ..run_config import RunConfig, ToolExecutionConfig from ..run_context import RunContextWrapper + from ..run_internal.resumable_session import ResumableRun @dataclass(frozen=True) @@ -22,7 +23,7 @@ class ModelToolHooks: context: RunContextWrapper[Any] lifecycle: RunHooks[Any] settings: ToolExecutionConfig | None - resumable: bool = False + resumable: ResumableRun | None = None _MODEL_RUN_CONTEXT: ContextVar[tuple[object | None, ModelToolHooks | None]] = ContextVar( diff --git a/src/agents/models/codex.py b/src/agents/models/codex.py index 4a61399c41..14ecd526a1 100644 --- a/src/agents/models/codex.py +++ b/src/agents/models/codex.py @@ -42,6 +42,7 @@ from ..exceptions import UserError from ..handoffs import Handoff from ..items import ModelResponse, TResponseInputItem, TResponseStreamEvent +from ..memory.resumable_session import Plan, PlanStep from ..memory.session import await_session_mutation as _join_close from ..model_settings import ModelSettings from ..retry import ModelRetryAdvice, ModelRetryAdviceRequest @@ -288,7 +289,17 @@ def _pending_native_call( _CHILD_TOOL_CONFLICT = "Native children cannot use SDK tools, handoffs, or tool hooks." -def _validate_static_children(bindings: ModelToolHooks) -> None: +def _check_plan_tool(tools: list[Tool]) -> None: + from .._plan import is_plan_tool + + if any(is_plan_tool(tool) for tool in tools): + raise UserError( + "Remove the SDK update_plan tool and enable tools.update_plan.enabled " + "in CodexProvider.config_overrides." + ) + + +def _validate_static_tools(bindings: ModelToolHooks) -> None: """Reject known conflicts before a fresh checkpoint claim, without discovery.""" from ..agent import Agent from ..run_internal.tool_declarations import _covered @@ -304,18 +315,21 @@ def _validate_static_children(bindings: ModelToolHooks) -> None: provider, name = config.model_provider, selected else: return + policy = config.tool_execution.prepare_tool_declaration if config.tool_execution else None + static_tools = [ + t + for t in agent.tools + if not isinstance(t, FunctionTool) + or (t.is_enabled is True and (policy is None or not _covered(t))) + ] if provider._children is None: + _check_plan_tool(static_tools) return settings = agent.model_settings.resolve(config.model_settings) if settings.tool_choice == "required": raise UserError("Native children cannot require an SDK tool. Use tool_choice='auto'.") - policy = config.tool_execution.prepare_tool_declaration if config.tool_execution else None if ( - any( - not isinstance(t, FunctionTool) - or (t.is_enabled is True and (policy is None or not _covered(t))) - for t in agent.tools - ) + static_tools or any(isinstance(h, Agent) or h.is_enabled is True for h in agent.handoffs) or _uses_sdk_workspace([], bindings) or CodexToolHooks.for_run(bindings, set()) is not None @@ -486,6 +500,7 @@ async def stream_response( raise UserError("CodexProvider does not support Responses API state or prompt IDs.") effort, summary = _settings(model_settings) history, turn_input = prepare_codex_history(input, tools) + _check_plan_tool(tools) dynamic_tools, identities = prepare_dynamic_tools(tools, handoffs) require_sdk_call = model_settings.tool_choice == "required" if require_sdk_call: @@ -603,6 +618,8 @@ async def stream_response( ) observations = CodexOperationTracing(identities, input) completed: Response | None = None + checkpoint = bindings.resumable if bindings is not None else None + checklist = None resources = AsyncExitStack() output: dict[str, Any] = {} streamed: set[str] = set() @@ -749,6 +766,21 @@ async def interrupt_when_ready() -> None: ) pending_approval = event continue + if kind == "plan_update": + # Core emits this only after accepting update_plan on the leased thread. + if checkpoint is not None and turn_id and event.get("id") == turn_id: + from .. import _redaction + + checklist = Plan( + thread_id=thread.thread_id, + turn_id=turn_id, + explanation=_redaction.redact_payload(message.get("explanation")), + steps=tuple( + PlanStep(**dict(item, step=_redaction.redact_payload(item["step"]))) + for item in message["plan"] + ), + ) + continue if kind == "dynamic_tool_call_request": if message.get("turnId") != turn_id: continue @@ -1090,6 +1122,9 @@ async def interrupt_when_ready() -> None: type="response.output_item.done", ) sequence += 1 - yield ResponseCompletedEvent( + completed_event = ResponseCompletedEvent( response=completed, sequence_number=sequence, type="response.completed" ) + if checkpoint is not None and checklist is not None: + checkpoint.plan = checklist + yield completed_event diff --git a/src/agents/run.py b/src/agents/run.py index cb033430d3..8253f68f03 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -701,7 +701,9 @@ async def run( decisions = _DecisionRun( starting_agent, run_config.tracing_disabled, kwargs.get("context") ) - with agent_tool_configuration_run(configuration_agent): + with agent_tool_configuration_run( + configuration_agent, session if isinstance(session, ResumableRun) else None + ): async with decisions.bind(): result = await self._run_impl(starting_agent, input, **kwargs) require_clean_final_output( @@ -3118,7 +3120,9 @@ async def stream() -> None: if run_state is not None and run_state._current_agent is not None else starting_agent ) - with agent_tool_configuration_run(configuration_agent): + with agent_tool_configuration_run( + configuration_agent, session if isinstance(session, ResumableRun) else None + ): await start_streaming( starting_input=input_for_result, streamed_result=streamed_result, diff --git a/src/agents/run_internal/agent_tool_configuration.py b/src/agents/run_internal/agent_tool_configuration.py index de6b313f1f..777321e175 100644 --- a/src/agents/run_internal/agent_tool_configuration.py +++ b/src/agents/run_internal/agent_tool_configuration.py @@ -12,6 +12,7 @@ if TYPE_CHECKING: from ..agent import AgentBase + from .resumable_session import ResumableRun @dataclass(eq=False) @@ -24,6 +25,7 @@ class _ToolResolution: @dataclass class _ToolConfigurationRun: + resumable: ResumableRun | None = field(default=None, repr=False) resolutions: dict[int, _ToolResolution] = field(default_factory=dict) closed: bool = False @@ -57,10 +59,17 @@ def _raise_conflict() -> None: ) +def current_plan_session() -> ResumableRun | None: + owner = _current_run.get() + return owner.resumable if owner is not None and not owner.closed else None + + @contextmanager -def agent_tool_configuration_run(agent: AgentBase[Any]) -> Iterator[None]: +def agent_tool_configuration_run( + agent: AgentBase[Any], resumable: ResumableRun | None = None +) -> Iterator[None]: """Own configuration checks across all turns without persisting runtime locks or state.""" - owner = _ToolConfigurationRun() + owner = _ToolConfigurationRun(resumable=resumable) token = _current_run.set(owner) try: register_agent_tool_configuration(agent) @@ -68,6 +77,7 @@ def agent_tool_configuration_run(agent: AgentBase[Any]) -> Iterator[None]: finally: with _resolution_lock: owner.closed = True + owner.resumable = None for agent_id, resolution in owner.resolutions.items(): active = _resolutions[agent_id] # Preserve changes from failed/cancelled callbacks for surviving runs. diff --git a/src/agents/run_internal/resumable_session.py b/src/agents/run_internal/resumable_session.py index 8d612a736f..96105f2c35 100644 --- a/src/agents/run_internal/resumable_session.py +++ b/src/agents/run_internal/resumable_session.py @@ -8,6 +8,7 @@ from ..items import ToolApprovalItem, TResponseInputItem from ..memory.resumable_session import ( + Plan, ResumableSession, ResumableSessionError, _ResumableSessionBinding, @@ -30,6 +31,7 @@ class ResumableRun: def __init__(self, source: ResumableSession | None) -> None: self.session_id = source.session_id if source is not None else "" self.session_settings: SessionSettings | None = None + self.plan: Plan | None = None self._source = source self._items: list[TResponseInputItem] = [] @@ -58,12 +60,14 @@ async def finish(self, result: RunResult | RunResultStreaming) -> None: state = result.to_state() if result.interruptions else None if state is not None: state._resumable_binding = "detached" - result._resumable_binding = await self._source._save_checkpoint(self._items, state) + result._resumable_binding = await self._source._save_checkpoint( + self._items, state, codex_checklist=self.plan + ) async def finish_budget_stop(self) -> None: """Keep completed work when the next request was refused before dispatch.""" assert self._source is not None - await self._source._save_checkpoint(self._items, None) + await self._source._save_checkpoint(self._items, None, codex_checklist=self.plan) def configure_stream(self, result: RunResultStreaming) -> None: queue = _CheckpointEventQueue() diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index cbce2f8feb..2a8efabf52 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -23,6 +23,7 @@ from openai.types.responses.response_output_item import ResponseOutputItem from openai.types.responses.response_prompt_param import ResponsePromptParam +from .._plan import validate_plan_session from .._redaction import ( current_redactor, redact_model_input, @@ -2552,6 +2553,7 @@ async def raise_if_input_guardrail_tripwire_known() -> None: all_tools, model_tools, prepared_tools, omitted = await prepare_declarations( all_tools, bindings, context_wrapper, run_config ) + validate_plan_session(all_tools) if agent_span is not None: agent_span.span_data.handoffs = [handoff.agent_name for handoff in handoffs] agent_span.span_data.tools = [ @@ -2742,7 +2744,7 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: context_wrapper, hooks, run_config.tool_execution, - resumable=isinstance(session, ResumableRun), + resumable=session if isinstance(session, ResumableRun) else None, ), ) ) @@ -3000,6 +3002,7 @@ async def run_single_turn( all_tools, model_tools, prepared_tools, omitted = await prepare_declarations( all_tools, bindings, context_wrapper, run_config ) + validate_plan_session(all_tools) if agent_span is not None: agent_span.span_data.handoffs = [handoff.agent_name for handoff in handoffs] agent_span.span_data.tools = [ @@ -3211,7 +3214,7 @@ async def rewind_model_request() -> None: context_wrapper, hooks, run_config.tool_execution, - resumable=isinstance(session, ResumableRun), + resumable=session if isinstance(session, ResumableRun) else None, ), ), record_failed_attempt_usage_on_error(context_wrapper.usage) as reported_usage, diff --git a/src/agents/run_internal/tool_execution.py b/src/agents/run_internal/tool_execution.py index 1857524441..cb3e7ec1fb 100644 --- a/src/agents/run_internal/tool_execution.py +++ b/src/agents/run_internal/tool_execution.py @@ -24,6 +24,7 @@ from .. import _debug from .._function_tool_arguments import FunctionToolApproval +from .._plan import is_plan_tool from .._redaction import hook_payload_diagnostics, redact_payload, require_clean from .._tool_identity import ( FunctionToolLookupKey, @@ -66,6 +67,7 @@ ToolCallOutputItem, ) from ..logger import log_tool_action_error as _log_tool_action_error, logger +from ..memory.resumable_session import Plan from ..model_settings import ModelSettings from ..run_config import RunConfig, ToolErrorFormatterArgs from ..run_context import RunContextWrapper @@ -113,6 +115,7 @@ from ..util._tool_errors import get_trace_tool_error from ._asyncio_progress import get_function_tool_task_progress_deadline from .agent_bindings import AgentBindings, bind_public_agent +from .agent_tool_configuration import current_plan_session from .approvals import append_approval_error_output from .items import ( REJECTION_MESSAGE, @@ -2140,6 +2143,8 @@ async def _invoke_tool_and_run_post_invoke( record = self.context_wrapper._tool_invocations.get(tool_call.call_id) if record is not None and record.declaration is not None: await record.declaration.check(self.context_wrapper, self.config) + plan_session = current_plan_session() if is_plan_tool(func_tool) else None + pending_plan: list[Plan] = [] bypass_output_schema = False try: with hook_payload_diagnostics( @@ -2157,6 +2162,8 @@ async def _invoke_tool_and_run_post_invoke( if tool_context._edit_text is not None else _invoke_function_tool_with_metadata ) + if plan_session is not None: + tool_context._propose_plan = pending_plan.append invocation_result = await invoke( function_tool=func_tool, context=tool_context, @@ -2196,6 +2203,9 @@ async def _invoke_tool_and_run_post_invoke( ) ) real_result = result + pending_plan.clear() + finally: + tool_context._propose_plan = None nested_run_result = peek_agent_tool_run_result( task_state.tool_run.tool_call, @@ -2287,6 +2297,13 @@ async def _invoke_tool_and_run_post_invoke( await run_tool_end_hooks( self.hooks, agent_hooks, tool_context, self.public_agent, func_tool, final_result ) + if ( + pending_plan + and not bypass_output_schema + and plan_session is not None + and current_plan_session() is plan_session + ): + plan_session.plan = pending_plan[0] return final_result async def _await_invoke_task( diff --git a/src/agents/tool_context.py b/src/agents/tool_context.py index 59e4860434..dc1dddd7ff 100644 --- a/src/agents/tool_context.py +++ b/src/agents/tool_context.py @@ -24,6 +24,7 @@ from ._function_tool_arguments import PreparedFunctionArguments from .agent import AgentBase from .items import ToolApprovalItem, TResponseInputItem + from .memory.resumable_session import Plan from .run_config import RunConfig from .run_context import _ApprovalKey, _ApprovalRecord @@ -121,6 +122,7 @@ def __init__( self.run_config = None # Internal adapter hook used to attach SDK-only custom data to the emitted output item. self._edit_text: Callable[[tuple[str, ...]], Awaitable[tuple[str, ...]]] | None = None + self._propose_plan: Callable[[Plan], None] | None = None self._custom_data: dict[str, Any] | None = None self._function_tool_arguments: PreparedFunctionArguments | None = None diff --git a/tests/memory/test_resumable_session.py b/tests/memory/test_resumable_session.py index 5df7882d3f..07caf3a2c3 100644 --- a/tests/memory/test_resumable_session.py +++ b/tests/memory/test_resumable_session.py @@ -994,3 +994,198 @@ async def run(worker: Agent[Any], input: Any, **options: Any) -> RunResult | Run assert json.loads(calls[0]["arguments"]) == {"text": "reviewed text"} assert outputs[0]["output"] == ("public receipt" if approved else "Rejected reviewed text") assert "private receipt" not in json.dumps(history) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_plan_replacement_redaction_and_clear(streamed): + from agents import Plan, PlanStep, update_plan + + store = MemoryStore() + session = await ResumableSession.create(store) + assert session.plan is None + model = ScriptedModel( + [ + [get_function_tool_call("update_plan", '{"steps":[]}', "first")], + [ + get_function_tool_call( + "update_plan", + '{"steps":[{"text":"private","status":"pending"}],"explanation":"private"}', + "second", + ) + ], + [get_text_message("done")], + [get_text_message("no change")], + [get_function_tool_call("update_plan", '{"steps":[]}', "clear")], + [get_text_message("cleared")], + ] + ) + config = RunConfig( + tracing_disabled=True, redact_text=lambda s: s.replace("private", "[hidden]") + ) + agent = Agent(name="Planner", model=model, tools=[update_plan]) + await run_agent(agent, "begin", session, streamed, run_config=config) + session = await ResumableSession.resume(store, session.session_id) + saved = session.plan + assert saved == Plan( + tool_call_id="second", + explanation="[hidden]", + steps=(PlanStep(text="[hidden]", status="pending"),), + ) + assert "private" not in store.records[session.session_id] + assert "[hidden]" not in repr(saved) + assert store.checkpoint(session.session_id)["codex_checklist"] == { + "tool_call_id": "second", + "explanation": "[hidden]", + "plan": [{"step": "[hidden]", "status": "pending"}], + } + await run_agent(agent, "leave unchanged", session, streamed, run_config=config) + assert session.plan == saved + await run_agent(agent, "clear", session, streamed, run_config=config) + assert session.plan == Plan(steps=(), tool_call_id="clear") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("approved", [False, True]) +async def test_plan_only_changes_after_approval(streamed, approved): + from dataclasses import replace + + from agents import Plan, update_plan + + store = MemoryStore() + session = await ResumableSession.create(store) + model = ScriptedModel( + [ + [get_function_tool_call("update_plan", '{"steps":[],"explanation":"private"}', "edit")], + [get_text_message("done")], + ] + ) + agent = Agent(name="Planner", model=model, tools=[replace(update_plan, needs_approval=True)]) + config = RunConfig( + tracing_disabled=True, redact_text=lambda s: s.replace("private", "[hidden]") + ) + await run_agent(agent, "begin", session, streamed, run_config=config) + assert "private" not in store.records[session.session_id] + assert "[hidden]" in store.checkpoint(session.session_id)["run_state"] + session = await ResumableSession.resume(store, session.session_id) + assert session.plan is None + state = await session.load_state(agent) + (pending,) = state.get_interruptions() + if approved: + state.approve(pending) + else: + state.reject(pending) + await run_agent(agent, state, None, streamed, run_config=config) + assert session.plan == ( + Plan(steps=(), tool_call_id="edit", explanation="[hidden]") if approved else None + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_plan_requires_own_resumable_session(streamed): + from agents import update_plan + + model = ScriptedModel([[get_function_tool_call("update_plan", '{"steps":[]}', "child")]]) + child = Agent(name="child", tools=[update_plan], model=model) + with pytest.raises(UserError, match="ResumableSession"): + await run_agent(child, "plan", None, streamed) + assert not model.calls + + session = await ResumableSession.create(MemoryStore()) + parent = Agent( + name="parent", + tools=[child.as_tool(tool_name="ask", tool_description="Ask")], + model=ScriptedModel( + [ + [get_function_tool_call("ask", '{"input":"plan"}', "ask")], + [get_text_message("done")], + ] + ), + ) + await run_agent(parent, "delegate", session, streamed) + assert not model.calls and session.plan is None + + +@pytest.mark.asyncio +async def test_an_unrelated_tool_name_cannot_update_the_plan(): + @tool + def update_plan() -> str: + return "Plan updated." + + session = await ResumableSession.create(MemoryStore()) + model = ScriptedModel([[get_function_tool_call("update_plan")], [get_text_message("done")]]) + agent = Agent(name="Worker", model=model, tools=[update_plan]) + await run_agent(agent, "begin", session, False) + assert session.plan is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("deserialize", [False, True]) +async def test_concurrent_plan_approvals_with_shared_context(streamed, deserialize): + from dataclasses import replace + + from agents import Plan, RunContextWrapper, update_plan + + store = MemoryStore() + shared = RunContextWrapper(context={}) + paused = [] + for name in ("first", "second"): + session = await ResumableSession.create(store) + agent = Agent( + name=name, + tools=[replace(update_plan, needs_approval=True)], + model=ScriptedModel( + [ + [get_function_tool_call("update_plan", '{"steps":[]}', name)], + [get_text_message("done")], + ] + ), + ) + await Runner.run(agent, "begin", context={}, session=session, run_config=CONFIG) + state = await session.load_state( + agent, + context_override=None if deserialize else shared, + context_deserializer=(lambda _: shared) if deserialize else None, + ) + paused.append((agent, state, session)) + for _, state, _ in paused: + state.approve(state.get_interruptions()[0]) + results = await asyncio.gather(*(run_agent(a, s, None, streamed) for a, s, _ in paused)) + for result, (agent, _, session) in zip(results, paused, strict=True): + assert result.context_wrapper.context is shared.context + saved = await ResumableSession.resume(store, session.session_id) + assert saved.plan == Plan(tool_call_id=agent.name, steps=()) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_rejected_tool_output_preserves_previous_plan(streamed): + from dataclasses import replace + + from agents import Plan, update_plan + from agents.tool_guardrails import ToolGuardrailFunctionOutput, tool_output_guardrail + + @tool_output_guardrail + def reject(data): + return ToolGuardrailFunctionOutput.reject_content("Rejected") + + store = MemoryStore() + session = await ResumableSession.create(store) + for updater, name in [ + (update_plan, "saved"), + (replace(update_plan, tool_output_guardrails=[reject]), "blocked"), + ]: + model = ScriptedModel( + [ + [get_function_tool_call("update_plan", '{"steps":[]}', name)], + [get_text_message("done")], + ] + ) + await run_agent( + Agent(name="Planner", model=model, tools=[updater]), "plan", session, streamed + ) + reopened = await ResumableSession.resume(store, session.session_id) + assert reopened.plan == Plan(tool_call_id="saved", steps=()) diff --git a/tests/memory/test_resumable_session_store.py b/tests/memory/test_resumable_session_store.py index 8d6f1bdf14..2833682a03 100644 --- a/tests/memory/test_resumable_session_store.py +++ b/tests/memory/test_resumable_session_store.py @@ -59,7 +59,7 @@ async def test_resume_does_not_create_a_missing_id() -> None: [ ("not-json synthetic-private-state-detail", "malformed"), ("[]", "malformed"), - ('{"version":3}', "incompatible"), + ('{"version":5}', "incompatible"), ('{"version":1}', "malformed"), ( json.dumps( diff --git a/tests/models/test_codex_provider.py b/tests/models/test_codex_provider.py index d1452ea097..513034ab77 100644 --- a/tests/models/test_codex_provider.py +++ b/tests/models/test_codex_provider.py @@ -1,4 +1,5 @@ import asyncio +import inspect import json import sys from collections import deque @@ -2250,3 +2251,212 @@ async def test_native_content_requires_explicit_policy_and_correlates_final_outp assert execution.span_data.input is execution.span_data.output is None assert execution.ended_at is not None and request.ended_at is not None assert execution.ended_at < request.ended_at + + +class PlanThread(FakeThread): + thread_id = "native_thread" + + async def next_event(self): + encoded = await super().next_event() + if encoded is None: + return None + event = json.loads(encoded) + event["id"] = event["msg"].pop("event_id", event["id"]) + return json.dumps(event) + + +def test_checklist_constructors_show_python_field_names(): + from agents.memory.resumable_session import Plan, PlanStep + + step = PlanStep(text="Review", status="pending") + checklist = Plan(thread_id="thread", turn_id="turn", steps=(step,)) + assert checklist.steps[0].text == "Review" + assert step.model_dump() == {"text": "Review", "status": "pending"} + assert json.loads(checklist.model_dump_json())["steps"] == [step.model_dump()] + assert checklist.model_dump(by_alias=True) == checklist.model_dump() + for mode in ("validation", "serialization"): + schema = Plan.model_json_schema(mode=mode) + assert "steps" in schema["properties"] + assert "text" in schema["$defs"]["PlanStep"]["properties"] + assert "thread" not in repr(checklist) and "turn" not in repr(checklist) + assert "text" in inspect.signature(PlanStep).parameters + assert "steps" in inspect.signature(Plan).parameters + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_checklist_is_latest_owned_update_in_idle_checkpoint(tmp_path, threads, streamed): + from agents import ResumableSession, ResumableSessionError + from tests.memory.test_resumable_session import MemoryStore + + queue, _ = threads + store = MemoryStore() + session = await ResumableSession.create(store) + agent = Agent(name="Planner") + cfg = config(tmp_path) + assert session.plan is None + clear = {"type": "plan_update", "plan": []} + revision = { + "type": "plan_update", + "explanation": "Two passes", + "plan": [ + {"step": "Review", "status": "completed"}, + {"step": "Review", "status": "pending"}, + ], + } + + async def turn(events): + queue.append(PlanThread(events=events)) + if streamed: + result = Runner.run_streamed(agent, "Go", session=session, run_config=cfg) + async for _ in result.stream_events(): + pass + else: + await Runner.run(agent, "Go", session=session, run_config=cfg) + + await turn([clear, revision, dict(clear, event_id=""), dict(clear, event_id="other")]) + session = await ResumableSession.resume(store, session.session_id) + saved = session.plan + assert saved is not None + assert (saved.thread_id, saved.turn_id, saved.explanation) == ( + "native_thread", + "turn_1", + "Two passes", + ) + assert [(s.text, s.status) for s in saved.steps] == [ + ("Review", "completed"), + ("Review", "pending"), + ] + record = store.checkpoint(session.session_id) + assert record["version"] == 3 + assert record["codex_checklist"]["plan"] == revision["plan"] + assert "tool_call_id" not in record["codex_checklist"] + assert type(saved).model_validate_json(json.dumps(record["codex_checklist"])) == saved + assert type(saved).model_validate_json(saved.model_dump_json()) == saved + assert "Review" not in repr(saved) and "Two passes" not in repr(saved) + record["version"] = 1 # Earlier writers stored checklists without a distinct version. + store.records[session.session_id] = json.dumps(record) + session = await ResumableSession.resume(store, session.session_id) + await turn([]) + assert store.checkpoint(session.session_id)["version"] == 3 + assert session.plan == saved + await turn([clear]) + assert store.checkpoint(session.session_id)["version"] == 3 + cleared = session.plan + assert cleared is not None and cleared.steps == () and cleared.explanation is None + + store.fail_checkpoint = True + with pytest.raises(ResumableSessionError): + await turn([revision]) + with pytest.raises(ResumableSessionError) as error: + _ = session.plan + assert error.value.reason == "active" + assert store.checkpoint(session.session_id)["codex_checklist"]["plan"] == [] + + +async def test_checklist_survives_approval_and_excludes_nested_updates(tmp_path, threads): + from agents import ResumableSession, ResumableSessionError + from tests.memory.test_resumable_session import MemoryStore + + queue, _ = threads + cfg = config(tmp_path) + worker = Agent(name="Worker") + manager = Agent( + name="Manager", + tools=[worker.as_tool("ask", "Ask worker", run_config=cfg, needs_approval=True)], + tool_use_behavior="stop_on_first_tool", + ) + queue.append( + PlanThread( + events=[ + {"type": "plan_update", "plan": [{"step": "Consult", "status": "in_progress"}]} + ], + call={"callId": "ask1", "tool": "ask", "arguments": {"input": "Check"}}, + ) + ) + store = MemoryStore() + session = await ResumableSession.create(store) + await Runner.run(manager, "Go", session=session, run_config=cfg) + resumed = await ResumableSession.resume(store, session.session_id) + assert resumed.is_paused + saved = resumed.plan + assert saved is not None and saved.steps[0].text == "Consult" + state = await resumed.load_state(manager) + state.approve(state.get_interruptions()[0]) + queue.append(PlanThread(events=[{"type": "plan_update", "plan": []}])) + result = await Runner.run(manager, state, run_config=cfg) + assert result.final_output == "A Codex response" + assert resumed.plan == saved + + record = store.checkpoint(session.session_id) + record["codex_checklist"]["plan"][0]["status"] = "blocked" + store.records[session.session_id] = json.dumps(record) + with pytest.raises(ResumableSessionError) as error: + await ResumableSession.resume(store, session.session_id) + assert error.value.reason == "malformed" + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_checklist_redacts_display_text_before_saving(tmp_path, threads, streamed): + from agents import ResumableSession + from tests.memory.test_resumable_session import MemoryStore + + store = MemoryStore() + session = await ResumableSession.create(store) + agent = Agent(name="Planner") + cfg = config(tmp_path) + marker = "PRIVATE_PLAN_TEXT" + cfg.redact_text = lambda text: text.replace(marker, "[hidden]") + threads[0].append( + PlanThread( + events=[ + { + "type": "plan_update", + "explanation": marker, + "plan": [{"step": f"Check {marker}", "status": "pending"}], + } + ] + ) + ) + if streamed: + result = Runner.run_streamed(agent, "Go", session=session, run_config=cfg) + async for event in result.stream_events(): + assert event.type != "raw_response_event" and marker not in repr(event) + else: + await Runner.run(agent, "Go", session=session, run_config=cfg) + assert marker not in store.records[session.session_id] + assert store.checkpoint(session.session_id)["version"] == 4 + reopened = await ResumableSession.resume(store, session.session_id) + saved = reopened.plan + assert saved is not None and saved.explanation == "[hidden]" + assert [(s.text, s.status) for s in saved.steps] == [("Check [hidden]", "pending")] + + with pytest.raises(UserError, match="redact_text"): + await Runner.run(agent, "Next", session=reopened, run_config=config(tmp_path)) + record = store.checkpoint(session.session_id) + assert record["status"] == "ready" + record["version"] = 2 + store.records[session.session_id] = json.dumps(record) + reopened = await ResumableSession.resume(store, session.session_id) + threads[0].append(PlanThread(events=[])) + await Runner.run(agent, "Next", session=reopened, run_config=cfg) + assert store.checkpoint(session.session_id)["version"] == 4 + assert reopened.plan == saved + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("namespaced", [False, True]) +async def test_sdk_plan_tool_conflict_precedes_claim(tmp_path, streamed, namespaced): + from agents import ResumableSession, tool_namespace, update_plan + from tests.memory.test_resumable_session import MemoryStore, run_agent + + store = MemoryStore() + session = await ResumableSession.create(store) + tools = ( + tool_namespace(name="group", description="Tools", tools=[update_plan]) + if namespaced + else [update_plan] + ) + agent = Agent(name="Planner", tools=[*tools]) + with pytest.raises(UserError, match="tools.update_plan.enabled"): + await run_agent(agent, "plan", session, streamed, run_config=config(tmp_path)) + assert (await ResumableSession.resume(store, session.session_id)).plan is None diff --git a/tests/test_run_budget.py b/tests/test_run_budget.py index 85b8f300e9..526ee6f135 100644 --- a/tests/test_run_budget.py +++ b/tests/test_run_budget.py @@ -236,6 +236,29 @@ def record() -> str: assert effects == [1] +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_budget_stop_checkpoints_staged_checklist_with_completed_tool(streamed): + from agents import Plan, PlanStep, update_plan + + store = MemoryStore() + session = await ResumableSession.create(store) + call = get_function_tool_call( + "update_plan", '{"steps":[{"text":"Record","status":"in_progress"}]}', "record" + ) + model = ScriptedModel([step(call)]) + agent = Agent(name="root", model=model, tools=[update_plan]) + with pytest.raises(RunBudgetError): + await run(agent, RunBudget(max_model_calls=1), streamed, session=session) + assert len(model.calls) == 1 + restored = await ResumableSession.resume(store, session.session_id) + assert store.checkpoint(session.session_id)["history"][-1]["call_id"] == "record" + assert store.checkpoint(session.session_id)["history"][-1]["output"] == "Plan updated." + assert restored.plan == Plan( + tool_call_id="record", steps=(PlanStep(text="Record", status="in_progress"),) + ) + + @pytest.mark.asyncio @pytest.mark.parametrize("streamed", [False, True]) async def test_nested_tool_has_independent_budget_and_usage(streamed):