Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions native/codex/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
5 changes: 5 additions & 0 deletions src/agents/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from openai import AsyncOpenAI

from . import _config, sandbox
from ._plan import update_plan
from .agent import (
Agent,
AgentBase,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -489,6 +491,9 @@ def enable_verbose_stdout_logging() -> None:
"ItemHelpers",
"RunHooks",
"AgentHooks",
"Plan",
"PlanStep",
"update_plan",
"ResumableSession",
"ResumableSessionError",
"ResumableSessionStore",
Expand Down
32 changes: 32 additions & 0 deletions src/agents/_plan.py
Original file line number Diff line number Diff line change
@@ -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)
119 changes: 114 additions & 5 deletions src/agents/memory/resumable_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
from uuid import uuid4

from pydantic import (
AliasChoices,
BaseModel,
ConfigDict,
Field,
TypeAdapter,
ValidationError,
field_serializer,
field_validator,
model_validator,
)
Expand Down Expand Up @@ -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
Expand All @@ -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
):
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -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")
Expand All @@ -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:
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/agents/models/_run_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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(
Expand Down
51 changes: 43 additions & 8 deletions src/agents/models/codex.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Loading
Loading