Skip to content

Session

🛈 DocStrings

Runtime handle for an active Codex thread.

Wraps a :class:CodexClient and a thread_id so that every thread-scoped operation can be called without passing the ID again.

Returned by :meth:CodexClient.thread_start, :meth:CodexClient.thread_resume, and :meth:CodexClient.thread_fork.

Example::

session = await client.thread_start(cwd="/my/project")
async for event in session.turn_stream("Explain this repo"):
    ...
await session.set_name("exploration")
Source code in src/codexed/client/session.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
class Session:
    """Runtime handle for an active Codex thread.

    Wraps a :class:`CodexClient` and a ``thread_id`` so that every
    thread-scoped operation can be called without passing the ID again.

    Returned by :meth:`CodexClient.thread_start`,
    :meth:`CodexClient.thread_resume`, and :meth:`CodexClient.thread_fork`.

    Example::

        session = await client.thread_start(cwd="/my/project")
        async for event in session.turn_stream("Explain this repo"):
            ...
        await session.set_name("exploration")
    """

    def __init__(self, client: CodexClient, response: ThreadResponse) -> None:
        self._client = client
        self.response = response
        self.usage: ThreadTokenUsage | None = None

    @property
    def thread_id(self) -> str:
        """The underlying thread ID."""
        return self.response.thread.id

    # -- Turn operations -----------------------------------------------------

    async def turn_stream(
        self,
        user_input: str | Sequence[UserInput],
        *,
        model: str | None = None,
        effort: ReasoningEffort | None = None,
        approval_policy: AskForApproval | None = None,
        approvals_reviewer: ApprovalsReviewer | None = None,
        cwd: str | None = None,
        sandbox_policy: SandboxMode | SandboxPolicy | None = None,
        output_schema: dict[str, Any] | type[Any] | None = None,
        personality: Personality | None = None,
        service_tier: str | None = None,
        summary: ReasoningSummary | None = None,
        collaboration_mode: CollaborationMode | None = None,
        responsesapi_client_metadata: dict[str, Any] | None = None,
        environments: list[TurnEnvironmentParams] | None = None,
        permissions: str | None = None,
    ) -> AsyncIterator[CodexEvent]:
        """Start a turn and stream events.

        Args:
            user_input: User input as string or list of input items (text/image)
            model: Optional model override for this turn
            effort: Optional reasoning effort override
            approval_policy: Optional approval policy
            approvals_reviewer: Where approval requests are routed for review
            cwd: Optional working directory override for this and subsequent turns
            sandbox_policy: Optional sandbox mode or policy dict
            output_schema: Optional JSON Schema dict or Pydantic type to constrain output
            personality: Optional personality override
            service_tier: Optional service tier (fast/flex)
            summary: Optional reasoning summary mode
            collaboration_mode: Optional collaboration mode preset (experimental)
            responsesapi_client_metadata: Optional turn-scoped Responses API client metadata.
            environments: Optional list of environment variables to set for this turn.
            permissions: Named permissions profile ID (cannot be combined with sandbox)

        Yields:
            CodexEvent: Streaming events from the turn

        Cancelling the consumer, or closing the stream before ``turn/completed``,
        interrupts the turn (``turn/interrupt``).
        """
        # Handle output_schema - convert type to JSON Schema if needed
        match output_schema:
            case None:
                schema_dict: dict[str, Any] | None = None
            case dict():
                schema_dict = output_schema
            case type():
                schema_dict = TypeAdapter(output_schema).json_schema()
            case _ as unreachable:
                assert_never(unreachable)
        # Handle sandbox_policy - convert string to dict if needed
        match sandbox_policy:
            case None:
                policy: SandboxPolicy | None = None
            case str():
                dct = {"type": kebab_to_camel(sandbox_policy)}
                policy = TypeAdapter[SandboxPolicy](SandboxPolicy).validate_python(dct)
            case (
                DangerFullAccessSandboxPolicy()
                | ReadOnlySandboxPolicy()
                | ExternalSandboxSandboxPolicy()
                | WorkspaceWriteSandboxPolicy()
            ):
                policy = sandbox_policy
            case _:
                assert_never(sandbox_policy)
        in_: list[UserInput] = (
            [TextUserInput(text=user_input)] if isinstance(user_input, str) else list(user_input)
        )
        params = TurnStartParams(
            thread_id=self.thread_id,
            input=in_,
            model=model,
            effort=effort,
            approval_policy=approval_policy,
            approvals_reviewer=approvals_reviewer,
            cwd=cwd,
            sandbox_policy=policy,
            service_tier=service_tier,
            output_schema=schema_dict,
            personality=personality,
            summary=summary,
            collaboration_mode=collaboration_mode,
            responsesapi_client_metadata=responsesapi_client_metadata,
            environments=environments,
            permissions=permissions,
        )
        turn_queue: asyncio.Queue[CodexEvent | None] = asyncio.Queue()
        turn_key: str | None = None
        turn_id: str | None = None
        finished = False  # The turn ended (or the connection did): nothing to interrupt
        self._client._begin_turn_start()
        # One try: a cancellation while _end_turn_start hands out buffered events
        # still forgets the queue and interrupts the turn.
        try:
            try:
                turn_result = await self._client.dispatch.send_request("turn/start", params)
                response = TurnStartResponse.model_validate(turn_result)
                turn_id = response.turn.id
                turn_key = f"{self.thread_id}:{turn_id}"
            finally:
                await self._client._end_turn_start(turn_key, turn_queue)
            while True:
                event = await turn_queue.get()
                match event:
                    case None:
                        finished = True
                        raise self._connection_closed()
                    case TurnCompletedEvent():
                        finished = True
                        yield event
                        break
                    case ErrorMessage(params=ErrorNotification(error=error)):
                        finished = True
                        yield event
                        raise TurnFailedError(error.message, turn_id=turn_id)
                    case ThreadTokenUsageUpdatedEvent(
                        params=ThreadTokenUsageUpdatedNotification(token_usage=usage)
                    ):
                        self.usage = usage
                        yield event
                    case _:
                        yield event
        finally:
            if turn_key is not None:
                self._client._turn_queues.pop(turn_key, None)
            if turn_id is not None and not finished:  # Cancelled, or closed early
                await self._interrupt_abandoned_turn(self.thread_id, turn_id)

    async def turn_steer(
        self,
        user_input: str | Sequence[UserInput],
        *,
        expected_turn_id: str,
        responsesapi_client_metadata: dict[str, Any] | None = None,
    ) -> TurnSteerResponse:
        """Steer a running turn with additional input.

        Args:
            user_input: Additional user input
            expected_turn_id: The expected active turn ID (precondition)
            responsesapi_client_metadata: Optional turn-scoped Responses API client metadata.

        Returns:
            TurnSteerResponse with the turn ID
        """
        params = TurnSteerParams(
            thread_id=self.thread_id,
            input=[TextUserInput(text=user_input)]  # pyright: ignore[reportCallIssue, reportArgumentType]
            if isinstance(user_input, str)
            else list(user_input),
            expected_turn_id=expected_turn_id,
            responsesapi_client_metadata=responsesapi_client_metadata,
        )
        result = await self._client.dispatch.send_request("turn/steer", params)
        return TurnSteerResponse.model_validate(result)

    async def turn_interrupt(self, turn_id: str) -> None:
        """Interrupt a running turn."""
        params = TurnInterruptParams(thread_id=self.thread_id, turn_id=turn_id)
        await self._client.dispatch.send_request("turn/interrupt", params)

    async def _interrupt_abandoned_turn(self, thread_id: str, turn_id: str) -> None:
        """Stop a turn whose stream was cancelled or closed early (best effort, bounded)."""
        params = TurnInterruptParams(thread_id=thread_id, turn_id=turn_id)
        try:
            async with asyncio.timeout(ABANDONED_TURN_INTERRUPT_TIMEOUT):
                await self._client.dispatch.send_request("turn/interrupt", params)
        except Exception as exc:  # noqa: BLE001
            logger.debug("Interrupting abandoned turn %s failed: %s", turn_id, exc)

    async def turn_stream_structured[ResultType: BaseModel](
        self,
        user_input: str | list[UserInput],
        result_type: type[ResultType],
        *,
        model: str | None = None,
        effort: ReasoningEffort | None = None,
        approval_policy: AskForApproval | None = None,
        approvals_reviewer: ApprovalsReviewer | None = None,
        cwd: str | None = None,
        sandbox_policy: SandboxMode | SandboxPolicy | None = None,
        personality: Personality | None = None,
        service_tier: str | None = None,
        summary: ReasoningSummary | None = None,
        collaboration_mode: CollaborationMode | None = None,
    ) -> ResultType:
        """Start a turn with structured output and return the parsed result.

        Args:
            user_input: User input as string or list of items
            result_type: Pydantic model class for the expected result
            model: Optional model override for this turn
            effort: Optional reasoning effort override
            approval_policy: Optional approval policy
            approvals_reviewer: Where approval requests are routed for review
            cwd: Optional working directory override
            sandbox_policy: Optional sandbox mode or policy dict
            personality: Optional personality override
            service_tier: Optional service tier (fast/flex)
            summary: Optional reasoning summary mode
            collaboration_mode: Optional collaboration mode preset (experimental)

        Returns:
            Parsed Pydantic model instance of type result_type
        """
        turn: Turn | None = None
        async for event in self.turn_stream(
            user_input,
            model=model,
            effort=effort,
            approval_policy=approval_policy,
            approvals_reviewer=approvals_reviewer,
            cwd=cwd,
            sandbox_policy=sandbox_policy,
            output_schema=result_type,
            personality=personality,
            service_tier=service_tier,
            summary=summary,
            collaboration_mode=collaboration_mode,
        ):
            match event:
                case TurnCompletedEvent(params=TurnCompletedData(turn=t)):
                    turn = t
                case ErrorMessage(params=ErrorNotification(error=error)):
                    raise TurnFailedError(error.message, turn_id="unknown")

        if turn is None:
            raise CodexRequestError(code=-1, message="Turn completed without a TurnCompletedEvent")
        response_text = turn.final_response
        if response_text is None:
            raise CodexRequestError(code=-1, message="Turn completed without a final response")
        return result_type.model_validate_json(response_text)

    # -- Thread operations ---------------------------------------------------

    async def read(self, *, include_turns: bool = False) -> ThreadReadResponse:
        """Read thread data."""
        params = ThreadReadParams(thread_id=self.thread_id, include_turns=include_turns)
        result = await self._client.dispatch.send_request("thread/read", params)
        return ThreadReadResponse.model_validate(result)

    async def unsubscribe(self) -> ThreadUnsubscribeResponse:
        """Stop listening to this thread's events."""
        params = ThreadUnsubscribeParams(thread_id=self.thread_id)
        result = await self._client.dispatch.send_request("thread/unsubscribe", params)
        return ThreadUnsubscribeResponse.model_validate(result)

    async def archive(self) -> None:
        """Archive this thread."""
        params = ThreadArchiveParams(thread_id=self.thread_id)
        await self._client.dispatch.send_request("thread/archive", params)
        self._client._active_threads.discard(self.thread_id)

    async def unarchive(self) -> ThreadUnarchiveResponse:
        """Unarchive this thread."""
        params = ThreadUnarchiveParams(thread_id=self.thread_id)
        result = await self._client.dispatch.send_request("thread/unarchive", params)
        return ThreadUnarchiveResponse.model_validate(result)

    async def set_name(self, name: str) -> None:
        """Set a user-facing name for this thread."""
        params = ThreadSetNameParams(thread_id=self.thread_id, name=name)
        await self._client.dispatch.send_request("thread/name/set", params)

    async def compact_start(self) -> None:
        """Trigger context compaction for this thread."""
        params = ThreadCompactStartParams(thread_id=self.thread_id)
        await self._client.dispatch.send_request("thread/compact/start", params)

    def realtime(
        self,
        output_modality: RealtimeOutputModality,
        prompt: str | None = None,
        *,
        realtime_session_id: str | None = None,
    ) -> RealtimeSession:
        """Open a realtime voice session on this thread.

        Returns an async context manager that sends ``thread/realtime/start``
        on enter and ``thread/realtime/stop`` on exit.  Iterate over the
        returned object to receive realtime events.

        Example::

            async with session.realtime(prompt="You are helpful") as rt:
                await rt.send_text("hello")
                async for event in rt:
                    ...
        """
        return RealtimeSession(
            self._client,
            self.thread_id,
            output_modality=output_modality,
            prompt=prompt,
            realtime_session_id=realtime_session_id,
        )

    async def list_turns(
        self,
        cursor: str | None = None,
        limit: int | None = None,
        sort_direction: SortDirection | None = None,
    ) -> ThreadTurnsListResponse:
        """List all turns in this thread."""
        params = ThreadTurnsListParams(
            cursor=cursor,
            limit=limit,
            sort_direction=sort_direction,
            thread_id=self.thread_id,
        )
        result = await self._client.dispatch.send_request("thread/turns/list", params)
        return ThreadTurnsListResponse.model_validate(result)

    async def revert(self, before_turn_id: str) -> ThreadRevertResponse:
        """Replace the thread's persisted history with the turns before `before_turn_id`.

        The given turn and all later turns are dropped. Only conversation history
        changes; local file changes are not reverted.

        Args:
            before_turn_id: First turn to drop (it and every later turn are removed)

        Returns:
            Updated thread metadata and cursors for re-hydrating the retained history
        """
        params = ThreadRevertParams(thread_id=self.thread_id, before_turn_id=before_turn_id)
        result = await self._client.dispatch.send_request("thread/revert", params)
        return ThreadRevertResponse.model_validate(result)

    async def shell_command(self, command: str) -> None:
        """Run a user-initiated shell command against this thread.

        Executes the command unsandboxed, as if the user typed ``!command``
        in the Codex CLI.

        Args:
            command: Shell command to execute.
        """
        params = ThreadShellCommandParams(thread_id=self.thread_id, command=command)
        await self._client.dispatch.send_request("thread/shellCommand", params)

    # -- Review --------------------------------------------------------------

    async def review_start(
        self,
        target: ReviewTarget,
        *,
        delivery: ReviewDelivery = "inline",
    ) -> ReviewStartResponse:
        """Start a code review.

        Inline delivery runs the review on the same thread, so review items
        appear in the existing thread history.  Detached delivery creates a new
        thread for the review, keeping the original thread's history clean.

        Args:
            target: Review target (uncommittedChanges, baseBranch, commit, or custom)
            delivery: Where to run the review (inline or detached)

        Returns:
            ReviewStartResponse with turn and review thread ID
        """
        params = ReviewStartParams(thread_id=self.thread_id, target=target, delivery=delivery)
        result = await self._client.dispatch.send_request("review/start", params)
        return ReviewStartResponse.model_validate(result)

    async def review_stream(
        self,
        target: ReviewTarget,
        *,
        delivery: ReviewDelivery = "inline",
    ) -> AsyncIterator[CodexEvent]:
        """Start a code review and stream events.

        Inline delivery runs the review on the same thread, so review items
        appear in the existing thread history.  Detached delivery creates a new
        thread for the review, keeping the original thread's history clean.

        Args:
            target: Review target (uncommittedChanges, baseBranch, commit, or custom)
            delivery: Where to run the review (inline or detached)

        Yields:
            CodexEvent: Streaming events from the review turn

        Cancelling the consumer, or closing the stream before the turn completes,
        interrupts the review turn.
        """
        params = ReviewStartParams(thread_id=self.thread_id, target=target, delivery=delivery)
        turn_queue: asyncio.Queue[CodexEvent | None] = asyncio.Queue()
        turn_key: str | None = None
        turn_id: str | None = None
        review_thread_id = self.thread_id
        finished = False  # The turn ended (or the connection did): nothing to interrupt
        self._client._begin_turn_start()
        try:  # One try, as in turn_stream
            try:
                result = await self._client.dispatch.send_request("review/start", params)
                response = ReviewStartResponse.model_validate(result)
                turn_id = response.turn.id
                review_thread_id = response.review_thread_id
                turn_key = f"{review_thread_id}:{turn_id}"
            finally:
                await self._client._end_turn_start(turn_key, turn_queue)
            while True:
                event = await turn_queue.get()
                match event:
                    case None:
                        finished = True
                        raise self._connection_closed()
                    case TurnCompletedEvent():
                        finished = True
                        yield event
                        break
                    case ErrorMessage(params=ErrorNotification(error=error)):
                        finished = True
                        yield event
                        raise TurnFailedError(error.message, turn_id=turn_id)
                    case _:
                        yield event
        finally:
            if turn_key is not None:
                self._client._turn_queues.pop(turn_key, None)
            if turn_id is not None and not finished:  # Cancelled, or closed early
                await self._interrupt_abandoned_turn(review_thread_id, turn_id)

    # -- Fork ----------------------------------------------------------------

    async def fork(
        self,
        *,
        path: str | None = None,
        cwd: str | None = None,
        model: str | None = None,
        model_provider: str | None = None,
        base_instructions: str | None = None,
        developer_instructions: str | None = None,
        approval_policy: AskForApproval | None = None,
        approvals_reviewer: ApprovalsReviewer | None = None,
        sandbox: SandboxMode | None = None,
        config: dict[str, Any] | None = None,
        tools: list[ToolConfig] | None = None,
        code_mode: bool | None = None,
        service_tier: str | None = None,
        ephemeral: bool | None = None,
        mcp_servers: Mapping[str, McpServerConfig] | None = None,
        last_turn_id: str | None = None,
        before_turn_id: str | None = None,
        exclude_turns: bool | None = None,
        permissions: str | None = None,
    ) -> Session:
        """Fork this thread into a new thread with copied history.

        Args:
            path: Path to thread storage
            cwd: Working directory for the forked thread
            model: Model override for forked thread
            model_provider: Model provider override
            base_instructions: Base system instructions for forked thread
            developer_instructions: Developer instructions for forked thread
            approval_policy: Tool approval policy for forked thread
            approvals_reviewer: Where approval requests are routed for review
            sandbox: Sandbox mode for forked thread
            config: Additional configuration overrides
            tools: Builtin tool configurations for forked thread
            code_mode: Enable experimental code mode feature flag
            service_tier: Service tier
            ephemeral: If true, forked thread is not persisted
            mcp_servers: Per-thread MCP server configurations
            last_turn_id: Fork through this turn (inclusive), omitting later turns
            before_turn_id: Fork before this turn, excluding it and all later turns
            exclude_turns: When true, return only thread metadata and live fork state
                            without populating `thread.turns`. This is useful when
                            the client plans to call `thread/turns/list` immediately after forking.
            permissions: Named permissions profile ID (cannot be combined with sandbox)

        Returns:
            Session wrapping the new forked thread
        """
        return await self._client.thread_fork(
            self.thread_id,
            path=path,
            cwd=cwd,
            model=model,
            model_provider=model_provider,
            base_instructions=base_instructions,
            developer_instructions=developer_instructions,
            approval_policy=approval_policy,
            approvals_reviewer=approvals_reviewer,
            sandbox=sandbox,
            config=config,
            tools=tools,
            code_mode=code_mode,
            service_tier=service_tier,
            ephemeral=ephemeral,
            mcp_servers=mcp_servers,
            last_turn_id=last_turn_id,
            before_turn_id=before_turn_id,
            exclude_turns=exclude_turns,
            permissions=permissions,
        )

    async def read_resource(self, server: str, uri: str) -> list[ResourceContents]:
        """Read a resource from the MCP server."""
        params = McpResourceReadParams(server=server, thread_id=self.thread_id, uri=uri)
        result = await self._client.dispatch.send_request("mcpServer/resource/read", params)
        data = McpResourceReadResponse.model_validate(result)
        ta = TypeAdapter[ResourceContents](ResourceContents)

        def convert(old: BaseModel) -> ResourceContents:
            dct = old.model_dump()
            dct["_meta"] = dct.pop("field_meta")
            return ta.validate_python(dct)

        return [convert(i) for i in data.contents]

    async def tool_call(
        self,
        server: str,
        tool: str,
        arguments: Any | None = None,
        meta: dict[str, Any] | None = None,
    ) -> CallToolResult:
        """Call a tool on the MCP server."""
        params = McpServerToolCallParams(
            server=server,
            thread_id=self.thread_id,
            tool=tool,
            arguments=arguments,
            field_meta=meta,
        )
        result = await self._client.dispatch.send_request("mcpServer/tool/call", params)
        data = McpServerToolCallResponse.model_validate(result)
        return CallToolResult(
            structured_content=data.structured_content,
            is_error=bool(data.is_error),
            content=data.content,
            meta=data.field_meta,
        )

    def _connection_closed(self) -> TransportClosedError:
        """The error for a stream whose connection ended before the turn completed."""
        reason = self._client.dispatch.closed_error or "connection closed"
        return TransportClosedError(f"Codex app-server connection ended mid-turn: {reason}")

    def __repr__(self) -> str:
        return f"Session(thread_id={self.thread_id!r})"

    async def inject_items(self, items: list[ResponseItem]) -> None:
        """Inject raw responses-API Items into the thread's model-visible history."""
        params = ThreadInjectItemsParams(items=items, thread_id=self.thread_id)
        await self._client.dispatch.send_request("thread/inject_items", params)

    async def set_memory_mode(self, mode: ThreadMemoryMode) -> None:
        """Set the thread's memory mode."""
        params = ThreadMemoryModeSetParams(mode=mode, thread_id=self.thread_id)
        await self._client.dispatch.send_request("thread/memoryMode/set", params)

    async def warning(self, message: str) -> None:
        """Send a thread-related warning message to the app-server."""
        params = WarningNotification(message=message, thread_id=self.thread_id)
        await self._client.dispatch.send_request("warning", params)

    async def guardian_warning(self, message: str) -> None:
        """Send a thread-related guardian warning message to the app-server."""
        params = GuardianWarningNotification(message=message, thread_id=self.thread_id)
        await self._client.dispatch.send_request("warning", params)

    async def approve_guardian_denied_action(self, event: Any) -> None:
        """Send a request to the server to approve a guardian denied action."""
        params = ThreadApproveGuardianDeniedActionParams(event=event, thread_id=self.thread_id)
        await self._client.dispatch.send_request("thread/approveGuardianDeniedAction", params)

thread_id property

thread_id: str

The underlying thread ID.

approve_guardian_denied_action async

approve_guardian_denied_action(event: Any) -> None

Send a request to the server to approve a guardian denied action.

Source code in src/codexed/client/session.py
async def approve_guardian_denied_action(self, event: Any) -> None:
    """Send a request to the server to approve a guardian denied action."""
    params = ThreadApproveGuardianDeniedActionParams(event=event, thread_id=self.thread_id)
    await self._client.dispatch.send_request("thread/approveGuardianDeniedAction", params)

archive async

archive() -> None

Archive this thread.

Source code in src/codexed/client/session.py
async def archive(self) -> None:
    """Archive this thread."""
    params = ThreadArchiveParams(thread_id=self.thread_id)
    await self._client.dispatch.send_request("thread/archive", params)
    self._client._active_threads.discard(self.thread_id)

compact_start async

compact_start() -> None

Trigger context compaction for this thread.

Source code in src/codexed/client/session.py
async def compact_start(self) -> None:
    """Trigger context compaction for this thread."""
    params = ThreadCompactStartParams(thread_id=self.thread_id)
    await self._client.dispatch.send_request("thread/compact/start", params)

fork async

fork(
    *,
    path: str | None = None,
    cwd: str | None = None,
    model: str | None = None,
    model_provider: str | None = None,
    base_instructions: str | None = None,
    developer_instructions: str | None = None,
    approval_policy: AskForApproval | None = None,
    approvals_reviewer: ApprovalsReviewer | None = None,
    sandbox: SandboxMode | None = None,
    config: dict[str, Any] | None = None,
    tools: list[ToolConfig] | None = None,
    code_mode: bool | None = None,
    service_tier: str | None = None,
    ephemeral: bool | None = None,
    mcp_servers: Mapping[str, McpServerConfig] | None = None,
    last_turn_id: str | None = None,
    before_turn_id: str | None = None,
    exclude_turns: bool | None = None,
    permissions: str | None = None,
) -> Session

Fork this thread into a new thread with copied history.

Parameters:

Name Type Description Default
path str | None

Path to thread storage

None
cwd str | None

Working directory for the forked thread

None
model str | None

Model override for forked thread

None
model_provider str | None

Model provider override

None
base_instructions str | None

Base system instructions for forked thread

None
developer_instructions str | None

Developer instructions for forked thread

None
approval_policy AskForApproval | None

Tool approval policy for forked thread

None
approvals_reviewer ApprovalsReviewer | None

Where approval requests are routed for review

None
sandbox SandboxMode | None

Sandbox mode for forked thread

None
config dict[str, Any] | None

Additional configuration overrides

None
tools list[ToolConfig] | None

Builtin tool configurations for forked thread

None
code_mode bool | None

Enable experimental code mode feature flag

None
service_tier str | None

Service tier

None
ephemeral bool | None

If true, forked thread is not persisted

None
mcp_servers Mapping[str, McpServerConfig] | None

Per-thread MCP server configurations

None
last_turn_id str | None

Fork through this turn (inclusive), omitting later turns

None
before_turn_id str | None

Fork before this turn, excluding it and all later turns

None
exclude_turns bool | None

When true, return only thread metadata and live fork state without populating thread.turns. This is useful when the client plans to call thread/turns/list immediately after forking.

None
permissions str | None

Named permissions profile ID (cannot be combined with sandbox)

None

Returns:

Type Description
Session

Session wrapping the new forked thread

Source code in src/codexed/client/session.py
async def fork(
    self,
    *,
    path: str | None = None,
    cwd: str | None = None,
    model: str | None = None,
    model_provider: str | None = None,
    base_instructions: str | None = None,
    developer_instructions: str | None = None,
    approval_policy: AskForApproval | None = None,
    approvals_reviewer: ApprovalsReviewer | None = None,
    sandbox: SandboxMode | None = None,
    config: dict[str, Any] | None = None,
    tools: list[ToolConfig] | None = None,
    code_mode: bool | None = None,
    service_tier: str | None = None,
    ephemeral: bool | None = None,
    mcp_servers: Mapping[str, McpServerConfig] | None = None,
    last_turn_id: str | None = None,
    before_turn_id: str | None = None,
    exclude_turns: bool | None = None,
    permissions: str | None = None,
) -> Session:
    """Fork this thread into a new thread with copied history.

    Args:
        path: Path to thread storage
        cwd: Working directory for the forked thread
        model: Model override for forked thread
        model_provider: Model provider override
        base_instructions: Base system instructions for forked thread
        developer_instructions: Developer instructions for forked thread
        approval_policy: Tool approval policy for forked thread
        approvals_reviewer: Where approval requests are routed for review
        sandbox: Sandbox mode for forked thread
        config: Additional configuration overrides
        tools: Builtin tool configurations for forked thread
        code_mode: Enable experimental code mode feature flag
        service_tier: Service tier
        ephemeral: If true, forked thread is not persisted
        mcp_servers: Per-thread MCP server configurations
        last_turn_id: Fork through this turn (inclusive), omitting later turns
        before_turn_id: Fork before this turn, excluding it and all later turns
        exclude_turns: When true, return only thread metadata and live fork state
                        without populating `thread.turns`. This is useful when
                        the client plans to call `thread/turns/list` immediately after forking.
        permissions: Named permissions profile ID (cannot be combined with sandbox)

    Returns:
        Session wrapping the new forked thread
    """
    return await self._client.thread_fork(
        self.thread_id,
        path=path,
        cwd=cwd,
        model=model,
        model_provider=model_provider,
        base_instructions=base_instructions,
        developer_instructions=developer_instructions,
        approval_policy=approval_policy,
        approvals_reviewer=approvals_reviewer,
        sandbox=sandbox,
        config=config,
        tools=tools,
        code_mode=code_mode,
        service_tier=service_tier,
        ephemeral=ephemeral,
        mcp_servers=mcp_servers,
        last_turn_id=last_turn_id,
        before_turn_id=before_turn_id,
        exclude_turns=exclude_turns,
        permissions=permissions,
    )

guardian_warning async

guardian_warning(message: str) -> None

Send a thread-related guardian warning message to the app-server.

Source code in src/codexed/client/session.py
async def guardian_warning(self, message: str) -> None:
    """Send a thread-related guardian warning message to the app-server."""
    params = GuardianWarningNotification(message=message, thread_id=self.thread_id)
    await self._client.dispatch.send_request("warning", params)

inject_items async

inject_items(items: list[ResponseItem]) -> None

Inject raw responses-API Items into the thread's model-visible history.

Source code in src/codexed/client/session.py
async def inject_items(self, items: list[ResponseItem]) -> None:
    """Inject raw responses-API Items into the thread's model-visible history."""
    params = ThreadInjectItemsParams(items=items, thread_id=self.thread_id)
    await self._client.dispatch.send_request("thread/inject_items", params)

list_turns async

list_turns(
    cursor: str | None = None, limit: int | None = None, sort_direction: SortDirection | None = None
) -> ThreadTurnsListResponse

List all turns in this thread.

Source code in src/codexed/client/session.py
async def list_turns(
    self,
    cursor: str | None = None,
    limit: int | None = None,
    sort_direction: SortDirection | None = None,
) -> ThreadTurnsListResponse:
    """List all turns in this thread."""
    params = ThreadTurnsListParams(
        cursor=cursor,
        limit=limit,
        sort_direction=sort_direction,
        thread_id=self.thread_id,
    )
    result = await self._client.dispatch.send_request("thread/turns/list", params)
    return ThreadTurnsListResponse.model_validate(result)

read async

read(*, include_turns: bool = False) -> ThreadReadResponse

Read thread data.

Source code in src/codexed/client/session.py
async def read(self, *, include_turns: bool = False) -> ThreadReadResponse:
    """Read thread data."""
    params = ThreadReadParams(thread_id=self.thread_id, include_turns=include_turns)
    result = await self._client.dispatch.send_request("thread/read", params)
    return ThreadReadResponse.model_validate(result)

read_resource async

read_resource(server: str, uri: str) -> list[ResourceContents]

Read a resource from the MCP server.

Source code in src/codexed/client/session.py
async def read_resource(self, server: str, uri: str) -> list[ResourceContents]:
    """Read a resource from the MCP server."""
    params = McpResourceReadParams(server=server, thread_id=self.thread_id, uri=uri)
    result = await self._client.dispatch.send_request("mcpServer/resource/read", params)
    data = McpResourceReadResponse.model_validate(result)
    ta = TypeAdapter[ResourceContents](ResourceContents)

    def convert(old: BaseModel) -> ResourceContents:
        dct = old.model_dump()
        dct["_meta"] = dct.pop("field_meta")
        return ta.validate_python(dct)

    return [convert(i) for i in data.contents]

realtime

realtime(
    output_modality: RealtimeOutputModality,
    prompt: str | None = None,
    *,
    realtime_session_id: str | None = None,
) -> RealtimeSession

Open a realtime voice session on this thread.

Returns an async context manager that sends thread/realtime/start on enter and thread/realtime/stop on exit. Iterate over the returned object to receive realtime events.

Example::

async with session.realtime(prompt="You are helpful") as rt:
    await rt.send_text("hello")
    async for event in rt:
        ...
Source code in src/codexed/client/session.py
def realtime(
    self,
    output_modality: RealtimeOutputModality,
    prompt: str | None = None,
    *,
    realtime_session_id: str | None = None,
) -> RealtimeSession:
    """Open a realtime voice session on this thread.

    Returns an async context manager that sends ``thread/realtime/start``
    on enter and ``thread/realtime/stop`` on exit.  Iterate over the
    returned object to receive realtime events.

    Example::

        async with session.realtime(prompt="You are helpful") as rt:
            await rt.send_text("hello")
            async for event in rt:
                ...
    """
    return RealtimeSession(
        self._client,
        self.thread_id,
        output_modality=output_modality,
        prompt=prompt,
        realtime_session_id=realtime_session_id,
    )

revert async

revert(before_turn_id: str) -> ThreadRevertResponse

Replace the thread's persisted history with the turns before before_turn_id.

The given turn and all later turns are dropped. Only conversation history changes; local file changes are not reverted.

Parameters:

Name Type Description Default
before_turn_id str

First turn to drop (it and every later turn are removed)

required

Returns:

Type Description
ThreadRevertResponse

Updated thread metadata and cursors for re-hydrating the retained history

Source code in src/codexed/client/session.py
async def revert(self, before_turn_id: str) -> ThreadRevertResponse:
    """Replace the thread's persisted history with the turns before `before_turn_id`.

    The given turn and all later turns are dropped. Only conversation history
    changes; local file changes are not reverted.

    Args:
        before_turn_id: First turn to drop (it and every later turn are removed)

    Returns:
        Updated thread metadata and cursors for re-hydrating the retained history
    """
    params = ThreadRevertParams(thread_id=self.thread_id, before_turn_id=before_turn_id)
    result = await self._client.dispatch.send_request("thread/revert", params)
    return ThreadRevertResponse.model_validate(result)

review_start async

review_start(target: ReviewTarget, *, delivery: ReviewDelivery = 'inline') -> ReviewStartResponse

Start a code review.

Inline delivery runs the review on the same thread, so review items appear in the existing thread history. Detached delivery creates a new thread for the review, keeping the original thread's history clean.

Parameters:

Name Type Description Default
target ReviewTarget

Review target (uncommittedChanges, baseBranch, commit, or custom)

required
delivery ReviewDelivery

Where to run the review (inline or detached)

'inline'

Returns:

Type Description
ReviewStartResponse

ReviewStartResponse with turn and review thread ID

Source code in src/codexed/client/session.py
async def review_start(
    self,
    target: ReviewTarget,
    *,
    delivery: ReviewDelivery = "inline",
) -> ReviewStartResponse:
    """Start a code review.

    Inline delivery runs the review on the same thread, so review items
    appear in the existing thread history.  Detached delivery creates a new
    thread for the review, keeping the original thread's history clean.

    Args:
        target: Review target (uncommittedChanges, baseBranch, commit, or custom)
        delivery: Where to run the review (inline or detached)

    Returns:
        ReviewStartResponse with turn and review thread ID
    """
    params = ReviewStartParams(thread_id=self.thread_id, target=target, delivery=delivery)
    result = await self._client.dispatch.send_request("review/start", params)
    return ReviewStartResponse.model_validate(result)

review_stream async

review_stream(
    target: ReviewTarget, *, delivery: ReviewDelivery = "inline"
) -> AsyncIterator[CodexEvent]

Start a code review and stream events.

Inline delivery runs the review on the same thread, so review items appear in the existing thread history. Detached delivery creates a new thread for the review, keeping the original thread's history clean.

Parameters:

Name Type Description Default
target ReviewTarget

Review target (uncommittedChanges, baseBranch, commit, or custom)

required
delivery ReviewDelivery

Where to run the review (inline or detached)

'inline'

Yields:

Name Type Description
CodexEvent AsyncIterator[CodexEvent]

Streaming events from the review turn

Cancelling the consumer, or closing the stream before the turn completes, interrupts the review turn.

Source code in src/codexed/client/session.py
async def review_stream(
    self,
    target: ReviewTarget,
    *,
    delivery: ReviewDelivery = "inline",
) -> AsyncIterator[CodexEvent]:
    """Start a code review and stream events.

    Inline delivery runs the review on the same thread, so review items
    appear in the existing thread history.  Detached delivery creates a new
    thread for the review, keeping the original thread's history clean.

    Args:
        target: Review target (uncommittedChanges, baseBranch, commit, or custom)
        delivery: Where to run the review (inline or detached)

    Yields:
        CodexEvent: Streaming events from the review turn

    Cancelling the consumer, or closing the stream before the turn completes,
    interrupts the review turn.
    """
    params = ReviewStartParams(thread_id=self.thread_id, target=target, delivery=delivery)
    turn_queue: asyncio.Queue[CodexEvent | None] = asyncio.Queue()
    turn_key: str | None = None
    turn_id: str | None = None
    review_thread_id = self.thread_id
    finished = False  # The turn ended (or the connection did): nothing to interrupt
    self._client._begin_turn_start()
    try:  # One try, as in turn_stream
        try:
            result = await self._client.dispatch.send_request("review/start", params)
            response = ReviewStartResponse.model_validate(result)
            turn_id = response.turn.id
            review_thread_id = response.review_thread_id
            turn_key = f"{review_thread_id}:{turn_id}"
        finally:
            await self._client._end_turn_start(turn_key, turn_queue)
        while True:
            event = await turn_queue.get()
            match event:
                case None:
                    finished = True
                    raise self._connection_closed()
                case TurnCompletedEvent():
                    finished = True
                    yield event
                    break
                case ErrorMessage(params=ErrorNotification(error=error)):
                    finished = True
                    yield event
                    raise TurnFailedError(error.message, turn_id=turn_id)
                case _:
                    yield event
    finally:
        if turn_key is not None:
            self._client._turn_queues.pop(turn_key, None)
        if turn_id is not None and not finished:  # Cancelled, or closed early
            await self._interrupt_abandoned_turn(review_thread_id, turn_id)

set_memory_mode async

set_memory_mode(mode: ThreadMemoryMode) -> None

Set the thread's memory mode.

Source code in src/codexed/client/session.py
async def set_memory_mode(self, mode: ThreadMemoryMode) -> None:
    """Set the thread's memory mode."""
    params = ThreadMemoryModeSetParams(mode=mode, thread_id=self.thread_id)
    await self._client.dispatch.send_request("thread/memoryMode/set", params)

set_name async

set_name(name: str) -> None

Set a user-facing name for this thread.

Source code in src/codexed/client/session.py
async def set_name(self, name: str) -> None:
    """Set a user-facing name for this thread."""
    params = ThreadSetNameParams(thread_id=self.thread_id, name=name)
    await self._client.dispatch.send_request("thread/name/set", params)

shell_command async

shell_command(command: str) -> None

Run a user-initiated shell command against this thread.

Executes the command unsandboxed, as if the user typed !command in the Codex CLI.

Parameters:

Name Type Description Default
command str

Shell command to execute.

required
Source code in src/codexed/client/session.py
async def shell_command(self, command: str) -> None:
    """Run a user-initiated shell command against this thread.

    Executes the command unsandboxed, as if the user typed ``!command``
    in the Codex CLI.

    Args:
        command: Shell command to execute.
    """
    params = ThreadShellCommandParams(thread_id=self.thread_id, command=command)
    await self._client.dispatch.send_request("thread/shellCommand", params)

tool_call async

tool_call(
    server: str, tool: str, arguments: Any | None = None, meta: dict[str, Any] | None = None
) -> CallToolResult

Call a tool on the MCP server.

Source code in src/codexed/client/session.py
async def tool_call(
    self,
    server: str,
    tool: str,
    arguments: Any | None = None,
    meta: dict[str, Any] | None = None,
) -> CallToolResult:
    """Call a tool on the MCP server."""
    params = McpServerToolCallParams(
        server=server,
        thread_id=self.thread_id,
        tool=tool,
        arguments=arguments,
        field_meta=meta,
    )
    result = await self._client.dispatch.send_request("mcpServer/tool/call", params)
    data = McpServerToolCallResponse.model_validate(result)
    return CallToolResult(
        structured_content=data.structured_content,
        is_error=bool(data.is_error),
        content=data.content,
        meta=data.field_meta,
    )

turn_interrupt async

turn_interrupt(turn_id: str) -> None

Interrupt a running turn.

Source code in src/codexed/client/session.py
async def turn_interrupt(self, turn_id: str) -> None:
    """Interrupt a running turn."""
    params = TurnInterruptParams(thread_id=self.thread_id, turn_id=turn_id)
    await self._client.dispatch.send_request("turn/interrupt", params)

turn_steer async

turn_steer(
    user_input: str | Sequence[UserInput],
    *,
    expected_turn_id: str,
    responsesapi_client_metadata: dict[str, Any] | None = None,
) -> TurnSteerResponse

Steer a running turn with additional input.

Parameters:

Name Type Description Default
user_input str | Sequence[UserInput]

Additional user input

required
expected_turn_id str

The expected active turn ID (precondition)

required
responsesapi_client_metadata dict[str, Any] | None

Optional turn-scoped Responses API client metadata.

None

Returns:

Type Description
TurnSteerResponse

TurnSteerResponse with the turn ID

Source code in src/codexed/client/session.py
async def turn_steer(
    self,
    user_input: str | Sequence[UserInput],
    *,
    expected_turn_id: str,
    responsesapi_client_metadata: dict[str, Any] | None = None,
) -> TurnSteerResponse:
    """Steer a running turn with additional input.

    Args:
        user_input: Additional user input
        expected_turn_id: The expected active turn ID (precondition)
        responsesapi_client_metadata: Optional turn-scoped Responses API client metadata.

    Returns:
        TurnSteerResponse with the turn ID
    """
    params = TurnSteerParams(
        thread_id=self.thread_id,
        input=[TextUserInput(text=user_input)]  # pyright: ignore[reportCallIssue, reportArgumentType]
        if isinstance(user_input, str)
        else list(user_input),
        expected_turn_id=expected_turn_id,
        responsesapi_client_metadata=responsesapi_client_metadata,
    )
    result = await self._client.dispatch.send_request("turn/steer", params)
    return TurnSteerResponse.model_validate(result)

turn_stream async

turn_stream(
    user_input: str | Sequence[UserInput],
    *,
    model: str | None = None,
    effort: ReasoningEffort | None = None,
    approval_policy: AskForApproval | None = None,
    approvals_reviewer: ApprovalsReviewer | None = None,
    cwd: str | None = None,
    sandbox_policy: SandboxMode | SandboxPolicy | None = None,
    output_schema: dict[str, Any] | type[Any] | None = None,
    personality: Personality | None = None,
    service_tier: str | None = None,
    summary: ReasoningSummary | None = None,
    collaboration_mode: CollaborationMode | None = None,
    responsesapi_client_metadata: dict[str, Any] | None = None,
    environments: list[TurnEnvironmentParams] | None = None,
    permissions: str | None = None,
) -> AsyncIterator[CodexEvent]

Start a turn and stream events.

Parameters:

Name Type Description Default
user_input str | Sequence[UserInput]

User input as string or list of input items (text/image)

required
model str | None

Optional model override for this turn

None
effort ReasoningEffort | None

Optional reasoning effort override

None
approval_policy AskForApproval | None

Optional approval policy

None
approvals_reviewer ApprovalsReviewer | None

Where approval requests are routed for review

None
cwd str | None

Optional working directory override for this and subsequent turns

None
sandbox_policy SandboxMode | SandboxPolicy | None

Optional sandbox mode or policy dict

None
output_schema dict[str, Any] | type[Any] | None

Optional JSON Schema dict or Pydantic type to constrain output

None
personality Personality | None

Optional personality override

None
service_tier str | None

Optional service tier (fast/flex)

None
summary ReasoningSummary | None

Optional reasoning summary mode

None
collaboration_mode CollaborationMode | None

Optional collaboration mode preset (experimental)

None
responsesapi_client_metadata dict[str, Any] | None

Optional turn-scoped Responses API client metadata.

None
environments list[TurnEnvironmentParams] | None

Optional list of environment variables to set for this turn.

None
permissions str | None

Named permissions profile ID (cannot be combined with sandbox)

None

Yields:

Name Type Description
CodexEvent AsyncIterator[CodexEvent]

Streaming events from the turn

Cancelling the consumer, or closing the stream before turn/completed, interrupts the turn (turn/interrupt).

Source code in src/codexed/client/session.py
async def turn_stream(
    self,
    user_input: str | Sequence[UserInput],
    *,
    model: str | None = None,
    effort: ReasoningEffort | None = None,
    approval_policy: AskForApproval | None = None,
    approvals_reviewer: ApprovalsReviewer | None = None,
    cwd: str | None = None,
    sandbox_policy: SandboxMode | SandboxPolicy | None = None,
    output_schema: dict[str, Any] | type[Any] | None = None,
    personality: Personality | None = None,
    service_tier: str | None = None,
    summary: ReasoningSummary | None = None,
    collaboration_mode: CollaborationMode | None = None,
    responsesapi_client_metadata: dict[str, Any] | None = None,
    environments: list[TurnEnvironmentParams] | None = None,
    permissions: str | None = None,
) -> AsyncIterator[CodexEvent]:
    """Start a turn and stream events.

    Args:
        user_input: User input as string or list of input items (text/image)
        model: Optional model override for this turn
        effort: Optional reasoning effort override
        approval_policy: Optional approval policy
        approvals_reviewer: Where approval requests are routed for review
        cwd: Optional working directory override for this and subsequent turns
        sandbox_policy: Optional sandbox mode or policy dict
        output_schema: Optional JSON Schema dict or Pydantic type to constrain output
        personality: Optional personality override
        service_tier: Optional service tier (fast/flex)
        summary: Optional reasoning summary mode
        collaboration_mode: Optional collaboration mode preset (experimental)
        responsesapi_client_metadata: Optional turn-scoped Responses API client metadata.
        environments: Optional list of environment variables to set for this turn.
        permissions: Named permissions profile ID (cannot be combined with sandbox)

    Yields:
        CodexEvent: Streaming events from the turn

    Cancelling the consumer, or closing the stream before ``turn/completed``,
    interrupts the turn (``turn/interrupt``).
    """
    # Handle output_schema - convert type to JSON Schema if needed
    match output_schema:
        case None:
            schema_dict: dict[str, Any] | None = None
        case dict():
            schema_dict = output_schema
        case type():
            schema_dict = TypeAdapter(output_schema).json_schema()
        case _ as unreachable:
            assert_never(unreachable)
    # Handle sandbox_policy - convert string to dict if needed
    match sandbox_policy:
        case None:
            policy: SandboxPolicy | None = None
        case str():
            dct = {"type": kebab_to_camel(sandbox_policy)}
            policy = TypeAdapter[SandboxPolicy](SandboxPolicy).validate_python(dct)
        case (
            DangerFullAccessSandboxPolicy()
            | ReadOnlySandboxPolicy()
            | ExternalSandboxSandboxPolicy()
            | WorkspaceWriteSandboxPolicy()
        ):
            policy = sandbox_policy
        case _:
            assert_never(sandbox_policy)
    in_: list[UserInput] = (
        [TextUserInput(text=user_input)] if isinstance(user_input, str) else list(user_input)
    )
    params = TurnStartParams(
        thread_id=self.thread_id,
        input=in_,
        model=model,
        effort=effort,
        approval_policy=approval_policy,
        approvals_reviewer=approvals_reviewer,
        cwd=cwd,
        sandbox_policy=policy,
        service_tier=service_tier,
        output_schema=schema_dict,
        personality=personality,
        summary=summary,
        collaboration_mode=collaboration_mode,
        responsesapi_client_metadata=responsesapi_client_metadata,
        environments=environments,
        permissions=permissions,
    )
    turn_queue: asyncio.Queue[CodexEvent | None] = asyncio.Queue()
    turn_key: str | None = None
    turn_id: str | None = None
    finished = False  # The turn ended (or the connection did): nothing to interrupt
    self._client._begin_turn_start()
    # One try: a cancellation while _end_turn_start hands out buffered events
    # still forgets the queue and interrupts the turn.
    try:
        try:
            turn_result = await self._client.dispatch.send_request("turn/start", params)
            response = TurnStartResponse.model_validate(turn_result)
            turn_id = response.turn.id
            turn_key = f"{self.thread_id}:{turn_id}"
        finally:
            await self._client._end_turn_start(turn_key, turn_queue)
        while True:
            event = await turn_queue.get()
            match event:
                case None:
                    finished = True
                    raise self._connection_closed()
                case TurnCompletedEvent():
                    finished = True
                    yield event
                    break
                case ErrorMessage(params=ErrorNotification(error=error)):
                    finished = True
                    yield event
                    raise TurnFailedError(error.message, turn_id=turn_id)
                case ThreadTokenUsageUpdatedEvent(
                    params=ThreadTokenUsageUpdatedNotification(token_usage=usage)
                ):
                    self.usage = usage
                    yield event
                case _:
                    yield event
    finally:
        if turn_key is not None:
            self._client._turn_queues.pop(turn_key, None)
        if turn_id is not None and not finished:  # Cancelled, or closed early
            await self._interrupt_abandoned_turn(self.thread_id, turn_id)

turn_stream_structured async

turn_stream_structured(
    user_input: str | list[UserInput],
    result_type: type[ResultType],
    *,
    model: str | None = None,
    effort: ReasoningEffort | None = None,
    approval_policy: AskForApproval | None = None,
    approvals_reviewer: ApprovalsReviewer | None = None,
    cwd: str | None = None,
    sandbox_policy: SandboxMode | SandboxPolicy | None = None,
    personality: Personality | None = None,
    service_tier: str | None = None,
    summary: ReasoningSummary | None = None,
    collaboration_mode: CollaborationMode | None = None,
) -> ResultType

Start a turn with structured output and return the parsed result.

Parameters:

Name Type Description Default
user_input str | list[UserInput]

User input as string or list of items

required
result_type type[ResultType]

Pydantic model class for the expected result

required
model str | None

Optional model override for this turn

None
effort ReasoningEffort | None

Optional reasoning effort override

None
approval_policy AskForApproval | None

Optional approval policy

None
approvals_reviewer ApprovalsReviewer | None

Where approval requests are routed for review

None
cwd str | None

Optional working directory override

None
sandbox_policy SandboxMode | SandboxPolicy | None

Optional sandbox mode or policy dict

None
personality Personality | None

Optional personality override

None
service_tier str | None

Optional service tier (fast/flex)

None
summary ReasoningSummary | None

Optional reasoning summary mode

None
collaboration_mode CollaborationMode | None

Optional collaboration mode preset (experimental)

None

Returns:

Type Description
ResultType

Parsed Pydantic model instance of type result_type

Source code in src/codexed/client/session.py
async def turn_stream_structured[ResultType: BaseModel](
    self,
    user_input: str | list[UserInput],
    result_type: type[ResultType],
    *,
    model: str | None = None,
    effort: ReasoningEffort | None = None,
    approval_policy: AskForApproval | None = None,
    approvals_reviewer: ApprovalsReviewer | None = None,
    cwd: str | None = None,
    sandbox_policy: SandboxMode | SandboxPolicy | None = None,
    personality: Personality | None = None,
    service_tier: str | None = None,
    summary: ReasoningSummary | None = None,
    collaboration_mode: CollaborationMode | None = None,
) -> ResultType:
    """Start a turn with structured output and return the parsed result.

    Args:
        user_input: User input as string or list of items
        result_type: Pydantic model class for the expected result
        model: Optional model override for this turn
        effort: Optional reasoning effort override
        approval_policy: Optional approval policy
        approvals_reviewer: Where approval requests are routed for review
        cwd: Optional working directory override
        sandbox_policy: Optional sandbox mode or policy dict
        personality: Optional personality override
        service_tier: Optional service tier (fast/flex)
        summary: Optional reasoning summary mode
        collaboration_mode: Optional collaboration mode preset (experimental)

    Returns:
        Parsed Pydantic model instance of type result_type
    """
    turn: Turn | None = None
    async for event in self.turn_stream(
        user_input,
        model=model,
        effort=effort,
        approval_policy=approval_policy,
        approvals_reviewer=approvals_reviewer,
        cwd=cwd,
        sandbox_policy=sandbox_policy,
        output_schema=result_type,
        personality=personality,
        service_tier=service_tier,
        summary=summary,
        collaboration_mode=collaboration_mode,
    ):
        match event:
            case TurnCompletedEvent(params=TurnCompletedData(turn=t)):
                turn = t
            case ErrorMessage(params=ErrorNotification(error=error)):
                raise TurnFailedError(error.message, turn_id="unknown")

    if turn is None:
        raise CodexRequestError(code=-1, message="Turn completed without a TurnCompletedEvent")
    response_text = turn.final_response
    if response_text is None:
        raise CodexRequestError(code=-1, message="Turn completed without a final response")
    return result_type.model_validate_json(response_text)

unarchive async

unarchive() -> ThreadUnarchiveResponse

Unarchive this thread.

Source code in src/codexed/client/session.py
async def unarchive(self) -> ThreadUnarchiveResponse:
    """Unarchive this thread."""
    params = ThreadUnarchiveParams(thread_id=self.thread_id)
    result = await self._client.dispatch.send_request("thread/unarchive", params)
    return ThreadUnarchiveResponse.model_validate(result)

unsubscribe async

unsubscribe() -> ThreadUnsubscribeResponse

Stop listening to this thread's events.

Source code in src/codexed/client/session.py
async def unsubscribe(self) -> ThreadUnsubscribeResponse:
    """Stop listening to this thread's events."""
    params = ThreadUnsubscribeParams(thread_id=self.thread_id)
    result = await self._client.dispatch.send_request("thread/unsubscribe", params)
    return ThreadUnsubscribeResponse.model_validate(result)

warning async

warning(message: str) -> None

Send a thread-related warning message to the app-server.

Source code in src/codexed/client/session.py
async def warning(self, message: str) -> None:
    """Send a thread-related warning message to the app-server."""
    params = WarningNotification(message=message, thread_id=self.thread_id)
    await self._client.dispatch.send_request("warning", params)

:fa-brands-github: Show source on GitHub