From f75d2652b8d5c3cb7ff6fe252dfbd8f486c42d73 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Sat, 21 Nov 2026 06:10:14 -0800 Subject: [PATCH 1/3] feat: retain native checklists in resumable sessions --- native/codex/src/lib.rs | 5 + src/agents/memory/resumable_session.py | 52 ++++++++- src/agents/models/_run_context.py | 2 + src/agents/models/codex.py | 18 ++- src/agents/run_internal/resumable_session.py | 6 +- src/agents/run_internal/run_loop.py | 18 ++- tests/models/test_codex_provider.py | 112 +++++++++++++++++++ 7 files changed, 207 insertions(+), 6 deletions(-) diff --git a/native/codex/src/lib.rs b/native/codex/src/lib.rs index f6082ddb38..9729584283 100644 --- a/native/codex/src/lib.rs +++ b/native/codex/src/lib.rs @@ -386,6 +386,11 @@ struct Thread { #[pymethods] impl Thread { + #[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/memory/resumable_session.py b/src/agents/memory/resumable_session.py index a9f1314edd..8e2093a27d 100644 --- a/src/agents/memory/resumable_session.py +++ b/src/agents/memory/resumable_session.py @@ -106,6 +106,26 @@ def _history_adapter() -> TypeAdapter[list[TResponseInputItem]]: return TypeAdapter(list[TResponseInputItem]) +class CodexChecklistStep(BaseModel): + """One entry in the native checklist, in the order supplied by Codex.""" + + model_config = ConfigDict(extra="forbid", frozen=True, strict=True) + + step: str + status: Literal["pending", "in_progress", "completed"] + + +class CodexChecklist(BaseModel): + """The most recent native checklist and the ephemeral thread and turn that issued it.""" + + model_config = ConfigDict(extra="forbid", frozen=True, strict=True) + + thread_id: str = Field(min_length=1) + turn_id: str = Field(min_length=1) + plan: tuple[CodexChecklistStep, ...] + explanation: str | None = None + + class _Checkpoint(BaseModel): model_config = ConfigDict(extra="forbid", strict=True, frozen=True) @@ -114,6 +134,7 @@ class _Checkpoint(BaseModel): status: Literal["ready", "paused", "active"] history: list[Any] run_state: str | None + codex_checklist: CodexChecklist | None = Field(default=None, exclude_if=lambda v: v is None) @field_validator("history") @classmethod @@ -199,6 +220,26 @@ def __init__( self._checkpoint = _checkpoint self._serialized = _serialized + @property + def codex_checklist(self) -> CodexChecklist | None: + """Read the latest accepted native plan in this idle checkpoint without inference. + + Use `CodexProvider(config_overrides=["tools.update_plan.enabled=true"])` + with this session. After the run finishes or pauses for approval, read + `session.codex_checklist`. To reopen, use + `session = await ResumableSession.resume(store, session_id)` first. + + Each accepted update replaces the whole list. An empty plan clears it. + Invalid tool arguments leave it unchanged. None means no saved plan. + History-only sessions cannot store this snapshot. Nested agent tools + do not update their parent session. Use the plan for display only. It + cannot authorize tools or resume a native thread. Older SDK versions + cannot open checkpoints that contain a checklist. + """ + 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.""" @@ -310,7 +351,11 @@ async def _begin_run(self, input: Any) -> None: 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: CodexChecklist | None = None, ) -> _ResumableSessionBinding: if self._checkpoint.status != "active": raise ResumableSessionError("conflict") @@ -321,6 +366,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: diff --git a/src/agents/models/_run_context.py b/src/agents/models/_run_context.py index ba57e3f19d..0b8a055334 100644 --- a/src/agents/models/_run_context.py +++ b/src/agents/models/_run_context.py @@ -11,6 +11,7 @@ from ..lifecycle import RunHooks from ..run_config import ToolExecutionConfig from ..run_context import RunContextWrapper + from ..run_internal.resumable_session import ResumableRun @dataclass(frozen=True) @@ -19,6 +20,7 @@ class ModelToolHooks: context: RunContextWrapper[Any] lifecycle: RunHooks[Any] settings: ToolExecutionConfig | None + checkpoint: 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 ca13c586db..0c00a1a8b8 100644 --- a/src/agents/models/codex.py +++ b/src/agents/models/codex.py @@ -41,6 +41,7 @@ from ..exceptions import UserError from ..handoffs import Handoff from ..items import ModelResponse, TResponseInputItem, TResponseStreamEvent +from ..memory.resumable_session import CodexChecklist from ..model_settings import ModelSettings from ..retry import ModelRetryAdvice, ModelRetryAdviceRequest from ..tool import ApplyPatchTool, ShellTool, Tool, WebSearchTool @@ -274,6 +275,8 @@ async def stream_response( ) provider = self._provider bindings = get_model_tool_hooks() + checkpoint = bindings.checkpoint if bindings is not None else None + checklist = None tool_execution = bindings.settings if bindings is not None else None classic_preparation = ( tool_execution is not None @@ -425,6 +428,16 @@ async def interrupt_when_ready() -> None: ) if event.get("id") not in ("", turn_id): 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: + checklist = CodexChecklist( + thread_id=thread.thread_id, + turn_id=turn_id, + explanation=message.get("explanation"), + plan=tuple(message["plan"]), + ) + continue if kind == "dynamic_tool_call_request": if message.get("turnId") != turn_id: continue @@ -754,9 +767,12 @@ async def interrupt_when_ready() -> None: ) if raw_usage is not None: _attach_raw_usage_snapshot(response, raw_usage) - yield ResponseCompletedEvent( + completed = ResponseCompletedEvent( response=response, sequence_number=sequence, type="response.completed" ) + if checkpoint is not None and checklist is not None: + checkpoint.codex_checklist = checklist + yield completed def _usage(total: dict[str, Any]) -> ResponseUsage: diff --git a/src/agents/run_internal/resumable_session.py b/src/agents/run_internal/resumable_session.py index a55fba5c31..ac84754338 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 ( + CodexChecklist, ResumableSession, ResumableSessionError, _ResumableSessionBinding, @@ -28,6 +29,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.codex_checklist: CodexChecklist | None = None self._source = source self._items: list[TResponseInputItem] = [] @@ -42,7 +44,9 @@ 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.codex_checklist + ) 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 659642845a..98a16db114 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -164,7 +164,7 @@ ) from .oai_conversation import OpenAIServerConversationTracker from .prompt_cache_key import PromptCacheKeyResolver, model_settings_with_prompt_cache_key -from .resumable_session import checkpoint_streamed_result +from .resumable_session import ResumableRun, checkpoint_streamed_result from .run_steps import ( NextStepFinalOutput, NextStepHandoff, @@ -2692,7 +2692,13 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: model_run_context_stream( retry_stream, tool_use_tracker, - ModelToolHooks(public_agent, context_wrapper, hooks, run_config.tool_execution), + ModelToolHooks( + public_agent, + context_wrapper, + hooks, + run_config.tool_execution, + checkpoint=session if isinstance(session, ResumableRun) else None, + ), ) ) as model_events: async for event in model_events: @@ -3117,7 +3123,13 @@ async def rewind_model_request() -> None: with ( model_run_context( tool_use_tracker, - ModelToolHooks(public_agent, context_wrapper, hooks, run_config.tool_execution), + ModelToolHooks( + public_agent, + context_wrapper, + hooks, + run_config.tool_execution, + checkpoint=session if isinstance(session, ResumableRun) else None, + ), ), record_failed_attempt_usage_on_error(context_wrapper.usage) as reported_usage, ): diff --git a/tests/models/test_codex_provider.py b/tests/models/test_codex_provider.py index 43e2f6ee89..8a42382c8c 100644 --- a/tests/models/test_codex_provider.py +++ b/tests/models/test_codex_provider.py @@ -1916,3 +1916,115 @@ async def events(self): "value": "prepared", "environment_id": "workspace", } + + +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) + + +@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.codex_checklist 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.codex_checklist + assert saved is not None + assert (saved.thread_id, saved.turn_id, saved.explanation) == ( + "native_thread", + "turn_1", + "Two passes", + ) + assert [(s.step, s.status) for s in saved.plan] == [ + ("Review", "completed"), + ("Review", "pending"), + ] + await turn([]) + assert session.codex_checklist == saved + await turn([clear]) + cleared = session.codex_checklist + assert cleared is not None and cleared.plan == () and cleared.explanation is None + + store.fail_checkpoint = True + with pytest.raises(ResumableSessionError): + await turn([revision]) + with pytest.raises(ResumableSessionError) as error: + _ = session.codex_checklist + 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.codex_checklist + assert saved is not None and saved.plan[0].step == "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.codex_checklist == 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" From 12906f0ee88b363effa660abd7ce916c1e75eebb Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Mon, 23 Nov 2026 21:42:25 -0800 Subject: [PATCH 2/3] Version checklist-bearing session records separately --- src/agents/memory/resumable_session.py | 12 +++++++++-- tests/memory/test_resumable_session_store.py | 2 +- tests/models/test_codex_provider.py | 21 +++++++++++++++++++- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/agents/memory/resumable_session.py b/src/agents/memory/resumable_session.py index afff329eeb..db02685475 100644 --- a/src/agents/memory/resumable_session.py +++ b/src/agents/memory/resumable_session.py @@ -132,7 +132,8 @@ class CodexChecklist(BaseModel): 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] @@ -149,6 +150,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 ): @@ -445,7 +448,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/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 b878f500ef..7744cc5108 100644 --- a/tests/models/test_codex_provider.py +++ b/tests/models/test_codex_provider.py @@ -2298,9 +2298,16 @@ async def turn(events): ("Review", "completed"), ("Review", "pending"), ] + record = store.checkpoint(session.session_id) + assert record["version"] == 3 + 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.codex_checklist == saved await turn([clear]) + assert store.checkpoint(session.session_id)["version"] == 3 cleared = session.codex_checklist assert cleared is not None and cleared.plan == () and cleared.explanation is None @@ -2384,8 +2391,20 @@ async def test_checklist_redacts_display_text_before_saving(tmp_path, threads, s 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"] == 2 + assert store.checkpoint(session.session_id)["version"] == 4 reopened = await ResumableSession.resume(store, session.session_id) saved = reopened.codex_checklist assert saved is not None and saved.explanation == "[hidden]" assert [(s.step, s.status) for s in saved.plan] == [("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.codex_checklist == saved From e6167cecf399183edee2a1fe3e17852ea43d9411 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Tue, 24 Nov 2026 13:24:44 -0800 Subject: [PATCH 3/3] Preserve accepted checklist updates when saving a budget stop --- src/agents/run_internal/resumable_session.py | 2 +- tests/test_run_budget.py | 37 ++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/agents/run_internal/resumable_session.py b/src/agents/run_internal/resumable_session.py index 9491f485e7..91aa3f8ea5 100644 --- a/src/agents/run_internal/resumable_session.py +++ b/src/agents/run_internal/resumable_session.py @@ -67,7 +67,7 @@ async def finish(self, result: RunResult | RunResultStreaming) -> None: 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.codex_checklist) def configure_stream(self, result: RunResultStreaming) -> None: queue = _CheckpointEventQueue() diff --git a/tests/test_run_budget.py b/tests/test_run_budget.py index 85b8f300e9..f2f16fe64c 100644 --- a/tests/test_run_budget.py +++ b/tests/test_run_budget.py @@ -236,6 +236,43 @@ 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.memory.resumable_session import CodexChecklist, CodexChecklistStep + from agents.models._run_context import get_model_tool_hooks + + store = MemoryStore() + session = await ResumableSession.create(store) + checklist = CodexChecklist( + thread_id="thread", + turn_id="turn", + steps=(CodexChecklistStep(text="Record", status="in_progress"),), + ) + effects = [] + + @tool + def record() -> str: + effects.append(1) + return "saved" + + def respond(_): + # Simulate a staged update. RunBudget rejects native Codex sampling. + hooks = get_model_tool_hooks() + assert hooks is not None and hooks.resumable is not None + hooks.resumable.codex_checklist = checklist + return step(get_function_tool_call("record")) + + model = ScriptedModel([ModelStep.respond(respond)]) + agent = Agent(name="root", model=model, tools=[record]) + with pytest.raises(RunBudgetError): + await run(agent, RunBudget(max_model_calls=1), streamed, session=session) + assert effects == [1] and len(model.calls) == 1 + restored = await ResumableSession.resume(store, session.session_id) + assert store.checkpoint(session.session_id)["history"][-1]["output"] == "saved" + assert restored.codex_checklist == checklist + + @pytest.mark.asyncio @pytest.mark.parametrize("streamed", [False, True]) async def test_nested_tool_has_independent_budget_and_usage(streamed):