Skip to content

Session

Session

One live conversation. Open with async with agent.session() as session.

Source code in src/openai_agents/codex/session.py
class Session:
    """One live conversation. Open with `async with agent.session() as session`."""

    def __init__(
        self,
        agent: Agent | None,
        *,
        environment: Environment | EllipsisType = ...,
        workspace: str | PathLike[str] | None = None,
        sandbox: Sandbox | None = None,
        state: ConversationState | None = None,
        storage: SessionStorage | None = None,
        session_id: str | None = None,
    ) -> None:
        self._agent = agent
        if session_id is not None:
            _validate_id(session_id)
            if storage is None or state is not None:
                raise ValueError("Resume by session_id requires storage and excludes state")
        self._storage = storage
        self._resuming = session_id is not None
        self._id = session_id
        if storage is not None and session_id is None:
            self._id = f"sess_{uuid4().hex}"
        self._environment = _resolve_environment(environment, workspace, sandbox)
        self._state = ConversationState(deepcopy(state)) if state is not None else None
        self._engine = Engine()
        self._callbacks: _Callbacks | None = None
        self._lifecycle = asyncio.Lock()
        self._entered = False
        self._closing: asyncio.Task[None] | None = None
        self._turn: _Turn | None = None

    @classmethod
    def resume(
        cls,
        session_id: str,
        *,
        storage: SessionStorage,
        environment: Environment | EllipsisType = ...,
    ) -> Session:
        """Resume without an executor. Use agent.session() for current tools and permissions."""
        _validate_id(session_id)
        return cls(None, storage=storage, session_id=session_id, environment=environment)

    def _bind(self) -> Agent:
        if self._resuming and self._state is not None and "sdk_settings" in self._state:
            from openai_agents.codex._settings import SessionSettings

            settings = SessionSettings.read(self._state["sdk_settings"])
            if self._environment is ...:
                settings.require_no_executor()
                self._environment = None
            agent = settings.bind(self._agent)
            if self._environment is not None and self._agent is None:
                raise RunError(
                    "Supply an agent with agent.session() to resume with an executor",
                    code="session_bindings_required",
                )
            return agent
        if self._agent is None:
            raise RunError("Supply an agent with agent.session()", code="session_bindings_required")
        if self._resuming and self._environment is ...:
            raise RunError(
                "Supply environment= to resume this session", code="session_bindings_required"
            )
        return self._agent

    async def __aenter__(self) -> Session:
        async with self._lifecycle:
            if self._entered or self._closing is not None:
                raise EngineError("A session can only be opened once")
            self._entered = True
            await self._engine.__aenter__()
            try:
                async with self._lock() as record:
                    if self._resuming:
                        if record.state is None:
                            raise SessionNotFound(self.id)
                        self._state = record.state
                    elif self._storage is not None and record.state is not None:
                        raise EngineError(f"Session {self.id!r} already exists")
                    agent = self._bind()
                    callbacks = await self._engine._open_session(
                        agent,
                        self._environment,
                        self._state,
                        save_settings=self._storage is not None,
                    )
                    if self._storage is not None:
                        if self._state is None:
                            self._state = ConversationState(
                                await self._engine._request("prepare", {})
                            )
                        self._state["session_id"] = self.id
                        if not self._resuming:
                            self._state["sdk_settings"] = deepcopy(self._engine._settings)
                        self._engine._session_id = self.id
                        record.state = self._state
                    else:
                        self._id = self._engine._session_id
                self._callbacks = callbacks
            except BaseException:
                await self._engine._close()
                raise
            if self._closing is not None:
                raise EngineError("Session closed while opening")
        return self

    def _lock(self) -> AbstractAsyncContextManager[StoredConversation]:
        if self._storage is None:
            return nullcontext(StoredConversation(self._state))
        return self._storage.lock(self.id)

    async def __aexit__(self, *exc: object) -> None:
        await self.close()

    @property
    def id(self) -> str:
        """The conversation's stable ID, available from entry through shutdown."""
        if self._id is None:
            raise EngineError("Open the session to get its ID")
        return self._id

    def snapshot(self) -> ConversationState | None:
        """Copy the last completed or interrupted state, or the initial state before any turns."""
        return deepcopy(self._state)

    async def run(self, input: str | None = None, *, text: str | None = None) -> RunResult:
        """Run one turn on this conversation."""
        text = _turn_input(input, text)
        return await _drain(self.stream(text))

    @_turn_stream
    async def stream(
        self, input: str | None = None, *, text: str | None = None
    ) -> AsyncGenerator[RunEvent, None]:
        """Yield one turn's events and final result. Closing the iterator stops that turn."""
        text = _turn_input(input, text)
        if self._callbacks is None or self._closing is not None:
            raise EngineError("Session is closed. Open it with 'async with agent.session()'.")
        if self._turn is not None:
            raise EngineError("Session already has an active turn")
        if not isinstance(text, str) or not text.strip():
            raise RunError("Turn input is required", code="invalid_input")
        turn = self._turn = _Turn()
        turn.reader = asyncio.create_task(self._read_turn(turn, text, self._callbacks))
        try:
            while True:
                event = await turn.events.get()
                if isinstance(event, BaseException):
                    raise event
                yield event
                if isinstance(event, RunResult):
                    return
                turn.advance.set()
        finally:
            await turn.stop()

    async def _read_turn(
        self, turn: _Turn, text: str, callbacks: _Callbacks
    ) -> BaseException | None:
        try:
            async with self._lock() as record:
                if record.state != self._state:
                    raise RunError(
                        "Stored session changed. Reopen it by ID.", code="session_changed"
                    )
                try:
                    outcome: RunResult | _Interrupted = await self._forward(turn, text, callbacks)
                except _Interrupted as stopped:
                    outcome = stopped
                record.state = deepcopy(outcome.state)
            self._state = record.state
            turn.events.put_nowait(outcome)
            return None
        except (Exception, asyncio.CancelledError) as failure:
            # The live thread may have progressed beyond the last portable snapshot.
            self._callbacks = None
            turn.events.put_nowait(failure)
            await self._engine._close()
            return failure
        finally:
            self._turn = None

    async def _forward(self, turn: _Turn, text: str, callbacks: _Callbacks) -> RunResult:
        async with aclosing(self._engine._stream_turn(text, callbacks, turn.control)) as events:
            async for event in events:
                if isinstance(event, RunResult):
                    return event
                turn.advance.clear()
                turn.events.put_nowait(event)
                # Follow the consumer's pace until stop takes over draining events.
                if not turn.control.stopping:
                    await turn.advance.wait()
        raise EngineError("Stream ended before the result")

    async def interrupt(self) -> None:
        """Stop the active turn and wait until its snapshot is ready. Idle calls do nothing."""
        if self._turn is not None:
            await self._turn.stop()

    async def cancel(self) -> None:
        """Cancel the current turn and wait for its snapshot to be saved."""
        await self.interrupt()

    async def close(self) -> None:
        """Stop active work and shut down the session. Safe to call more than once."""
        if self._closing is None:
            self._closing = asyncio.create_task(self._shutdown())
        await asyncio.shield(self._closing)

    async def _shutdown(self) -> None:
        async with self._lifecycle:
            try:
                await self.interrupt()
                if self._callbacks is not None:
                    await self._engine._request("close", {})
            finally:
                self._callbacks = None
                await self._engine._close()

id property

id: str

The conversation's stable ID, available from entry through shutdown.

resume classmethod

resume(
    session_id: str,
    *,
    storage: SessionStorage,
    environment: Environment | EllipsisType = ...,
) -> Session

Resume without an executor. Use agent.session() for current tools and permissions.

Source code in src/openai_agents/codex/session.py
@classmethod
def resume(
    cls,
    session_id: str,
    *,
    storage: SessionStorage,
    environment: Environment | EllipsisType = ...,
) -> Session:
    """Resume without an executor. Use agent.session() for current tools and permissions."""
    _validate_id(session_id)
    return cls(None, storage=storage, session_id=session_id, environment=environment)

snapshot

snapshot() -> ConversationState | None

Copy the last completed or interrupted state, or the initial state before any turns.

Source code in src/openai_agents/codex/session.py
def snapshot(self) -> ConversationState | None:
    """Copy the last completed or interrupted state, or the initial state before any turns."""
    return deepcopy(self._state)

run async

run(
    input: str | None = None, *, text: str | None = None
) -> RunResult

Run one turn on this conversation.

Source code in src/openai_agents/codex/session.py
async def run(self, input: str | None = None, *, text: str | None = None) -> RunResult:
    """Run one turn on this conversation."""
    text = _turn_input(input, text)
    return await _drain(self.stream(text))

stream async

stream(
    input: str | None = None, *, text: str | None = None
) -> AsyncGenerator[RunEvent, None]

Yield one turn's events and final result. Closing the iterator stops that turn.

Source code in src/openai_agents/codex/session.py
@_turn_stream
async def stream(
    self, input: str | None = None, *, text: str | None = None
) -> AsyncGenerator[RunEvent, None]:
    """Yield one turn's events and final result. Closing the iterator stops that turn."""
    text = _turn_input(input, text)
    if self._callbacks is None or self._closing is not None:
        raise EngineError("Session is closed. Open it with 'async with agent.session()'.")
    if self._turn is not None:
        raise EngineError("Session already has an active turn")
    if not isinstance(text, str) or not text.strip():
        raise RunError("Turn input is required", code="invalid_input")
    turn = self._turn = _Turn()
    turn.reader = asyncio.create_task(self._read_turn(turn, text, self._callbacks))
    try:
        while True:
            event = await turn.events.get()
            if isinstance(event, BaseException):
                raise event
            yield event
            if isinstance(event, RunResult):
                return
            turn.advance.set()
    finally:
        await turn.stop()

interrupt async

interrupt() -> None

Stop the active turn and wait until its snapshot is ready. Idle calls do nothing.

Source code in src/openai_agents/codex/session.py
async def interrupt(self) -> None:
    """Stop the active turn and wait until its snapshot is ready. Idle calls do nothing."""
    if self._turn is not None:
        await self._turn.stop()

cancel async

cancel() -> None

Cancel the current turn and wait for its snapshot to be saved.

Source code in src/openai_agents/codex/session.py
async def cancel(self) -> None:
    """Cancel the current turn and wait for its snapshot to be saved."""
    await self.interrupt()

close async

close() -> None

Stop active work and shut down the session. Safe to call more than once.

Source code in src/openai_agents/codex/session.py
async def close(self) -> None:
    """Stop active work and shut down the session. Safe to call more than once."""
    if self._closing is None:
        self._closing = asyncio.create_task(self._shutdown())
    await asyncio.shield(self._closing)