Skip to content

codexed

Class info

Re-exported classes

Class Module Description
AgentMessageDeltaNotification codexed.models.v2_protocol
AppInfo codexed.models.v2_protocol EXPERIMENTAL - app metadata returned by app-list APIs.
AppListUpdatedMessage codexed.models.v2_protocol Notification sent from the server to the client.
AppListUpdatedNotification codexed.models.v2_protocol EXPERIMENTAL - notification emitted when the app list changes.
BuiltinToolsConfig codexed.models.tool_config Combined configuration for all Codex builtin tools.
CodexClient codexed.client.client Client for the Codex app-server JSON-RPC protocol.
CodexError codexed.exceptions Base exception for Codex adapter errors.
CodexProcessError codexed.exceptions Error starting or communicating with the Codex app-server process.
CodexRequestError codexed.exceptions Error from a Codex app-server request (JSON-RPC error response).
CollaborationMode codexed.models.v2_protocol Collaboration mode for a Codex session.
CommandExecResponse codexed.models.v2_protocol Final buffered result for command/exec.
CommandExecutionOutputDeltaNotification codexed.models.v2_protocol
ConfigWarningMessage codexed.models.v2_protocol Notification sent from the server to the client.
ConfigWarningNotification codexed.models.v2_protocol
DangerFullAccessSandboxPolicy codexed.models.v2_protocol
ExperimentalFeature codexed.models.v2_protocol
ExternalSandboxSandboxPolicy codexed.models.v2_protocol
FsChangedMessage codexed.models.v2_protocol Notification sent from the server to the client.
HttpMcpServer codexed.models.mcp_server MCP server accessible via HTTP/SSE transport.
InternalRpcError codexed.exceptions JSON-RPC internal error (-32603).
InvalidParamsError codexed.exceptions JSON-RPC invalid params (-32602).
InvalidRequestError codexed.exceptions JSON-RPC invalid request (-32600).
ItemAgentMessageDeltaNotification codexed.models.v2_protocol Notification sent from the server to the client.
ItemCommandExecutionOutputDeltaNotification codexed.models.v2_protocol Notification sent from the server to the client.
ItemCompletedEvent codexed.models.events Item completed event.
ItemFileChangeOutputDeltaNotification codexed.models.v2_protocol Deprecated legacy apply_patch output stream notification.
ItemPlanDeltaNotification codexed.models.v2_protocol EXPERIMENTAL - proposed plan streaming deltas for plan items.
ItemReasoningTextDeltaNotification codexed.models.v2_protocol Notification sent from the server to the client.
ItemStartedEvent codexed.models.events Item started event.
LocalImageUserInput codexed.models.v2_protocol
MentionUserInput codexed.models.v2_protocol
MethodNotFoundError codexed.exceptions JSON-RPC method not found (-32601).
Model codexed.models.v2_protocol
ModelReroutedMessage codexed.models.v2_protocol Notification sent from the server to the client.
ModelReroutedNotification codexed.models.v2_protocol
ParseError codexed.exceptions JSON-RPC parse error (-32700).
PlanDeltaNotification codexed.models.v2_protocol EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should not assume concatenated deltas match the completed plan item content.
ReadOnlySandboxPolicy codexed.models.v2_protocol
ReasoningTextDeltaNotification codexed.models.v2_protocol
RetryLimitExceededError codexed.exceptions Server exhausted internal retry budget for a retryable operation.
ReviewStartResponse codexed.models.responses Response for review/start request.
ServerBusyError codexed.exceptions Server is overloaded / unavailable and caller should retry.
Session codexed.client.session Runtime handle for an active Codex thread.
Settings codexed.models.v2_protocol Settings for a collaboration mode.
SkillMetadata codexed.models.v2_protocol
SkillUserInput codexed.models.v2_protocol
StdioMcpServer codexed.models.mcp_server MCP server running as a subprocess via stdio transport.
StdioTransport codexed.transport Transport that communicates with a Codex app-server subprocess via stdin/stdout.
TextUserInput codexed.models.v2_protocol
Thread codexed.models.misc
ThreadArchivedMessage codexed.models.v2_protocol Notification sent from the server to the client.
ThreadArchivedNotification codexed.models.v2_protocol
ThreadCompactedMessage codexed.models.v2_protocol Deprecated: Use ContextCompaction item type instead.
ThreadListResponse codexed.models.responses Response for thread/list request.
ThreadNameUpdatedMessage codexed.models.v2_protocol Notification sent from the server to the client.
ThreadNameUpdatedNotification codexed.models.v2_protocol
ThreadReadResponse codexed.models.responses Response for thread/read request.
ThreadResponse codexed.models.responses Response for thread/start, thread/resume, and thread/fork.
ThreadRevertResponse codexed.models.responses Response for thread/revert request.
ThreadStartedData codexed.models.event_data Payload for thread/started notification (V2 protocol).
ThreadStartedEvent codexed.models.events Thread started event.
ThreadStatusChangedMessage codexed.models.v2_protocol Notification sent from the server to the client.
ThreadStatusChangedNotification codexed.models.v2_protocol
ThreadTokenUsage codexed.models.v2_protocol
ThreadUnarchiveParams codexed.models.v2_protocol
ThreadUnarchiveResponse codexed.models.responses Response for thread/unarchive request.
ThreadUnarchivedMessage codexed.models.v2_protocol Notification sent from the server to the client.
TokenUsageBreakdown codexed.models.v2_protocol
TransportClosedError codexed.exceptions Raised when the app-server transport closes unexpectedly.
TurnCompletedData codexed.models.event_data Payload for turn/completed notification (V2 protocol).
TurnCompletedEvent codexed.models.events Turn completed event.
TurnFailedError codexed.exceptions Raised when a turn completes with failed status.
TurnPlanUpdatedMessage codexed.models.v2_protocol Notification sent from the server to the client.
TurnStartedData codexed.models.event_data Payload for turn/started notification (V2 protocol).
TurnStartedEvent codexed.models.events Turn started event.
TurnSteerResponse codexed.models.v2_protocol
WebSocketTransport codexed.transport Transport that connects to a remote Codex app-server via WebSocket.
WorkspaceWriteSandboxPolicy codexed.models.v2_protocol

🛈 DocStrings

Codexed: main package.

Alternative codex app-server client.

InputModality

InputModality = Literal['text', 'image', 'audio']

Canonical user-input modality tags advertised by a model.

MessagePhase

MessagePhase = Literal['commentary', 'partial_answer', 'final_answer']

Classifies assistant text as commentary, a partial answer, or a terminal answer.

Providers do not emit this consistently, so callers must treat None as "phase unknown" and keep compatibility behavior for legacy models.

ModeKind

ModeKind = Literal['plan', 'default']

Initial collaboration mode to use when the TUI starts.

Personality

Personality = Literal['none', 'friendly', 'pragmatic']

Deprecated: friendly and pragmatic no longer select a style.

ReasoningEffort

ReasoningEffort = Annotated[str, Field(..., min_length=1)]

A non-empty reasoning effort value advertised by the model.

ReasoningSummary

ReasoningSummary = Literal['auto', 'concise', 'detailed', 'none']

A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries

AppInfo

Bases: CodexBaseModel

EXPERIMENTAL - app metadata returned by app-list APIs.

Source code in src/codexed/models/v2_protocol.py
class AppInfo(CodexBaseModel):
    """EXPERIMENTAL - app metadata returned by app-list APIs."""

    app_metadata: AppMetadata | None = None
    branding: AppBranding | None = None
    description: str | None = None
    distribution_channel: str | None = None
    icon_assets: dict[str, Any] | None = None
    icon_dark_assets: dict[str, Any] | None = None
    id: str
    install_url: str | None = None
    is_accessible: bool | None = False
    is_enabled: bool | None = True
    """
    Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```
    """
    labels: dict[str, Any] | None = None
    logo_url: str | None = None
    logo_url_dark: str | None = None
    name: str
    plugin_display_names: list[str] | None = []

is_enabled class-attribute instance-attribute

is_enabled: bool | None = True

Whether this app is enabled in config.toml. Example: toml [apps.bad_app] enabled = false

AppListUpdatedMessage

Bases: CodexBaseModel

Notification sent from the server to the client.

Source code in src/codexed/models/v2_protocol.py
class AppListUpdatedMessage(CodexBaseModel):
    """Notification sent from the server to the client."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["app/list/updated"] = "app/list/updated"
    params: AppListUpdatedNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

AppListUpdatedNotification

Bases: CodexBaseModel

EXPERIMENTAL - notification emitted when the app list changes.

Source code in src/codexed/models/v2_protocol.py
class AppListUpdatedNotification(CodexBaseModel):
    """EXPERIMENTAL - notification emitted when the app list changes."""

    data: list[AppInfo]

BuiltinToolsConfig

Bases: BaseModel

Combined configuration for all Codex builtin tools.

Provides named fields as a convenience over list[ToolConfig]. Call :meth:to_config_dict to obtain the config dict for ThreadStartParams, or :meth:to_tool_list to get a list[ToolConfig].

Example::

tools = BuiltinToolsConfig(
    web_search=WebSearchToolConfig(mode="live", context_size="high"),
    js_repl=JsReplToolConfig(),
)
params = ThreadStartParams(config=tools.to_config_dict())
Source code in src/codexed/models/tool_config.py
class BuiltinToolsConfig(BaseModel):
    """Combined configuration for all Codex builtin tools.

    Provides named fields as a convenience over ``list[ToolConfig]``.
    Call :meth:`to_config_dict` to obtain the ``config`` dict for
    ``ThreadStartParams``, or :meth:`to_tool_list` to get a
    ``list[ToolConfig]``.

    Example::

        tools = BuiltinToolsConfig(
            web_search=WebSearchToolConfig(mode="live", context_size="high"),
            js_repl=JsReplToolConfig(),
        )
        params = ThreadStartParams(config=tools.to_config_dict())
    """

    model_config = ConfigDict(populate_by_name=True)

    shell: ShellToolConfig | None = None
    apply_patch: ApplyPatchToolConfig | None = None
    web_search: WebSearchToolConfig | None = None
    image_generation: ImageGenerationToolConfig | None = None
    view_image: ViewImageToolConfig | None = None
    plan: PlanToolConfig | None = None
    js_repl: JsReplToolConfig | None = None
    collab: CollabToolsConfig | None = None
    agent_jobs: AgentJobsToolsConfig | None = None
    request_user_input: RequestUserInputToolConfig | None = None
    request_permissions: RequestPermissionsToolConfig | None = None
    artifacts: ArtifactsToolConfig | None = None
    grep_files: GrepFilesToolConfig | None = None
    read_file: ReadFileToolConfig | None = None
    list_dir: ListDirToolConfig | None = None
    tool_search: ToolSearchToolConfig | None = None
    tool_suggest: ToolSuggestToolConfig | None = None
    mcp_resources: McpResourceToolsConfig | None = None

    def to_tool_list(self) -> list[ToolConfig]:
        """Return only explicitly set tool configs as a list."""
        return [
            v
            for v in (
                self.shell,
                self.apply_patch,
                self.web_search,
                self.image_generation,
                self.view_image,
                self.plan,
                self.js_repl,
                self.collab,
                self.agent_jobs,
                self.request_user_input,
                self.request_permissions,
                self.artifacts,
                self.grep_files,
                self.read_file,
                self.list_dir,
                self.tool_search,
                self.tool_suggest,
                self.mcp_resources,
            )
            if v is not None
        ]

    def to_config_dict(self) -> dict[str, Any]:
        """Serialize into a flat config dict for ``ThreadStartParams.config``.

        Only explicitly set tools are included. An empty ``BuiltinToolsConfig``
        produces an empty dict (server defaults preserved).
        """
        tool_list = self.to_tool_list()
        if not tool_list:
            return {}
        return tools_to_config_dict(tool_list)

to_config_dict

to_config_dict() -> dict[str, Any]

Serialize into a flat config dict for ThreadStartParams.config.

Only explicitly set tools are included. An empty BuiltinToolsConfig produces an empty dict (server defaults preserved).

Source code in src/codexed/models/tool_config.py
def to_config_dict(self) -> dict[str, Any]:
    """Serialize into a flat config dict for ``ThreadStartParams.config``.

    Only explicitly set tools are included. An empty ``BuiltinToolsConfig``
    produces an empty dict (server defaults preserved).
    """
    tool_list = self.to_tool_list()
    if not tool_list:
        return {}
    return tools_to_config_dict(tool_list)

to_tool_list

to_tool_list() -> list[ToolConfig]

Return only explicitly set tool configs as a list.

Source code in src/codexed/models/tool_config.py
def to_tool_list(self) -> list[ToolConfig]:
    """Return only explicitly set tool configs as a list."""
    return [
        v
        for v in (
            self.shell,
            self.apply_patch,
            self.web_search,
            self.image_generation,
            self.view_image,
            self.plan,
            self.js_repl,
            self.collab,
            self.agent_jobs,
            self.request_user_input,
            self.request_permissions,
            self.artifacts,
            self.grep_files,
            self.read_file,
            self.list_dir,
            self.tool_search,
            self.tool_suggest,
            self.mcp_resources,
        )
        if v is not None
    ]

CodexClient

Client for the Codex app-server JSON-RPC protocol.

Manages the subprocess lifecycle and provides async methods for: - Thread management (conversations) - Turn management (message exchanges) - Event streaming via notifications

Source code in src/codexed/client/client.py
 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
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
class CodexClient:
    """Client for the Codex app-server JSON-RPC protocol.

    Manages the subprocess lifecycle and provides async methods for:
    - Thread management (conversations)
    - Turn management (message exchanges)
    - Event streaming via notifications
    """

    def __init__(
        self,
        codex_command: str = "codex",
        profile: str | None = None,
        env_vars: dict[str, str] | None = None,
        mcp_servers: Mapping[str, McpServerConfig] | None = None,
        on_approval: ApprovalHandler | None = None,
        on_user_input: UserInputHandler | None = None,
        on_dynamic_tool_call: DynamicToolCallHandler | None = None,
        on_mcp_elicitation: McpElicitationHandler | None = None,
        mcp_elicitation_for_approvals: bool = False,
        transport: Transport | None = None,
    ) -> None:
        """Initialize the Codex app-server client.

        Args:
            codex_command: Path to the codex binary (default: "codex")
            profile: Optional Codex profile to use
            env_vars: Optional environment variables to set for the Codex process.
            mcp_servers: Optional MCP servers to inject programmatically.
                Keys are server names, values are server configurations.
            on_approval: Handler for all approval requests
                (command execution, file change, and skill approval).
            on_user_input: Handler for tool user input requests.
            on_dynamic_tool_call: Handler for dynamic tool call requests.
            on_mcp_elicitation: Handler for MCP elicitation requests.
            mcp_elicitation_for_approvals: If True, enables the Codex
                ``tool_call_mcp_elicitation`` feature flag which routes MCP tool
                approval prompts through ``mcpServer/elicitation/request`` instead
                of ``item/tool/requestUserInput``.  Requires *on_mcp_elicitation*
                to handle approvals (the schema is empty; context is in ``_meta``).
                Default is False because the default elicitation handler auto-declines,
                which would break MCP tool approvals.
            transport: Pre-configured transport instance. If provided,
                ``codex_command``, ``profile``, ``env_vars``, and ``mcp_servers``
                are ignored (they are only used to build the default
                ``StdioTransport``).  Pass a ``WebSocketTransport`` here to
                connect to a remote app-server.
        """
        tp = transport or StdioTransport(
            command=codex_command,
            profile=profile,
            env_vars=env_vars,
            mcp_servers=mcp_servers,
        )
        self.dispatch = Dispatch(
            tp,
            on_notification=self._handle_notification,
            on_server_request=self._handle_server_request,
            on_close=self._handle_close,
        )
        self._turn_queues: dict[str, asyncio.Queue[CodexEvent | None]] = {}
        # Turn events that arrive while a turn/start (or review/start) request is pending
        # and have no queue yet: the response and the first events can come in one read.
        self._pending_turn_starts = 0
        self._turn_buffer: list[tuple[str, CodexEvent]] = []
        self._realtime_queues: dict[str, asyncio.Queue[CodexEvent | None]] = {}
        self._event_listeners: list[EventListener] = []
        self._active_threads: set[str] = set()
        self._mcp_elicitation_enabled = on_mcp_elicitation is not None
        self._mcp_elicitation_for_approvals = mcp_elicitation_for_approvals
        self._server_request_handlers: dict[str, ServerRequestHandler] = {}
        self.account = CodexAccount(self)
        self.fs = CodexFS(self)
        self.plugins = CodexPlugin(self)
        self.marketplace = CodexMarketPlace(self)
        self.skills = CodexSkills(self)
        if on_approval:
            self.register_handler(SERVER_REQUEST_COMMAND_APPROVAL, on_approval)  # ty: ignore[invalid-argument-type]
            self.register_handler(SERVER_REQUEST_FILE_CHANGE_APPROVAL, on_approval)  # ty: ignore[invalid-argument-type]
            self.register_handler(SERVER_REQUEST_SKILL_APPROVAL, on_approval)  # ty: ignore[invalid-argument-type]
        if on_user_input:
            self.register_handler(SERVER_REQUEST_USER_INPUT, on_user_input)  # ty: ignore[invalid-argument-type]
        if on_dynamic_tool_call:
            self.register_handler(SERVER_REQUEST_DYNAMIC_TOOL_CALL, on_dynamic_tool_call)  # ty: ignore[invalid-argument-type]
        if on_mcp_elicitation:
            self.register_handler(SERVER_REQUEST_MCP_ELICITATION, on_mcp_elicitation)  # ty: ignore[invalid-argument-type]

    async def __aenter__(self) -> Self:
        """Async context manager entry - starts the app-server."""
        import codexed
        from codexed.models import ClientInfo, InitializeCapabilities, InitializeParams

        await self.dispatch.start()
        version = codexed.__version__
        init_params = InitializeParams(
            client_info=ClientInfo(name="codexed", version=version),
            capabilities=InitializeCapabilities(experimental_api=True),
        )
        await self.dispatch.send_request("initialize", init_params)
        return self

    async def __aexit__(self, *_args: object) -> None:
        """Async context manager exit - stops the app-server."""
        await self.dispatch.stop()

    # ========================================================================
    # Thread lifecycle methods
    # ========================================================================

    async def thread_start(
        self,
        *,
        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_name: str | None = None,
        service_tier: str | None = None,
        personality: Personality | None = None,
        ephemeral: bool | None = None,
        dynamic_tools: list[DynamicToolSpec] | None = None,
        mcp_servers: Mapping[str, McpServerConfig] | None = None,
        experimental_raw_events: bool = False,
        session_start_source: ThreadStartSource | None = None,
        environments: list[TurnEnvironmentParams] | None = None,
    ) -> Session:
        """Start a new conversation thread.

        Args:
            cwd: Working directory for the thread
            model: Model to use (e.g., "gpt-5-codex")
            model_provider: Model provider (e.g., "openai", "anthropic")
            base_instructions: Base system instructions for the thread
            developer_instructions: Developer-provided instructions
            approval_policy: Tool approval policy
            approvals_reviewer: Where approval requests are routed for review
            sandbox: Sandbox mode for file operations
            config: Additional configuration overrides
            tools: Builtin tool configurations. ``None`` uses server defaults,
                an empty list disables all tools, a populated list enables
                exactly those tools. Merged into ``config``.
            code_mode: Enable experimental code mode feature flag
            service_name: Optional service name
            service_tier: Service tier
            personality: Personality preset (none, friendly, pragmatic)
            ephemeral: If true, thread is not persisted to disk
            dynamic_tools: Dynamic tool specifications
            mcp_servers: Per-thread MCP server configurations.
                Merged into ``config`` under the ``mcp_servers`` key.
            experimental_raw_events: Emit raw Responses API items (internal)
            session_start_source: Source of the session start
            environments: List of environment variables to set for the thread

        Returns:
            Session wrapping the new thread
        """
        from codexed.client.session import Session

        cfg = merge_config(
            config,
            tools,
            code_mode,
            mcp_servers,
            mcp_elicitation_for_approvals=self._mcp_elicitation_for_approvals,
        )
        params = ThreadStartParams(
            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=cfg,
            service_name=service_name,
            service_tier=service_tier,
            personality=personality,
            ephemeral=ephemeral,
            dynamic_tools=dynamic_tools,
            experimental_raw_events=experimental_raw_events,
            session_start_source=session_start_source,
            environments=environments,
        )
        result = await self.dispatch.send_request("thread/start", params)
        response = ThreadResponse.model_validate(result)
        self._active_threads.add(response.thread.id)
        return Session(self, response)

    async def thread_resume(
        self,
        thread_id: str,
        *,
        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,
        personality: Personality | None = None,
        mcp_servers: Mapping[str, McpServerConfig] | None = None,
        exclude_turns: bool | None = None,
        permissions: str | None = None,
    ) -> Session:
        """Resume an existing thread by ID.

        Args:
            thread_id: ID of the thread to resume
            path: Path to thread storage
            cwd: Working directory override
            model: Model override
            model_provider: Model provider override
            base_instructions: Base system instructions override
            developer_instructions: Developer instructions override
            approval_policy: Tool approval policy override
            approvals_reviewer: Where approval requests are routed for review
            sandbox: Sandbox mode override
            config: Additional configuration overrides
            tools: Builtin tool configurations override
            code_mode: Enable experimental code mode feature flag
            service_tier: Service tier
            personality: Personality override
            mcp_servers: Per-thread MCP server configurations
            exclude_turns: If true, exclude turns from the thread's history
            permissions: Named permissions profile ID (cannot be combined with sandbox)

        Returns:
            Session wrapping the resumed thread
        """
        from codexed.client.session import Session

        cfg = merge_config(
            config,
            tools,
            code_mode,
            mcp_servers,
            mcp_elicitation_for_approvals=self._mcp_elicitation_for_approvals,
        )
        params = ThreadResumeParams(
            thread_id=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=cfg,
            service_tier=service_tier,
            personality=personality,
            exclude_turns=exclude_turns,
            permissions=permissions,
        )
        result = await self.dispatch.send_request("thread/resume", params)
        response = ThreadResponse.model_validate(result)
        self._active_threads.add(response.thread.id)
        return Session(self, response)

    async def thread_fork(
        self,
        thread_id: str,
        *,
        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 an existing thread into a new thread with copied history.

        Args:
            thread_id: ID of the thread to fork
            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
            personality: Personality for forked thread
            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
        """
        from codexed.client.session import Session

        cfg = merge_config(
            config,
            tools,
            code_mode,
            mcp_servers,
            mcp_elicitation_for_approvals=self._mcp_elicitation_for_approvals,
        )
        params = ThreadForkParams(
            thread_id=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=cfg,
            service_tier=service_tier,
            ephemeral=ephemeral,
            last_turn_id=last_turn_id,
            before_turn_id=before_turn_id,
            exclude_turns=exclude_turns,
            permissions=permissions,
        )
        result = await self.dispatch.send_request("thread/fork", params)
        response = ThreadResponse.model_validate(result)
        self._active_threads.add(response.thread.id)
        return Session(self, response)

    async def thread_list(
        self,
        *,
        cursor: str | None = None,
        limit: int | None = None,
        sort_key: ThreadSortKey | None = None,
        model_providers: list[str] | None = None,
        source_kinds: list[ThreadSourceKind] | None = None,
        archived: bool | None = None,
        cwd: ThreadListCwdFilter | None = None,
        search_term: str | None = None,
        sort_direction: SortDirection | None = None,
        use_state_db_only: bool | None = None,
    ) -> ThreadListResponse:
        """List stored threads with pagination.

        Args:
            cursor: Opaque pagination cursor from previous response
            limit: Maximum number of threads to return
            sort_key: Sort key (created_at or updated_at)
            model_providers: Filter by model providers
            source_kinds: Filter by source kinds
            archived: If true, only return archived threads
            cwd: Filter by working directory
            search_term: Substring filter for thread title
            sort_direction: Sort direction (asc or desc)
            use_state_db_only: If true, only return threads from the state DB

        Returns:
            ThreadListResponse with data (list of threads) and next_cursor
        """
        params = ThreadListParams(
            cursor=cursor,
            limit=limit,
            sort_key=sort_key,
            model_providers=model_providers,
            source_kinds=source_kinds,
            archived=archived,
            cwd=cwd,
            search_term=search_term,
            sort_direction=sort_direction,
            use_state_db_only=use_state_db_only,
        )
        result = await self.dispatch.send_request("thread/list", params)
        return ThreadListResponse.model_validate(result)

    async def thread_loaded_list(
        self,
        *,
        cursor: str | None = None,
        limit: int | None = None,
    ) -> ThreadLoadedListResponse:
        """List thread IDs currently loaded in memory.

        Args:
            cursor: Opaque pagination cursor from previous response
            limit: Maximum number of thread IDs to return

        Returns:
            ThreadLoadedListResponse with data (list of thread IDs) and next_cursor
        """
        params = ThreadLoadedListParams(cursor=cursor, limit=limit)
        result = await self.dispatch.send_request("thread/loaded/list", params)
        return ThreadLoadedListResponse.model_validate(result)

    # ========================================================================
    # Model methods
    # ========================================================================

    async def model_list(
        self,
        *,
        include_hidden: bool | None = None,
        cursor: str | None = None,
        limit: int | None = None,
    ) -> ModelListResponse:
        """List available models with reasoning effort options.

        Args:
            include_hidden: When true, include hidden models
            cursor: Opaque pagination cursor from previous response
            limit: Maximum number of models to return

        Returns:
            ModelListResponse with data (list of models) and next_cursor
        """
        params = ModelListParams(include_hidden=include_hidden, cursor=cursor, limit=limit)
        result = await self.dispatch.send_request("model/list", params)
        return ModelListResponse.model_validate(result)

    async def collaboration_mode_list(self) -> list[CollaborationModeMask]:
        """List available collaboration mode presets (experimental).

        Returns:
            List of collaboration mode presets with name, mode, model, and effort
        """
        result = await self.dispatch.send_request("collaborationMode/list")
        response = CollaborationModeListResponse.model_validate(result)
        return response.data

    # ========================================================================
    # Command execution
    # ========================================================================

    async def command_exec(
        self,
        command: list[str],
        *,
        cwd: str | None = None,
        sandbox_policy: SandboxPolicy | None = None,
        output_bytes_cap: int | None = None,
        timeout_ms: int | None = None,
        permission_profile: str | None = None,
    ) -> CommandExecResponse:
        """Execute a command without creating a thread/turn.

        Args:
            command: Command and arguments as list (e.g., ["ls", "-la"])
            cwd: Working directory for command
            sandbox_policy: Sandbox policy override
            output_bytes_cap: Cap output based on bytes
            timeout_ms: Timeout in milliseconds
            permission_profile: Named permissions profile ID
                (cannot be combined with sandbox_policy)

        Returns:
            CommandExecResponse with exit_code, stdout, stderr
        """
        params = CommandExecParams(
            command=command,
            cwd=cwd,
            output_bytes_cap=output_bytes_cap,
            sandbox_policy=sandbox_policy,
            timeout_ms=timeout_ms,
            permission_profile=permission_profile,
        )
        result = await self.dispatch.send_request("command/exec", params)
        return CommandExecResponse.model_validate(result)

    # ========================================================================
    # MCP server methods
    # ========================================================================

    async def mcp_server_refresh(self) -> None:
        """Reload MCP server configurations from disk."""
        await self.dispatch.send_request("config/mcpServer/reload")

    async def mcp_server_status_list(
        self,
        *,
        detail: McpServerStatusDetail | None = None,
        cursor: str | None = None,
        limit: int | None = None,
    ) -> ListMcpServerStatusResponse:
        """List MCP server status with tool and resource information.

        Args:
            detail: Level of detail to include in the response
            cursor: Pagination cursor from previous call
            limit: Maximum number of servers to return

        Returns:
            Response with server status entries and optional next_cursor
        """
        params = ListMcpServerStatusParams(cursor=cursor, limit=limit, detail=detail)
        result = await self.dispatch.send_request("mcpServerStatus/list", params)
        return ListMcpServerStatusResponse.model_validate(result)

    async def mcp_server_oauth_login(
        self,
        name: str,
        *,
        scopes: list[str] | None = None,
        timeout_secs: int | None = None,
    ) -> str:
        """Start OAuth login for an MCP server.

        Args:
            name: Name of the MCP server
            scopes: Optional OAuth scopes to request
            timeout_secs: Optional timeout in seconds

        Returns:
            Authorization URL
        """
        params = McpServerOauthLoginParams(name=name, scopes=scopes, timeout_secs=timeout_secs)
        result = await self.dispatch.send_request("mcpServer/oauth/login", params)
        response = McpServerOauthLoginResponse.model_validate(result)
        return response.authorization_url

    async def read_resource(self, server: str, uri: str) -> list[ResourceContents]:
        """Read a resource from the MCP server."""
        params = McpResourceReadParams(server=server, uri=uri)
        result = await self.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]

    # ========================================================================
    # Config methods
    # ========================================================================

    async def config_read(
        self,
        *,
        include_layers: bool = False,
        cwd: str | None = None,
    ) -> ConfigReadResponse:
        """Read configuration.

        Args:
            include_layers: Whether to include config layer details
            cwd: Optional working directory for project config resolution

        Returns:
            ConfigReadResponse with config data
        """
        params = ConfigReadParams(include_layers=include_layers, cwd=cwd)
        result = await self.dispatch.send_request("config/read", params)
        return ConfigReadResponse.model_validate(result)

    async def config_value_write(
        self,
        key_path: str,
        value: Any,
        merge_strategy: MergeStrategy,
        *,
        file_path: str | None = None,
        expected_version: str | None = None,
    ) -> ConfigWriteResponse:
        """Write a config value.

        Args:
            key_path: Dotted key path (e.g., "model")
            value: Value to write
            merge_strategy: How to merge (replace or merge)
            file_path: Optional config file path
            expected_version: Optional expected version for optimistic locking

        Returns:
            ConfigWriteResponse with status
        """
        params = ConfigValueWriteParams(
            key_path=key_path,
            value=value,
            merge_strategy=merge_strategy,
            file_path=file_path,
            expected_version=expected_version,
        )
        result = await self.dispatch.send_request("config/value/write", params)
        return ConfigWriteResponse.model_validate(result)

    async def config_batch_write(
        self,
        edits: list[ConfigEdit],
        *,
        file_path: str | None = None,
        expected_version: str | None = None,
    ) -> ConfigWriteResponse:
        """Batch write config values.

        Args:
            edits: List of ConfigEdit objects
            file_path: Optional config file path
            expected_version: Optional expected version for optimistic locking

        Returns:
            ConfigWriteResponse with status
        """
        params = ConfigBatchWriteParams(
            edits=edits,
            file_path=file_path,
            expected_version=expected_version,
        )
        result = await self.dispatch.send_request("config/batchWrite", params)
        return ConfigWriteResponse.model_validate(result)

    async def config_requirements_read(self) -> ConfigRequirements | None:
        """Read config requirements."""
        result = await self.dispatch.send_request("configRequirements/read")
        response = ConfigRequirementsReadResponse.model_validate(result)
        return response.requirements

    # ========================================================================
    # Apps methods
    # ========================================================================

    async def apps_list(
        self,
        *,
        cursor: str | None = None,
        limit: int | None = None,
        thread_id: str | None = None,
        force_refetch: bool | None = None,
    ) -> list[AppInfo]:
        """List available apps/connectors.

        Args:
            cursor: Pagination cursor
            limit: Maximum number of apps to return
            thread_id: Optional thread ID for feature gating
            force_refetch: Bypass caches and fetch latest

        Returns:
            List of AppInfo objects
        """
        params = AppsListParams(
            cursor=cursor,
            limit=limit,
            thread_id=thread_id,
            force_refetch=force_refetch,
        )
        result = await self.dispatch.send_request("app/list", params)
        response = AppsListResponse.model_validate(result)
        return response.data

    # ========================================================================
    # Experimental feature methods
    # ========================================================================

    async def experimental_feature_list(
        self,
        *,
        cursor: str | None = None,
        limit: int | None = None,
    ) -> list[ExperimentalFeature]:
        """List experimental features.

        Args:
            cursor: Pagination cursor
            limit: Maximum number of features to return

        Returns:
            List of ExperimentalFeature objects
        """
        params = ExperimentalFeatureListParams(cursor=cursor, limit=limit)
        result = await self.dispatch.send_request("experimentalFeature/list", params)
        response = ExperimentalFeatureListResponse.model_validate(result)
        return response.data

    # ========================================================================
    # Feedback methods
    # ========================================================================

    async def feedback_upload(
        self,
        classification: str,
        *,
        reason: str | None = None,
        thread_id: str | None = None,
        tags: dict[str, Any] | None = None,
        include_logs: bool = False,
        extra_log_files: list[str] | None = None,
    ) -> str:
        """Upload feedback.

        Args:
            classification: Feedback classification
            reason: Optional reason text
            thread_id: Optional thread ID to associate
            tags: Optional tags to associate with the feedback
            include_logs: Whether to include logs
            extra_log_files: Additional log files to include

        Returns:
            thread ID
        """
        params = FeedbackUploadParams(
            classification=classification,
            reason=reason,
            thread_id=thread_id,
            tags=tags,
            include_logs=include_logs,
            extra_log_files=extra_log_files,
        )
        result = await self.dispatch.send_request("feedback/upload", params)
        response = FeedbackUploadResponse.model_validate(result)
        return response.thread_id

    # ========================================================================
    # External agent config methods
    # ========================================================================

    async def external_agent_config_detect(
        self,
        *,
        include_home: bool | None = None,
        cwds: list[str] | None = None,
    ) -> list[ExternalAgentConfigMigrationItem]:
        """Detect external agent configurations.

        Args:
            include_home: Include detection under user's home directory
            cwds: Working directories for repo-scoped detection

        Returns:
            ExternalAgentConfigDetectResponse with migration items
        """
        params = ExternalAgentConfigDetectParams(include_home=include_home, cwds=cwds)
        result = await self.dispatch.send_request("externalAgentConfig/detect", params)
        response = ExternalAgentConfigDetectResponse.model_validate(result)
        return response.items

    async def external_agent_config_import(
        self,
        migration_items: list[ExternalAgentConfigMigrationItem],
    ) -> None:
        """Import external agent configurations.

        Args:
            migration_items: List of migration items to import
        """
        params = ExternalAgentConfigImportParams(migration_items=migration_items)
        await self.dispatch.send_request("externalAgentConfig/import", params)

    # ========================================================================
    # Internal: JSON-RPC dispatch callbacks
    # ========================================================================

    async def _handle_notification(self, method: str, params: dict[str, Any]) -> None:
        """Route a JSON-RPC notification to the appropriate event queue."""
        if method.startswith("codex/event/"):
            return

        event_data = {"method": method, "params": params}
        event = codex_event_adapter.validate_python(event_data)
        if isinstance(event, AccountRateLimitsUpdatedMessage):
            self.account.rate_limits = event.params.rate_limits

        thread_id = params.get("threadId")

        # Route realtime events to the realtime session queue
        if method.startswith("thread/realtime/") and thread_id:
            rt_key = f"realtime:{thread_id}"
            if (queue := self._realtime_queues.get(rt_key)) is not None:
                await queue.put(event)
            else:
                await self._notify_listeners(event)
            return

        turn_id = params.get("turnId")
        if not turn_id and "turn" in params:
            turn_id = params.get("turn", {}).get("id")

        turn_key = f"{thread_id}:{turn_id}" if thread_id and turn_id else None
        turn_queue = self._turn_queues.get(turn_key) if turn_key else None
        if turn_queue is not None:
            await turn_queue.put(event)
        elif turn_key and self._pending_turn_starts:
            self._turn_buffer.append((turn_key, event))
        else:
            await self._notify_listeners(event)

    def _begin_turn_start(self) -> None:
        """Buffer unrouted turn events until :meth:`_end_turn_start` (call before sending)."""
        self._pending_turn_starts += 1

    async def _end_turn_start(
        self, turn_key: str | None, queue: asyncio.Queue[CodexEvent | None]
    ) -> None:
        """Register the turn's queue (if the start succeeded) with its buffered events.

        Registering and claiming happen without a suspension point in between, so no
        event can slip past the queue. Once no start is pending, events no turn claimed
        go to the listeners.
        """
        if turn_key is not None:
            self._turn_queues[turn_key] = queue
            rest: list[tuple[str, CodexEvent]] = []
            for key, event in self._turn_buffer:
                if key == turn_key:
                    queue.put_nowait(event)
                else:
                    rest.append((key, event))
            self._turn_buffer = rest
            if self.dispatch.closed_error is not None:
                queue.put_nowait(None)  # the connection ended before the queue existed
        self._pending_turn_starts -= 1
        if not self._pending_turn_starts and self._turn_buffer:
            leftovers, self._turn_buffer = self._turn_buffer, []
            for _, event in leftovers:
                await self._notify_listeners(event)

    def _handle_close(self, error: Exception) -> None:
        """End every turn and realtime stream: no more events will come."""
        logger.debug("Ending open streams: %s", error)
        for queue in [*self._turn_queues.values(), *self._realtime_queues.values()]:
            queue.put_nowait(None)

    def add_event_listener(self, listener: EventListener) -> None:
        """Receive events that belong to no running turn (account, config, app updates, ...).

        Turn events go to the turn's stream; everything else is passed to the listeners
        (and otherwise dropped). Listeners run inside the read loop, in event order: they
        must return quickly and must not await client requests (that would deadlock).
        """
        self._event_listeners.append(listener)

    def remove_event_listener(self, listener: EventListener) -> None:
        """Stop passing events to a listener added with :meth:`add_event_listener`."""
        self._event_listeners.remove(listener)

    async def _notify_listeners(self, event: CodexEvent) -> None:
        for listener in list(self._event_listeners):
            try:
                result = listener(event)
                if inspect.isawaitable(result):
                    await result
            except Exception:
                logger.exception("Codex event listener failed for %s", event.method)

    async def _handle_server_request(
        self, method: str, request_id: int | str, params: dict[str, Any]
    ) -> None:
        """Handle a server-initiated JSON-RPC request."""
        type_entry = SERVER_REQUEST_TYPES.get(method)
        if type_entry is None:
            logger.warning("Unhandled server request method: %s (id=%s)", method, request_id)
            await self.dispatch.send_error(request_id, -32601, f"Method not found: {method}")
            return

        handler = self._server_request_handlers.get(method)
        if handler is None:
            logger.warning("No handler registered for request: %s (id=%s)", method, request_id)
            await self.dispatch.send_error(request_id, -32603, f"No handler for: {method}")
            return

        params_type, _ = type_entry
        try:
            if isinstance(params_type, TypeAdapter):
                parsed_params = params_type.validate_python(params)
            else:
                parsed_params = params_type.model_validate(params)
            response_model = await handler(parsed_params)
            result = response_model.model_dump(by_alias=True, exclude_none=True)
            await self.dispatch.send_response(request_id, result)
        except Exception:
            logger.exception("Error handling server request %s (id=%s)", method, request_id)
            await self.dispatch.send_error(request_id, -32603, f"Internal error handling {method}")

    # ========================================================================
    # Server request handler registration
    # ========================================================================

    def register_handler(self, method: HandlerMethod, handler: ServerRequestHandler) -> None:
        """Register a handler for a server request method.

        The handler receives the parsed params model and must return
        the appropriate response model.

        Args:
            method: Server request method name (use SERVER_REQUEST_* constants)
            handler: Async callback that processes the request and returns a response
        """
        if method not in SERVER_REQUEST_TYPES:
            msg = (
                f"Unknown server request method: {method}. "
                f"Valid methods: {list(SERVER_REQUEST_TYPES)}"
            )
            raise ValueError(msg)
        self._server_request_handlers[method] = handler

    def set_auto_approve(self) -> None:
        """Register default handlers that auto-approve all server requests.

        Convenience method for non-interactive use cases where all approvals
        should be automatically granted and tool calls return empty results.
        """
        self._server_request_handlers = create_auto_approve_dict()

    async def reset_memory(self) -> MemoryResetResponse:
        """Reset the app-server memory."""
        response = await self.dispatch.send_request("memory/reset")
        return MemoryResetResponse.model_validate(response)

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

__aenter__ async

__aenter__() -> Self

Async context manager entry - starts the app-server.

Source code in src/codexed/client/client.py
async def __aenter__(self) -> Self:
    """Async context manager entry - starts the app-server."""
    import codexed
    from codexed.models import ClientInfo, InitializeCapabilities, InitializeParams

    await self.dispatch.start()
    version = codexed.__version__
    init_params = InitializeParams(
        client_info=ClientInfo(name="codexed", version=version),
        capabilities=InitializeCapabilities(experimental_api=True),
    )
    await self.dispatch.send_request("initialize", init_params)
    return self

__aexit__ async

__aexit__(*_args: object) -> None

Async context manager exit - stops the app-server.

Source code in src/codexed/client/client.py
async def __aexit__(self, *_args: object) -> None:
    """Async context manager exit - stops the app-server."""
    await self.dispatch.stop()

__init__

__init__(
    codex_command: str = "codex",
    profile: str | None = None,
    env_vars: dict[str, str] | None = None,
    mcp_servers: Mapping[str, McpServerConfig] | None = None,
    on_approval: ApprovalHandler | None = None,
    on_user_input: UserInputHandler | None = None,
    on_dynamic_tool_call: DynamicToolCallHandler | None = None,
    on_mcp_elicitation: McpElicitationHandler | None = None,
    mcp_elicitation_for_approvals: bool = False,
    transport: Transport | None = None,
) -> None

Initialize the Codex app-server client.

Parameters:

Name Type Description Default
codex_command str

Path to the codex binary (default: "codex")

'codex'
profile str | None

Optional Codex profile to use

None
env_vars dict[str, str] | None

Optional environment variables to set for the Codex process.

None
mcp_servers Mapping[str, McpServerConfig] | None

Optional MCP servers to inject programmatically. Keys are server names, values are server configurations.

None
on_approval ApprovalHandler | None

Handler for all approval requests (command execution, file change, and skill approval).

None
on_user_input UserInputHandler | None

Handler for tool user input requests.

None
on_dynamic_tool_call DynamicToolCallHandler | None

Handler for dynamic tool call requests.

None
on_mcp_elicitation McpElicitationHandler | None

Handler for MCP elicitation requests.

None
mcp_elicitation_for_approvals bool

If True, enables the Codex tool_call_mcp_elicitation feature flag which routes MCP tool approval prompts through mcpServer/elicitation/request instead of item/tool/requestUserInput. Requires on_mcp_elicitation to handle approvals (the schema is empty; context is in _meta). Default is False because the default elicitation handler auto-declines, which would break MCP tool approvals.

False
transport Transport | None

Pre-configured transport instance. If provided, codex_command, profile, env_vars, and mcp_servers are ignored (they are only used to build the default StdioTransport). Pass a WebSocketTransport here to connect to a remote app-server.

None
Source code in src/codexed/client/client.py
def __init__(
    self,
    codex_command: str = "codex",
    profile: str | None = None,
    env_vars: dict[str, str] | None = None,
    mcp_servers: Mapping[str, McpServerConfig] | None = None,
    on_approval: ApprovalHandler | None = None,
    on_user_input: UserInputHandler | None = None,
    on_dynamic_tool_call: DynamicToolCallHandler | None = None,
    on_mcp_elicitation: McpElicitationHandler | None = None,
    mcp_elicitation_for_approvals: bool = False,
    transport: Transport | None = None,
) -> None:
    """Initialize the Codex app-server client.

    Args:
        codex_command: Path to the codex binary (default: "codex")
        profile: Optional Codex profile to use
        env_vars: Optional environment variables to set for the Codex process.
        mcp_servers: Optional MCP servers to inject programmatically.
            Keys are server names, values are server configurations.
        on_approval: Handler for all approval requests
            (command execution, file change, and skill approval).
        on_user_input: Handler for tool user input requests.
        on_dynamic_tool_call: Handler for dynamic tool call requests.
        on_mcp_elicitation: Handler for MCP elicitation requests.
        mcp_elicitation_for_approvals: If True, enables the Codex
            ``tool_call_mcp_elicitation`` feature flag which routes MCP tool
            approval prompts through ``mcpServer/elicitation/request`` instead
            of ``item/tool/requestUserInput``.  Requires *on_mcp_elicitation*
            to handle approvals (the schema is empty; context is in ``_meta``).
            Default is False because the default elicitation handler auto-declines,
            which would break MCP tool approvals.
        transport: Pre-configured transport instance. If provided,
            ``codex_command``, ``profile``, ``env_vars``, and ``mcp_servers``
            are ignored (they are only used to build the default
            ``StdioTransport``).  Pass a ``WebSocketTransport`` here to
            connect to a remote app-server.
    """
    tp = transport or StdioTransport(
        command=codex_command,
        profile=profile,
        env_vars=env_vars,
        mcp_servers=mcp_servers,
    )
    self.dispatch = Dispatch(
        tp,
        on_notification=self._handle_notification,
        on_server_request=self._handle_server_request,
        on_close=self._handle_close,
    )
    self._turn_queues: dict[str, asyncio.Queue[CodexEvent | None]] = {}
    # Turn events that arrive while a turn/start (or review/start) request is pending
    # and have no queue yet: the response and the first events can come in one read.
    self._pending_turn_starts = 0
    self._turn_buffer: list[tuple[str, CodexEvent]] = []
    self._realtime_queues: dict[str, asyncio.Queue[CodexEvent | None]] = {}
    self._event_listeners: list[EventListener] = []
    self._active_threads: set[str] = set()
    self._mcp_elicitation_enabled = on_mcp_elicitation is not None
    self._mcp_elicitation_for_approvals = mcp_elicitation_for_approvals
    self._server_request_handlers: dict[str, ServerRequestHandler] = {}
    self.account = CodexAccount(self)
    self.fs = CodexFS(self)
    self.plugins = CodexPlugin(self)
    self.marketplace = CodexMarketPlace(self)
    self.skills = CodexSkills(self)
    if on_approval:
        self.register_handler(SERVER_REQUEST_COMMAND_APPROVAL, on_approval)  # ty: ignore[invalid-argument-type]
        self.register_handler(SERVER_REQUEST_FILE_CHANGE_APPROVAL, on_approval)  # ty: ignore[invalid-argument-type]
        self.register_handler(SERVER_REQUEST_SKILL_APPROVAL, on_approval)  # ty: ignore[invalid-argument-type]
    if on_user_input:
        self.register_handler(SERVER_REQUEST_USER_INPUT, on_user_input)  # ty: ignore[invalid-argument-type]
    if on_dynamic_tool_call:
        self.register_handler(SERVER_REQUEST_DYNAMIC_TOOL_CALL, on_dynamic_tool_call)  # ty: ignore[invalid-argument-type]
    if on_mcp_elicitation:
        self.register_handler(SERVER_REQUEST_MCP_ELICITATION, on_mcp_elicitation)  # ty: ignore[invalid-argument-type]

add_event_listener

add_event_listener(listener: EventListener) -> None

Receive events that belong to no running turn (account, config, app updates, ...).

Turn events go to the turn's stream; everything else is passed to the listeners (and otherwise dropped). Listeners run inside the read loop, in event order: they must return quickly and must not await client requests (that would deadlock).

Source code in src/codexed/client/client.py
def add_event_listener(self, listener: EventListener) -> None:
    """Receive events that belong to no running turn (account, config, app updates, ...).

    Turn events go to the turn's stream; everything else is passed to the listeners
    (and otherwise dropped). Listeners run inside the read loop, in event order: they
    must return quickly and must not await client requests (that would deadlock).
    """
    self._event_listeners.append(listener)

apps_list async

apps_list(
    *,
    cursor: str | None = None,
    limit: int | None = None,
    thread_id: str | None = None,
    force_refetch: bool | None = None,
) -> list[AppInfo]

List available apps/connectors.

Parameters:

Name Type Description Default
cursor str | None

Pagination cursor

None
limit int | None

Maximum number of apps to return

None
thread_id str | None

Optional thread ID for feature gating

None
force_refetch bool | None

Bypass caches and fetch latest

None

Returns:

Type Description
list[AppInfo]

List of AppInfo objects

Source code in src/codexed/client/client.py
async def apps_list(
    self,
    *,
    cursor: str | None = None,
    limit: int | None = None,
    thread_id: str | None = None,
    force_refetch: bool | None = None,
) -> list[AppInfo]:
    """List available apps/connectors.

    Args:
        cursor: Pagination cursor
        limit: Maximum number of apps to return
        thread_id: Optional thread ID for feature gating
        force_refetch: Bypass caches and fetch latest

    Returns:
        List of AppInfo objects
    """
    params = AppsListParams(
        cursor=cursor,
        limit=limit,
        thread_id=thread_id,
        force_refetch=force_refetch,
    )
    result = await self.dispatch.send_request("app/list", params)
    response = AppsListResponse.model_validate(result)
    return response.data

collaboration_mode_list async

collaboration_mode_list() -> list[CollaborationModeMask]

List available collaboration mode presets (experimental).

Returns:

Type Description
list[CollaborationModeMask]

List of collaboration mode presets with name, mode, model, and effort

Source code in src/codexed/client/client.py
async def collaboration_mode_list(self) -> list[CollaborationModeMask]:
    """List available collaboration mode presets (experimental).

    Returns:
        List of collaboration mode presets with name, mode, model, and effort
    """
    result = await self.dispatch.send_request("collaborationMode/list")
    response = CollaborationModeListResponse.model_validate(result)
    return response.data

command_exec async

command_exec(
    command: list[str],
    *,
    cwd: str | None = None,
    sandbox_policy: SandboxPolicy | None = None,
    output_bytes_cap: int | None = None,
    timeout_ms: int | None = None,
    permission_profile: str | None = None,
) -> CommandExecResponse

Execute a command without creating a thread/turn.

Parameters:

Name Type Description Default
command list[str]

Command and arguments as list (e.g., ["ls", "-la"])

required
cwd str | None

Working directory for command

None
sandbox_policy SandboxPolicy | None

Sandbox policy override

None
output_bytes_cap int | None

Cap output based on bytes

None
timeout_ms int | None

Timeout in milliseconds

None
permission_profile str | None

Named permissions profile ID (cannot be combined with sandbox_policy)

None

Returns:

Type Description
CommandExecResponse

CommandExecResponse with exit_code, stdout, stderr

Source code in src/codexed/client/client.py
async def command_exec(
    self,
    command: list[str],
    *,
    cwd: str | None = None,
    sandbox_policy: SandboxPolicy | None = None,
    output_bytes_cap: int | None = None,
    timeout_ms: int | None = None,
    permission_profile: str | None = None,
) -> CommandExecResponse:
    """Execute a command without creating a thread/turn.

    Args:
        command: Command and arguments as list (e.g., ["ls", "-la"])
        cwd: Working directory for command
        sandbox_policy: Sandbox policy override
        output_bytes_cap: Cap output based on bytes
        timeout_ms: Timeout in milliseconds
        permission_profile: Named permissions profile ID
            (cannot be combined with sandbox_policy)

    Returns:
        CommandExecResponse with exit_code, stdout, stderr
    """
    params = CommandExecParams(
        command=command,
        cwd=cwd,
        output_bytes_cap=output_bytes_cap,
        sandbox_policy=sandbox_policy,
        timeout_ms=timeout_ms,
        permission_profile=permission_profile,
    )
    result = await self.dispatch.send_request("command/exec", params)
    return CommandExecResponse.model_validate(result)

config_batch_write async

config_batch_write(
    edits: list[ConfigEdit], *, file_path: str | None = None, expected_version: str | None = None
) -> ConfigWriteResponse

Batch write config values.

Parameters:

Name Type Description Default
edits list[ConfigEdit]

List of ConfigEdit objects

required
file_path str | None

Optional config file path

None
expected_version str | None

Optional expected version for optimistic locking

None

Returns:

Type Description
ConfigWriteResponse

ConfigWriteResponse with status

Source code in src/codexed/client/client.py
async def config_batch_write(
    self,
    edits: list[ConfigEdit],
    *,
    file_path: str | None = None,
    expected_version: str | None = None,
) -> ConfigWriteResponse:
    """Batch write config values.

    Args:
        edits: List of ConfigEdit objects
        file_path: Optional config file path
        expected_version: Optional expected version for optimistic locking

    Returns:
        ConfigWriteResponse with status
    """
    params = ConfigBatchWriteParams(
        edits=edits,
        file_path=file_path,
        expected_version=expected_version,
    )
    result = await self.dispatch.send_request("config/batchWrite", params)
    return ConfigWriteResponse.model_validate(result)

config_read async

config_read(*, include_layers: bool = False, cwd: str | None = None) -> ConfigReadResponse

Read configuration.

Parameters:

Name Type Description Default
include_layers bool

Whether to include config layer details

False
cwd str | None

Optional working directory for project config resolution

None

Returns:

Type Description
ConfigReadResponse

ConfigReadResponse with config data

Source code in src/codexed/client/client.py
async def config_read(
    self,
    *,
    include_layers: bool = False,
    cwd: str | None = None,
) -> ConfigReadResponse:
    """Read configuration.

    Args:
        include_layers: Whether to include config layer details
        cwd: Optional working directory for project config resolution

    Returns:
        ConfigReadResponse with config data
    """
    params = ConfigReadParams(include_layers=include_layers, cwd=cwd)
    result = await self.dispatch.send_request("config/read", params)
    return ConfigReadResponse.model_validate(result)

config_requirements_read async

config_requirements_read() -> ConfigRequirements | None

Read config requirements.

Source code in src/codexed/client/client.py
async def config_requirements_read(self) -> ConfigRequirements | None:
    """Read config requirements."""
    result = await self.dispatch.send_request("configRequirements/read")
    response = ConfigRequirementsReadResponse.model_validate(result)
    return response.requirements

config_value_write async

config_value_write(
    key_path: str,
    value: Any,
    merge_strategy: MergeStrategy,
    *,
    file_path: str | None = None,
    expected_version: str | None = None,
) -> ConfigWriteResponse

Write a config value.

Parameters:

Name Type Description Default
key_path str

Dotted key path (e.g., "model")

required
value Any

Value to write

required
merge_strategy MergeStrategy

How to merge (replace or merge)

required
file_path str | None

Optional config file path

None
expected_version str | None

Optional expected version for optimistic locking

None

Returns:

Type Description
ConfigWriteResponse

ConfigWriteResponse with status

Source code in src/codexed/client/client.py
async def config_value_write(
    self,
    key_path: str,
    value: Any,
    merge_strategy: MergeStrategy,
    *,
    file_path: str | None = None,
    expected_version: str | None = None,
) -> ConfigWriteResponse:
    """Write a config value.

    Args:
        key_path: Dotted key path (e.g., "model")
        value: Value to write
        merge_strategy: How to merge (replace or merge)
        file_path: Optional config file path
        expected_version: Optional expected version for optimistic locking

    Returns:
        ConfigWriteResponse with status
    """
    params = ConfigValueWriteParams(
        key_path=key_path,
        value=value,
        merge_strategy=merge_strategy,
        file_path=file_path,
        expected_version=expected_version,
    )
    result = await self.dispatch.send_request("config/value/write", params)
    return ConfigWriteResponse.model_validate(result)

experimental_feature_list async

experimental_feature_list(
    *, cursor: str | None = None, limit: int | None = None
) -> list[ExperimentalFeature]

List experimental features.

Parameters:

Name Type Description Default
cursor str | None

Pagination cursor

None
limit int | None

Maximum number of features to return

None

Returns:

Type Description
list[ExperimentalFeature]

List of ExperimentalFeature objects

Source code in src/codexed/client/client.py
async def experimental_feature_list(
    self,
    *,
    cursor: str | None = None,
    limit: int | None = None,
) -> list[ExperimentalFeature]:
    """List experimental features.

    Args:
        cursor: Pagination cursor
        limit: Maximum number of features to return

    Returns:
        List of ExperimentalFeature objects
    """
    params = ExperimentalFeatureListParams(cursor=cursor, limit=limit)
    result = await self.dispatch.send_request("experimentalFeature/list", params)
    response = ExperimentalFeatureListResponse.model_validate(result)
    return response.data

external_agent_config_detect async

external_agent_config_detect(
    *, include_home: bool | None = None, cwds: list[str] | None = None
) -> list[ExternalAgentConfigMigrationItem]

Detect external agent configurations.

Parameters:

Name Type Description Default
include_home bool | None

Include detection under user's home directory

None
cwds list[str] | None

Working directories for repo-scoped detection

None

Returns:

Type Description
list[ExternalAgentConfigMigrationItem]

ExternalAgentConfigDetectResponse with migration items

Source code in src/codexed/client/client.py
async def external_agent_config_detect(
    self,
    *,
    include_home: bool | None = None,
    cwds: list[str] | None = None,
) -> list[ExternalAgentConfigMigrationItem]:
    """Detect external agent configurations.

    Args:
        include_home: Include detection under user's home directory
        cwds: Working directories for repo-scoped detection

    Returns:
        ExternalAgentConfigDetectResponse with migration items
    """
    params = ExternalAgentConfigDetectParams(include_home=include_home, cwds=cwds)
    result = await self.dispatch.send_request("externalAgentConfig/detect", params)
    response = ExternalAgentConfigDetectResponse.model_validate(result)
    return response.items

external_agent_config_import async

external_agent_config_import(migration_items: list[ExternalAgentConfigMigrationItem]) -> None

Import external agent configurations.

Parameters:

Name Type Description Default
migration_items list[ExternalAgentConfigMigrationItem]

List of migration items to import

required
Source code in src/codexed/client/client.py
async def external_agent_config_import(
    self,
    migration_items: list[ExternalAgentConfigMigrationItem],
) -> None:
    """Import external agent configurations.

    Args:
        migration_items: List of migration items to import
    """
    params = ExternalAgentConfigImportParams(migration_items=migration_items)
    await self.dispatch.send_request("externalAgentConfig/import", params)

feedback_upload async

feedback_upload(
    classification: str,
    *,
    reason: str | None = None,
    thread_id: str | None = None,
    tags: dict[str, Any] | None = None,
    include_logs: bool = False,
    extra_log_files: list[str] | None = None,
) -> str

Upload feedback.

Parameters:

Name Type Description Default
classification str

Feedback classification

required
reason str | None

Optional reason text

None
thread_id str | None

Optional thread ID to associate

None
tags dict[str, Any] | None

Optional tags to associate with the feedback

None
include_logs bool

Whether to include logs

False
extra_log_files list[str] | None

Additional log files to include

None

Returns:

Type Description
str

thread ID

Source code in src/codexed/client/client.py
async def feedback_upload(
    self,
    classification: str,
    *,
    reason: str | None = None,
    thread_id: str | None = None,
    tags: dict[str, Any] | None = None,
    include_logs: bool = False,
    extra_log_files: list[str] | None = None,
) -> str:
    """Upload feedback.

    Args:
        classification: Feedback classification
        reason: Optional reason text
        thread_id: Optional thread ID to associate
        tags: Optional tags to associate with the feedback
        include_logs: Whether to include logs
        extra_log_files: Additional log files to include

    Returns:
        thread ID
    """
    params = FeedbackUploadParams(
        classification=classification,
        reason=reason,
        thread_id=thread_id,
        tags=tags,
        include_logs=include_logs,
        extra_log_files=extra_log_files,
    )
    result = await self.dispatch.send_request("feedback/upload", params)
    response = FeedbackUploadResponse.model_validate(result)
    return response.thread_id

mcp_server_oauth_login async

mcp_server_oauth_login(
    name: str, *, scopes: list[str] | None = None, timeout_secs: int | None = None
) -> str

Start OAuth login for an MCP server.

Parameters:

Name Type Description Default
name str

Name of the MCP server

required
scopes list[str] | None

Optional OAuth scopes to request

None
timeout_secs int | None

Optional timeout in seconds

None

Returns:

Type Description
str

Authorization URL

Source code in src/codexed/client/client.py
async def mcp_server_oauth_login(
    self,
    name: str,
    *,
    scopes: list[str] | None = None,
    timeout_secs: int | None = None,
) -> str:
    """Start OAuth login for an MCP server.

    Args:
        name: Name of the MCP server
        scopes: Optional OAuth scopes to request
        timeout_secs: Optional timeout in seconds

    Returns:
        Authorization URL
    """
    params = McpServerOauthLoginParams(name=name, scopes=scopes, timeout_secs=timeout_secs)
    result = await self.dispatch.send_request("mcpServer/oauth/login", params)
    response = McpServerOauthLoginResponse.model_validate(result)
    return response.authorization_url

mcp_server_refresh async

mcp_server_refresh() -> None

Reload MCP server configurations from disk.

Source code in src/codexed/client/client.py
async def mcp_server_refresh(self) -> None:
    """Reload MCP server configurations from disk."""
    await self.dispatch.send_request("config/mcpServer/reload")

mcp_server_status_list async

mcp_server_status_list(
    *,
    detail: McpServerStatusDetail | None = None,
    cursor: str | None = None,
    limit: int | None = None,
) -> ListMcpServerStatusResponse

List MCP server status with tool and resource information.

Parameters:

Name Type Description Default
detail McpServerStatusDetail | None

Level of detail to include in the response

None
cursor str | None

Pagination cursor from previous call

None
limit int | None

Maximum number of servers to return

None

Returns:

Type Description
ListMcpServerStatusResponse

Response with server status entries and optional next_cursor

Source code in src/codexed/client/client.py
async def mcp_server_status_list(
    self,
    *,
    detail: McpServerStatusDetail | None = None,
    cursor: str | None = None,
    limit: int | None = None,
) -> ListMcpServerStatusResponse:
    """List MCP server status with tool and resource information.

    Args:
        detail: Level of detail to include in the response
        cursor: Pagination cursor from previous call
        limit: Maximum number of servers to return

    Returns:
        Response with server status entries and optional next_cursor
    """
    params = ListMcpServerStatusParams(cursor=cursor, limit=limit, detail=detail)
    result = await self.dispatch.send_request("mcpServerStatus/list", params)
    return ListMcpServerStatusResponse.model_validate(result)

model_list async

model_list(
    *, include_hidden: bool | None = None, cursor: str | None = None, limit: int | None = None
) -> ModelListResponse

List available models with reasoning effort options.

Parameters:

Name Type Description Default
include_hidden bool | None

When true, include hidden models

None
cursor str | None

Opaque pagination cursor from previous response

None
limit int | None

Maximum number of models to return

None

Returns:

Type Description
ModelListResponse

ModelListResponse with data (list of models) and next_cursor

Source code in src/codexed/client/client.py
async def model_list(
    self,
    *,
    include_hidden: bool | None = None,
    cursor: str | None = None,
    limit: int | None = None,
) -> ModelListResponse:
    """List available models with reasoning effort options.

    Args:
        include_hidden: When true, include hidden models
        cursor: Opaque pagination cursor from previous response
        limit: Maximum number of models to return

    Returns:
        ModelListResponse with data (list of models) and next_cursor
    """
    params = ModelListParams(include_hidden=include_hidden, cursor=cursor, limit=limit)
    result = await self.dispatch.send_request("model/list", params)
    return ModelListResponse.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/client.py
async def read_resource(self, server: str, uri: str) -> list[ResourceContents]:
    """Read a resource from the MCP server."""
    params = McpResourceReadParams(server=server, uri=uri)
    result = await self.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]

register_handler

register_handler(method: HandlerMethod, handler: ServerRequestHandler) -> None

Register a handler for a server request method.

The handler receives the parsed params model and must return the appropriate response model.

Parameters:

Name Type Description Default
method HandlerMethod

Server request method name (use SERVER_REQUEST_* constants)

required
handler ServerRequestHandler

Async callback that processes the request and returns a response

required
Source code in src/codexed/client/client.py
def register_handler(self, method: HandlerMethod, handler: ServerRequestHandler) -> None:
    """Register a handler for a server request method.

    The handler receives the parsed params model and must return
    the appropriate response model.

    Args:
        method: Server request method name (use SERVER_REQUEST_* constants)
        handler: Async callback that processes the request and returns a response
    """
    if method not in SERVER_REQUEST_TYPES:
        msg = (
            f"Unknown server request method: {method}. "
            f"Valid methods: {list(SERVER_REQUEST_TYPES)}"
        )
        raise ValueError(msg)
    self._server_request_handlers[method] = handler

remove_event_listener

remove_event_listener(listener: EventListener) -> None

Stop passing events to a listener added with :meth:add_event_listener.

Source code in src/codexed/client/client.py
def remove_event_listener(self, listener: EventListener) -> None:
    """Stop passing events to a listener added with :meth:`add_event_listener`."""
    self._event_listeners.remove(listener)

reset_memory async

reset_memory() -> MemoryResetResponse

Reset the app-server memory.

Source code in src/codexed/client/client.py
async def reset_memory(self) -> MemoryResetResponse:
    """Reset the app-server memory."""
    response = await self.dispatch.send_request("memory/reset")
    return MemoryResetResponse.model_validate(response)

set_auto_approve

set_auto_approve() -> None

Register default handlers that auto-approve all server requests.

Convenience method for non-interactive use cases where all approvals should be automatically granted and tool calls return empty results.

Source code in src/codexed/client/client.py
def set_auto_approve(self) -> None:
    """Register default handlers that auto-approve all server requests.

    Convenience method for non-interactive use cases where all approvals
    should be automatically granted and tool calls return empty results.
    """
    self._server_request_handlers = create_auto_approve_dict()

thread_fork async

thread_fork(
    thread_id: str,
    *,
    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 an existing thread into a new thread with copied history.

Parameters:

Name Type Description Default
thread_id str

ID of the thread to fork

required
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
personality

Personality for forked thread

required
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/client.py
async def thread_fork(
    self,
    thread_id: str,
    *,
    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 an existing thread into a new thread with copied history.

    Args:
        thread_id: ID of the thread to fork
        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
        personality: Personality for forked thread
        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
    """
    from codexed.client.session import Session

    cfg = merge_config(
        config,
        tools,
        code_mode,
        mcp_servers,
        mcp_elicitation_for_approvals=self._mcp_elicitation_for_approvals,
    )
    params = ThreadForkParams(
        thread_id=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=cfg,
        service_tier=service_tier,
        ephemeral=ephemeral,
        last_turn_id=last_turn_id,
        before_turn_id=before_turn_id,
        exclude_turns=exclude_turns,
        permissions=permissions,
    )
    result = await self.dispatch.send_request("thread/fork", params)
    response = ThreadResponse.model_validate(result)
    self._active_threads.add(response.thread.id)
    return Session(self, response)

thread_list async

thread_list(
    *,
    cursor: str | None = None,
    limit: int | None = None,
    sort_key: ThreadSortKey | None = None,
    model_providers: list[str] | None = None,
    source_kinds: list[ThreadSourceKind] | None = None,
    archived: bool | None = None,
    cwd: ThreadListCwdFilter | None = None,
    search_term: str | None = None,
    sort_direction: SortDirection | None = None,
    use_state_db_only: bool | None = None,
) -> ThreadListResponse

List stored threads with pagination.

Parameters:

Name Type Description Default
cursor str | None

Opaque pagination cursor from previous response

None
limit int | None

Maximum number of threads to return

None
sort_key ThreadSortKey | None

Sort key (created_at or updated_at)

None
model_providers list[str] | None

Filter by model providers

None
source_kinds list[ThreadSourceKind] | None

Filter by source kinds

None
archived bool | None

If true, only return archived threads

None
cwd ThreadListCwdFilter | None

Filter by working directory

None
search_term str | None

Substring filter for thread title

None
sort_direction SortDirection | None

Sort direction (asc or desc)

None
use_state_db_only bool | None

If true, only return threads from the state DB

None

Returns:

Type Description
ThreadListResponse

ThreadListResponse with data (list of threads) and next_cursor

Source code in src/codexed/client/client.py
async def thread_list(
    self,
    *,
    cursor: str | None = None,
    limit: int | None = None,
    sort_key: ThreadSortKey | None = None,
    model_providers: list[str] | None = None,
    source_kinds: list[ThreadSourceKind] | None = None,
    archived: bool | None = None,
    cwd: ThreadListCwdFilter | None = None,
    search_term: str | None = None,
    sort_direction: SortDirection | None = None,
    use_state_db_only: bool | None = None,
) -> ThreadListResponse:
    """List stored threads with pagination.

    Args:
        cursor: Opaque pagination cursor from previous response
        limit: Maximum number of threads to return
        sort_key: Sort key (created_at or updated_at)
        model_providers: Filter by model providers
        source_kinds: Filter by source kinds
        archived: If true, only return archived threads
        cwd: Filter by working directory
        search_term: Substring filter for thread title
        sort_direction: Sort direction (asc or desc)
        use_state_db_only: If true, only return threads from the state DB

    Returns:
        ThreadListResponse with data (list of threads) and next_cursor
    """
    params = ThreadListParams(
        cursor=cursor,
        limit=limit,
        sort_key=sort_key,
        model_providers=model_providers,
        source_kinds=source_kinds,
        archived=archived,
        cwd=cwd,
        search_term=search_term,
        sort_direction=sort_direction,
        use_state_db_only=use_state_db_only,
    )
    result = await self.dispatch.send_request("thread/list", params)
    return ThreadListResponse.model_validate(result)

thread_loaded_list async

thread_loaded_list(
    *, cursor: str | None = None, limit: int | None = None
) -> ThreadLoadedListResponse

List thread IDs currently loaded in memory.

Parameters:

Name Type Description Default
cursor str | None

Opaque pagination cursor from previous response

None
limit int | None

Maximum number of thread IDs to return

None

Returns:

Type Description
ThreadLoadedListResponse

ThreadLoadedListResponse with data (list of thread IDs) and next_cursor

Source code in src/codexed/client/client.py
async def thread_loaded_list(
    self,
    *,
    cursor: str | None = None,
    limit: int | None = None,
) -> ThreadLoadedListResponse:
    """List thread IDs currently loaded in memory.

    Args:
        cursor: Opaque pagination cursor from previous response
        limit: Maximum number of thread IDs to return

    Returns:
        ThreadLoadedListResponse with data (list of thread IDs) and next_cursor
    """
    params = ThreadLoadedListParams(cursor=cursor, limit=limit)
    result = await self.dispatch.send_request("thread/loaded/list", params)
    return ThreadLoadedListResponse.model_validate(result)

thread_resume async

thread_resume(
    thread_id: str,
    *,
    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,
    personality: Personality | None = None,
    mcp_servers: Mapping[str, McpServerConfig] | None = None,
    exclude_turns: bool | None = None,
    permissions: str | None = None,
) -> Session

Resume an existing thread by ID.

Parameters:

Name Type Description Default
thread_id str

ID of the thread to resume

required
path str | None

Path to thread storage

None
cwd str | None

Working directory override

None
model str | None

Model override

None
model_provider str | None

Model provider override

None
base_instructions str | None

Base system instructions override

None
developer_instructions str | None

Developer instructions override

None
approval_policy AskForApproval | None

Tool approval policy override

None
approvals_reviewer ApprovalsReviewer | None

Where approval requests are routed for review

None
sandbox SandboxMode | None

Sandbox mode override

None
config dict[str, Any] | None

Additional configuration overrides

None
tools list[ToolConfig] | None

Builtin tool configurations override

None
code_mode bool | None

Enable experimental code mode feature flag

None
service_tier str | None

Service tier

None
personality Personality | None

Personality override

None
mcp_servers Mapping[str, McpServerConfig] | None

Per-thread MCP server configurations

None
exclude_turns bool | None

If true, exclude turns from the thread's history

None
permissions str | None

Named permissions profile ID (cannot be combined with sandbox)

None

Returns:

Type Description
Session

Session wrapping the resumed thread

Source code in src/codexed/client/client.py
async def thread_resume(
    self,
    thread_id: str,
    *,
    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,
    personality: Personality | None = None,
    mcp_servers: Mapping[str, McpServerConfig] | None = None,
    exclude_turns: bool | None = None,
    permissions: str | None = None,
) -> Session:
    """Resume an existing thread by ID.

    Args:
        thread_id: ID of the thread to resume
        path: Path to thread storage
        cwd: Working directory override
        model: Model override
        model_provider: Model provider override
        base_instructions: Base system instructions override
        developer_instructions: Developer instructions override
        approval_policy: Tool approval policy override
        approvals_reviewer: Where approval requests are routed for review
        sandbox: Sandbox mode override
        config: Additional configuration overrides
        tools: Builtin tool configurations override
        code_mode: Enable experimental code mode feature flag
        service_tier: Service tier
        personality: Personality override
        mcp_servers: Per-thread MCP server configurations
        exclude_turns: If true, exclude turns from the thread's history
        permissions: Named permissions profile ID (cannot be combined with sandbox)

    Returns:
        Session wrapping the resumed thread
    """
    from codexed.client.session import Session

    cfg = merge_config(
        config,
        tools,
        code_mode,
        mcp_servers,
        mcp_elicitation_for_approvals=self._mcp_elicitation_for_approvals,
    )
    params = ThreadResumeParams(
        thread_id=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=cfg,
        service_tier=service_tier,
        personality=personality,
        exclude_turns=exclude_turns,
        permissions=permissions,
    )
    result = await self.dispatch.send_request("thread/resume", params)
    response = ThreadResponse.model_validate(result)
    self._active_threads.add(response.thread.id)
    return Session(self, response)

thread_start async

thread_start(
    *,
    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_name: str | None = None,
    service_tier: str | None = None,
    personality: Personality | None = None,
    ephemeral: bool | None = None,
    dynamic_tools: list[DynamicToolSpec] | None = None,
    mcp_servers: Mapping[str, McpServerConfig] | None = None,
    experimental_raw_events: bool = False,
    session_start_source: ThreadStartSource | None = None,
    environments: list[TurnEnvironmentParams] | None = None,
) -> Session

Start a new conversation thread.

Parameters:

Name Type Description Default
cwd str | None

Working directory for the thread

None
model str | None

Model to use (e.g., "gpt-5-codex")

None
model_provider str | None

Model provider (e.g., "openai", "anthropic")

None
base_instructions str | None

Base system instructions for the thread

None
developer_instructions str | None

Developer-provided instructions

None
approval_policy AskForApproval | None

Tool approval policy

None
approvals_reviewer ApprovalsReviewer | None

Where approval requests are routed for review

None
sandbox SandboxMode | None

Sandbox mode for file operations

None
config dict[str, Any] | None

Additional configuration overrides

None
tools list[ToolConfig] | None

Builtin tool configurations. None uses server defaults, an empty list disables all tools, a populated list enables exactly those tools. Merged into config.

None
code_mode bool | None

Enable experimental code mode feature flag

None
service_name str | None

Optional service name

None
service_tier str | None

Service tier

None
personality Personality | None

Personality preset (none, friendly, pragmatic)

None
ephemeral bool | None

If true, thread is not persisted to disk

None
dynamic_tools list[DynamicToolSpec] | None

Dynamic tool specifications

None
mcp_servers Mapping[str, McpServerConfig] | None

Per-thread MCP server configurations. Merged into config under the mcp_servers key.

None
experimental_raw_events bool

Emit raw Responses API items (internal)

False
session_start_source ThreadStartSource | None

Source of the session start

None
environments list[TurnEnvironmentParams] | None

List of environment variables to set for the thread

None

Returns:

Type Description
Session

Session wrapping the new thread

Source code in src/codexed/client/client.py
async def thread_start(
    self,
    *,
    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_name: str | None = None,
    service_tier: str | None = None,
    personality: Personality | None = None,
    ephemeral: bool | None = None,
    dynamic_tools: list[DynamicToolSpec] | None = None,
    mcp_servers: Mapping[str, McpServerConfig] | None = None,
    experimental_raw_events: bool = False,
    session_start_source: ThreadStartSource | None = None,
    environments: list[TurnEnvironmentParams] | None = None,
) -> Session:
    """Start a new conversation thread.

    Args:
        cwd: Working directory for the thread
        model: Model to use (e.g., "gpt-5-codex")
        model_provider: Model provider (e.g., "openai", "anthropic")
        base_instructions: Base system instructions for the thread
        developer_instructions: Developer-provided instructions
        approval_policy: Tool approval policy
        approvals_reviewer: Where approval requests are routed for review
        sandbox: Sandbox mode for file operations
        config: Additional configuration overrides
        tools: Builtin tool configurations. ``None`` uses server defaults,
            an empty list disables all tools, a populated list enables
            exactly those tools. Merged into ``config``.
        code_mode: Enable experimental code mode feature flag
        service_name: Optional service name
        service_tier: Service tier
        personality: Personality preset (none, friendly, pragmatic)
        ephemeral: If true, thread is not persisted to disk
        dynamic_tools: Dynamic tool specifications
        mcp_servers: Per-thread MCP server configurations.
            Merged into ``config`` under the ``mcp_servers`` key.
        experimental_raw_events: Emit raw Responses API items (internal)
        session_start_source: Source of the session start
        environments: List of environment variables to set for the thread

    Returns:
        Session wrapping the new thread
    """
    from codexed.client.session import Session

    cfg = merge_config(
        config,
        tools,
        code_mode,
        mcp_servers,
        mcp_elicitation_for_approvals=self._mcp_elicitation_for_approvals,
    )
    params = ThreadStartParams(
        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=cfg,
        service_name=service_name,
        service_tier=service_tier,
        personality=personality,
        ephemeral=ephemeral,
        dynamic_tools=dynamic_tools,
        experimental_raw_events=experimental_raw_events,
        session_start_source=session_start_source,
        environments=environments,
    )
    result = await self.dispatch.send_request("thread/start", params)
    response = ThreadResponse.model_validate(result)
    self._active_threads.add(response.thread.id)
    return Session(self, response)

warning async

warning(message: str) -> None

Send a warning message to the app-server.

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

CodexError

Bases: Exception

Base exception for Codex adapter errors.

Source code in src/codexed/exceptions.py
class CodexError(Exception):
    """Base exception for Codex adapter errors."""

CodexProcessError

Bases: CodexError

Error starting or communicating with the Codex app-server process.

Source code in src/codexed/exceptions.py
class CodexProcessError(CodexError):
    """Error starting or communicating with the Codex app-server process."""

CodexRequestError

Bases: CodexError

Error from a Codex app-server request (JSON-RPC error response).

Source code in src/codexed/exceptions.py
class CodexRequestError(CodexError):
    """Error from a Codex app-server request (JSON-RPC error response)."""

    def __init__(self, code: int, message: str, data: dict[str, Any] | None = None) -> None:
        super().__init__(message)
        self.code = code
        self.message = message
        self.data = data or {}

    def __str__(self) -> str:
        if self.data:
            return f"[{self.code}] {self.message}: {self.data}"
        return f"[{self.code}] {self.message}"

CollaborationMode

Bases: CodexBaseModel

Collaboration mode for a Codex session.

Source code in src/codexed/models/v2_protocol.py
class CollaborationMode(CodexBaseModel):
    """Collaboration mode for a Codex session."""

    mode: ModeKind
    settings: Settings

CommandExecResponse

Bases: CodexBaseModel

Final buffered result for command/exec.

Source code in src/codexed/models/v2_protocol.py
class CommandExecResponse(CodexBaseModel):
    """Final buffered result for `command/exec`."""

    exit_code: int
    """
    Process exit code.
    """
    stderr: str
    """
    Buffered stderr capture.

    Empty when stderr was streamed via `command/exec/outputDelta`.
    """
    stdout: str
    """
    Buffered stdout capture.

    Empty when stdout was streamed via `command/exec/outputDelta`.
    """

exit_code instance-attribute

exit_code: int

Process exit code.

stderr instance-attribute

stderr: str

Buffered stderr capture.

Empty when stderr was streamed via command/exec/outputDelta.

stdout instance-attribute

stdout: str

Buffered stdout capture.

Empty when stdout was streamed via command/exec/outputDelta.

ConfigWarningMessage

Bases: CodexBaseModel

Notification sent from the server to the client.

Source code in src/codexed/models/v2_protocol.py
class ConfigWarningMessage(CodexBaseModel):
    """Notification sent from the server to the client."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["configWarning"] = "configWarning"
    params: ConfigWarningNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

ConfigWarningNotification

Bases: CodexBaseModel

Source code in src/codexed/models/v2_protocol.py
class ConfigWarningNotification(CodexBaseModel):
    details: str | None = None
    """
    Optional extra guidance or error details.
    """
    path: str | None = None
    """
    Optional path to the config file that triggered the warning.
    """
    range: TextRange | None = None
    """
    Optional range for the error location inside the config file.
    """
    summary: str
    """
    Concise summary of the warning.
    """

details class-attribute instance-attribute

details: str | None = None

Optional extra guidance or error details.

path class-attribute instance-attribute

path: str | None = None

Optional path to the config file that triggered the warning.

range class-attribute instance-attribute

range: TextRange | None = None

Optional range for the error location inside the config file.

summary instance-attribute

summary: str

Concise summary of the warning.

ExperimentalFeature

Bases: CodexBaseModel

Source code in src/codexed/models/v2_protocol.py
class ExperimentalFeature(CodexBaseModel):
    announcement: str | None = None
    """
    Announcement copy shown to users when the feature is introduced. Null when this feature is not in beta.
    """
    default_enabled: bool
    """
    Whether this feature is enabled by default.
    """
    description: str | None = None
    """
    Short summary describing what the feature does. Null when this feature is not in beta.
    """
    display_name: str | None = None
    """
    User-facing display name shown in the experimental features UI. Null when this feature is not in beta.
    """
    enabled: bool
    """
    Whether this feature is currently enabled in the loaded config.
    """
    name: str
    """
    Stable key used in config.toml and CLI flag toggles.
    """
    stage: ExperimentalFeatureStage
    """
    Lifecycle stage of this feature flag.
    """

announcement class-attribute instance-attribute

announcement: str | None = None

Announcement copy shown to users when the feature is introduced. Null when this feature is not in beta.

default_enabled instance-attribute

default_enabled: bool

Whether this feature is enabled by default.

description class-attribute instance-attribute

description: str | None = None

Short summary describing what the feature does. Null when this feature is not in beta.

display_name class-attribute instance-attribute

display_name: str | None = None

User-facing display name shown in the experimental features UI. Null when this feature is not in beta.

enabled instance-attribute

enabled: bool

Whether this feature is currently enabled in the loaded config.

name instance-attribute

name: str

Stable key used in config.toml and CLI flag toggles.

stage instance-attribute

stage: ExperimentalFeatureStage

Lifecycle stage of this feature flag.

FsChangedMessage

Bases: CodexBaseModel

Notification sent from the server to the client.

Source code in src/codexed/models/v2_protocol.py
class FsChangedMessage(CodexBaseModel):
    """Notification sent from the server to the client."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["fs/changed"] = "fs/changed"
    params: FsChangedNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

HttpMcpServer

Bases: BaseModel

MCP server accessible via HTTP/SSE transport.

Source code in src/codexed/models/mcp_server.py
class HttpMcpServer(BaseModel):
    """MCP server accessible via HTTP/SSE transport."""

    url: str
    bearer_token_env_var: str | None = None
    http_headers: dict[str, str] | None = None
    enabled: bool = True
    default_tools_approval_mode: ToolApprovalMode | None = None
    """When Codex asks before calling this server's tools (Codex's default: ``auto``)."""

    def to_config_toml(self, name: str) -> str:
        parts = [f'url = "{self.url}"']
        if self.bearer_token_env_var:
            parts.append(f'bearer_token_env_var = "{self.bearer_token_env_var}"')
        if self.http_headers:
            # headers as inline table
            headers_items = ", ".join(f'{k} = "{v}"' for k, v in self.http_headers.items())
            parts.append(f"http_headers = {{{headers_items}}}")
        if not self.enabled:
            parts.append("enabled = false")
        if self.default_tools_approval_mode:
            parts.append(f'default_tools_approval_mode = "{self.default_tools_approval_mode}"')
        return f"mcp_servers.{name}={{{', '.join(parts)}}}"

default_tools_approval_mode class-attribute instance-attribute

default_tools_approval_mode: ToolApprovalMode | None = None

When Codex asks before calling this server's tools (Codex's default: auto).

InternalRpcError

Bases: CodexRequestError

JSON-RPC internal error (-32603).

Source code in src/codexed/exceptions.py
class InternalRpcError(CodexRequestError):
    """JSON-RPC internal error (-32603)."""

InvalidParamsError

Bases: CodexRequestError

JSON-RPC invalid params (-32602).

Source code in src/codexed/exceptions.py
class InvalidParamsError(CodexRequestError):
    """JSON-RPC invalid params (-32602)."""

InvalidRequestError

Bases: CodexRequestError

JSON-RPC invalid request (-32600).

Source code in src/codexed/exceptions.py
class InvalidRequestError(CodexRequestError):
    """JSON-RPC invalid request (-32600)."""

ItemAgentMessageDeltaNotification

Bases: CodexBaseModel

Notification sent from the server to the client.

Source code in src/codexed/models/v2_protocol.py
class ItemAgentMessageDeltaNotification(CodexBaseModel):
    """Notification sent from the server to the client."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["item/agentMessage/delta"] = "item/agentMessage/delta"
    params: AgentMessageDeltaNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

ItemCommandExecutionOutputDeltaNotification

Bases: CodexBaseModel

Notification sent from the server to the client.

Source code in src/codexed/models/v2_protocol.py
class ItemCommandExecutionOutputDeltaNotification(CodexBaseModel):
    """Notification sent from the server to the client."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["item/commandExecution/outputDelta"] = "item/commandExecution/outputDelta"
    params: CommandExecutionOutputDeltaNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

ItemCompletedEvent

Bases: CodexBaseModel

Item completed event.

Source code in src/codexed/models/events.py
class ItemCompletedEvent(CodexBaseModel):
    """Item completed event."""

    method: Literal["item/completed"] = "item/completed"
    params: ItemCompletedData

ItemFileChangeOutputDeltaNotification

Bases: CodexBaseModel

Deprecated legacy apply_patch output stream notification.

Source code in src/codexed/models/v2_protocol.py
class ItemFileChangeOutputDeltaNotification(CodexBaseModel):
    """Deprecated legacy apply_patch output stream notification."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["item/fileChange/outputDelta"] = "item/fileChange/outputDelta"
    params: FileChangeOutputDeltaNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

ItemPlanDeltaNotification

Bases: CodexBaseModel

EXPERIMENTAL - proposed plan streaming deltas for plan items.

Source code in src/codexed/models/v2_protocol.py
class ItemPlanDeltaNotification(CodexBaseModel):
    """EXPERIMENTAL - proposed plan streaming deltas for plan items."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["item/plan/delta"] = "item/plan/delta"
    params: PlanDeltaNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

ItemReasoningTextDeltaNotification

Bases: CodexBaseModel

Notification sent from the server to the client.

Source code in src/codexed/models/v2_protocol.py
class ItemReasoningTextDeltaNotification(CodexBaseModel):
    """Notification sent from the server to the client."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["item/reasoning/textDelta"] = "item/reasoning/textDelta"
    params: ReasoningTextDeltaNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

ItemStartedEvent

Bases: CodexBaseModel

Item started event.

Source code in src/codexed/models/events.py
class ItemStartedEvent(CodexBaseModel):
    """Item started event."""

    method: Literal["item/started"] = "item/started"
    params: ItemStartedData

MethodNotFoundError

Bases: CodexRequestError

JSON-RPC method not found (-32601).

Source code in src/codexed/exceptions.py
class MethodNotFoundError(CodexRequestError):
    """JSON-RPC method not found (-32601)."""

Model

Bases: CodexBaseModel

Source code in src/codexed/models/v2_protocol.py
class Model(CodexBaseModel):
    additional_speed_tiers: list[str] | None = []
    """
    Deprecated: use `serviceTiers` instead.
    """
    availability_nux: ModelAvailabilityNux | None = None
    available_access_programs: ModelAccessPrograms | None = None
    """
    Null when the catalog does not provide access-program metadata.
    """
    default_reasoning_effort: ReasoningEffort
    default_service_tier: str | None = None
    """
    Catalog default service tier id for this model, when one is configured.
    """
    description: str
    display_name: str
    hidden: bool
    id: str
    input_modalities: list[InputModality] | None = ["text", "image"]
    is_default: bool
    model: str
    model_specialty: str | None = None
    multi_agent_version: MultiAgentVersion | None = None
    """
    Multi-agent runtime declared by this model, when available.
    """
    service_tiers: list[ModelServiceTier] | None = Field([], validate_default=True)
    supported_reasoning_efforts: list[ReasoningEffortOption]
    supports_personality: bool | None = False
    """
    @deprecated Always false; models no longer support personality selection.
    """
    upgrade: str | None = None
    upgrade_info: ModelUpgradeInfo | None = None

additional_speed_tiers class-attribute instance-attribute

additional_speed_tiers: list[str] | None = []

Deprecated: use serviceTiers instead.

available_access_programs class-attribute instance-attribute

available_access_programs: ModelAccessPrograms | None = None

Null when the catalog does not provide access-program metadata.

default_service_tier class-attribute instance-attribute

default_service_tier: str | None = None

Catalog default service tier id for this model, when one is configured.

multi_agent_version class-attribute instance-attribute

multi_agent_version: MultiAgentVersion | None = None

Multi-agent runtime declared by this model, when available.

supports_personality class-attribute instance-attribute

supports_personality: bool | None = False

@deprecated Always false; models no longer support personality selection.

ModelReroutedMessage

Bases: CodexBaseModel

Notification sent from the server to the client.

Source code in src/codexed/models/v2_protocol.py
class ModelReroutedMessage(CodexBaseModel):
    """Notification sent from the server to the client."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["model/rerouted"] = "model/rerouted"
    params: ModelReroutedNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

ParseError

Bases: CodexRequestError

JSON-RPC parse error (-32700).

Source code in src/codexed/exceptions.py
class ParseError(CodexRequestError):
    """JSON-RPC parse error (-32700)."""

PlanDeltaNotification

Bases: CodexBaseModel

EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should not assume concatenated deltas match the completed plan item content.

Source code in src/codexed/models/v2_protocol.py
class PlanDeltaNotification(CodexBaseModel):
    """EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should not assume concatenated deltas match the completed plan item content."""

    delta: str
    item_id: str
    thread_id: str
    turn_id: str

RetryLimitExceededError

Bases: ServerBusyError

Server exhausted internal retry budget for a retryable operation.

Source code in src/codexed/exceptions.py
class RetryLimitExceededError(ServerBusyError):
    """Server exhausted internal retry budget for a retryable operation."""

ReviewStartResponse

Bases: CodexBaseModel

Response for review/start request.

Source code in src/codexed/models/responses.py
class ReviewStartResponse(CodexBaseModel):
    """Response for review/start request."""

    turn: TurnData
    review_thread_id: str

ServerBusyError

Bases: CodexRequestError

Server is overloaded / unavailable and caller should retry.

Source code in src/codexed/exceptions.py
class ServerBusyError(CodexRequestError):
    """Server is overloaded / unavailable and caller should retry."""

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")
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)

Settings

Bases: CodexBaseModel

Settings for a collaboration mode.

Source code in src/codexed/models/v2_protocol.py
class Settings(CodexBaseModel):
    """Settings for a collaboration mode."""

    developer_instructions: str | None = None
    model: str
    reasoning_effort: ReasoningEffort | None = None

SkillMetadata

Bases: CodexBaseModel

Source code in src/codexed/models/v2_protocol.py
class SkillMetadata(CodexBaseModel):
    dependencies: SkillDependencies | None = None
    description: str
    enabled: bool
    interface: SkillInterface | None = None
    name: str
    path: LegacyAppPathString
    plugin_id: str | None = None
    """
    Owning plugin ID, matching `PluginSummary.id`, when known.
    """
    scope: SkillScope
    short_description: str | None = None
    """
    Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.
    """

plugin_id class-attribute instance-attribute

plugin_id: str | None = None

Owning plugin ID, matching PluginSummary.id, when known.

short_description class-attribute instance-attribute

short_description: str | None = None

Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.

StdioMcpServer

Bases: BaseModel

MCP server running as a subprocess via stdio transport.

Source code in src/codexed/models/mcp_server.py
class StdioMcpServer(BaseModel):
    """MCP server running as a subprocess via stdio transport."""

    command: str
    args: list[str] = []
    env: dict[str, str] | None = None
    enabled: bool = True
    default_tools_approval_mode: ToolApprovalMode | None = None
    """When Codex asks before calling this server's tools (Codex's default: ``auto``)."""

    def to_config_toml(self, name: str) -> str:
        parts = [f'command = "{self.command}"']
        if self.args:
            args_str = ", ".join(f'"{arg}"' for arg in self.args)
            parts.append(f"args = [{args_str}]")
        if self.env:
            # env as inline table
            env_items = ", ".join(f'{k} = "{v}"' for k, v in self.env.items())
            parts.append(f"env = {{{env_items}}}")
        if not self.enabled:
            parts.append("enabled = false")
        if self.default_tools_approval_mode:
            parts.append(f'default_tools_approval_mode = "{self.default_tools_approval_mode}"')
        return f"mcp_servers.{name}={{{', '.join(parts)}}}"

default_tools_approval_mode class-attribute instance-attribute

default_tools_approval_mode: ToolApprovalMode | None = None

When Codex asks before calling this server's tools (Codex's default: auto).

StdioTransport

Transport that communicates with a Codex app-server subprocess via stdin/stdout.

Source code in src/codexed/transport.py
class StdioTransport:
    """Transport that communicates with a Codex app-server subprocess via stdin/stdout."""

    def __init__(
        self,
        command: str,
        profile: str | None = None,
        env_vars: dict[str, str] | None = None,
        mcp_servers: Mapping[str, McpServerConfig] | None = None,
    ) -> None:
        self._command = command
        self._profile = profile
        self._mcp_servers = dict(mcp_servers) if mcp_servers else {}
        self._env_vars = env_vars or {}
        self._process: asyncio.subprocess.Process | None = None
        self._writer_lock = asyncio.Lock()
        self._stderr_task: asyncio.Task[None] | None = None
        self._stderr_tail: deque[str] = deque(maxlen=STDERR_TAIL_LINES)

    async def start(self) -> None:
        if self._process is not None:
            return

        cmd = [self._command, "app-server"]
        if self._profile:
            cmd.extend(["--profile", self._profile])
        for server_name, server_config in self._mcp_servers.items():
            config_str = server_config.to_config_toml(server_name)
            cmd.extend(["--config", config_str])

        logger.info("Starting Codex app-server: %s", " ".join(cmd))
        try:
            self._process = await asyncio.create_subprocess_exec(
                *cmd,
                stdin=asyncio.subprocess.PIPE,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                limit=STDOUT_LINE_LIMIT,
                env={**os.environ, **self._env_vars},
                # Own process group: stop() also ends wrapper children and MCP servers.
                start_new_session=sys.platform != "win32",
            )
        except FileNotFoundError as exc:
            raise CodexProcessError(f"Codex binary not found: {self._command}") from exc
        except Exception as exc:
            raise CodexProcessError(f"Failed to start Codex app-server: {exc}") from exc
        self._stderr_tail.clear()
        self._stderr_task = asyncio.create_task(self._drain_stderr(self._process))

    async def _drain_stderr(self, process: asyncio.subprocess.Process) -> None:
        """Read stderr continuously: an unread pipe fills up and blocks the server."""
        assert process.stderr is not None
        while True:
            try:
                line_bytes = await process.stderr.readline()
            except ValueError:  # a line over the stream limit (dropped): read on
                self._stderr_tail.append("[stderr line over the length limit dropped]")
                continue
            if not line_bytes:
                break
            line = line_bytes.decode(errors="replace").rstrip()
            self._stderr_tail.append(line)
            logger.debug("codex stderr: %s", line)

    async def close_reason(self) -> str:
        """Describe why the server's stdout closed: exit code and the last stderr lines."""
        process = self._process
        if process is None:
            return "transport stopped"
        with contextlib.suppress(TimeoutError):
            await asyncio.wait_for(process.wait(), timeout=2.0)
        if self._stderr_task is not None:
            with contextlib.suppress(TimeoutError, Exception):
                await asyncio.wait_for(asyncio.shield(self._stderr_task), timeout=0.5)
        code = process.returncode
        reason = "still running" if code is None else f"exit code {code}"
        if self._stderr_tail:
            reason += "; stderr:\n" + "\n".join(self._stderr_tail)
        return reason

    def _signal_group(self, process: asyncio.subprocess.Process, sig: int) -> None:
        if sys.platform == "win32":
            if process.returncode is None:
                with contextlib.suppress(ProcessLookupError, PermissionError):
                    if sig == signal.SIGTERM:
                        process.terminate()
                    else:
                        process.kill()
            return
        with contextlib.suppress(ProcessLookupError, PermissionError):
            os.killpg(process.pid, sig)

    async def stop(self) -> None:
        process = self._process
        if process is None:
            return
        # Closing stdin is the graceful shutdown for a stdio server.
        if process.stdin is not None and not process.stdin.is_closing():
            process.stdin.close()
        with contextlib.suppress(TimeoutError):
            await asyncio.wait_for(process.wait(), timeout=2.0)
        # Also when the server exited: its children (MCP servers, tools) may still run.
        self._signal_group(process, signal.SIGTERM)
        try:
            await asyncio.wait_for(process.wait(), timeout=5.0)
        except TimeoutError:
            self._signal_group(process, getattr(signal, "SIGKILL", signal.SIGTERM))
            await process.wait()
        if self._stderr_task is not None:
            self._stderr_task.cancel()
            with contextlib.suppress(asyncio.CancelledError, Exception):
                await self._stderr_task
            self._stderr_task = None
        self._process = None

    async def send(self, message: dict[str, Any]) -> None:
        if self._process is None or self._process.stdin is None:
            raise TransportClosedError("Not connected to Codex app-server")
        async with self._writer_lock:
            line = anyenv.dump_json(message) + "\n"
            self._process.stdin.write(line.encode())
            await self._process.stdin.drain()

    async def receive(self) -> dict[str, Any] | None:
        if self._process is None or self._process.stdout is None:
            return None
        while True:
            line_bytes = await self._process.stdout.readline()
            if not line_bytes:
                return None
            # A stray warning line or byte must not end the connection: skip it.
            if (message := _parse_line(line_bytes.decode(errors="replace"))) is not None:
                return message

    @property
    def is_connected(self) -> bool:
        return self._process is not None

close_reason async

close_reason() -> str

Describe why the server's stdout closed: exit code and the last stderr lines.

Source code in src/codexed/transport.py
async def close_reason(self) -> str:
    """Describe why the server's stdout closed: exit code and the last stderr lines."""
    process = self._process
    if process is None:
        return "transport stopped"
    with contextlib.suppress(TimeoutError):
        await asyncio.wait_for(process.wait(), timeout=2.0)
    if self._stderr_task is not None:
        with contextlib.suppress(TimeoutError, Exception):
            await asyncio.wait_for(asyncio.shield(self._stderr_task), timeout=0.5)
    code = process.returncode
    reason = "still running" if code is None else f"exit code {code}"
    if self._stderr_tail:
        reason += "; stderr:\n" + "\n".join(self._stderr_tail)
    return reason

TextUserInput

Bases: CodexBaseModel

Source code in src/codexed/models/v2_protocol.py
class TextUserInput(CodexBaseModel):
    text: str
    text_elements: list[TextElement] | None = Field([], validate_default=True)
    """
    UI-defined spans within `text` used to render or persist special elements.
    """
    type: Literal["text"] = "text"

text_elements class-attribute instance-attribute

text_elements: list[TextElement] | None = Field([], validate_default=True)

UI-defined spans within text used to render or persist special elements.

Thread

Bases: CodexBaseModel

Source code in src/codexed/models/misc.py
class Thread(CodexBaseModel):
    agent_nickname: str | None = None
    """
    Optional random unique nickname assigned to an AgentControl-spawned sub-agent.
    """
    agent_role: str | None = None
    """
    Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.
    """
    cli_version: str
    """
    Version of the CLI that created the thread.
    """
    created_at: int
    """
    Unix timestamp (in seconds) when the thread was created.
    """
    cwd: AbsolutePathBuf
    """
    Working directory captured for the thread.
    """
    ephemeral: bool
    """
    Whether the thread is ephemeral and should not be materialized on disk.
    """
    forked_from_id: str | None = None
    """
    Source thread id when this thread was created by forking another thread.
    """
    git_info: GitInfo | None = None
    """
    Optional Git metadata captured when the thread was created.
    """
    id: str
    model_provider: str
    """
    Model provider used for this thread (for example, 'openai').
    """
    name: str | None = None
    """
    Optional user-facing thread title.
    """
    path: str | None = None
    """
    [UNSTABLE] Path to the thread on disk.
    """
    preview: str
    """
    Usually the first user message in the thread, if available.
    """
    source: SessionSource
    """
    Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).
    """
    status: ThreadStatus
    """
    Current runtime status for the thread.
    """
    turns: list[Turn]
    """
    Only populated on `thread/resume`, `thread/fork`, and `thread/read`
    (when `includeTurns` is true) responses.
    For all other responses and notifications returning a Thread,
    the turns field will be an empty list.
    """
    updated_at: int
    """
    Unix timestamp (in seconds) when the thread was last updated.
    """
    attached_to_thread_id: str | None = None
    can_accept_direct_input: bool | None = None
    daybreak_enabled: bool | None = None
    environments: list[ThreadEnvironment] | None = None
    extra: ThreadExtra | None = None
    history_mode: ThreadHistoryMode | None = None
    model: str | None = None
    originator: str | None = None
    parent_thread_id: str | None = None
    project_id: str | None = None
    reasoning_effort: ReasoningEffort | None = None
    recency_at: int | None = None
    """Unix timestamp (in seconds) used to order threads by recency."""
    section: ThreadSection | None = None
    section_entered_at: int | None = None
    session_id: str | None = None
    thread_source: str | None = None

agent_nickname class-attribute instance-attribute

agent_nickname: str | None = None

Optional random unique nickname assigned to an AgentControl-spawned sub-agent.

agent_role class-attribute instance-attribute

agent_role: str | None = None

Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.

cli_version instance-attribute

cli_version: str

Version of the CLI that created the thread.

created_at instance-attribute

created_at: int

Unix timestamp (in seconds) when the thread was created.

cwd instance-attribute

Working directory captured for the thread.

ephemeral instance-attribute

ephemeral: bool

Whether the thread is ephemeral and should not be materialized on disk.

forked_from_id class-attribute instance-attribute

forked_from_id: str | None = None

Source thread id when this thread was created by forking another thread.

git_info class-attribute instance-attribute

git_info: GitInfo | None = None

Optional Git metadata captured when the thread was created.

model_provider instance-attribute

model_provider: str

Model provider used for this thread (for example, 'openai').

name class-attribute instance-attribute

name: str | None = None

Optional user-facing thread title.

path class-attribute instance-attribute

path: str | None = None

[UNSTABLE] Path to the thread on disk.

preview instance-attribute

preview: str

Usually the first user message in the thread, if available.

recency_at class-attribute instance-attribute

recency_at: int | None = None

Unix timestamp (in seconds) used to order threads by recency.

source instance-attribute

source: SessionSource

Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).

status instance-attribute

status: ThreadStatus

Current runtime status for the thread.

turns instance-attribute

turns: list[Turn]

Only populated on thread/resume, thread/fork, and thread/read (when includeTurns is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.

updated_at instance-attribute

updated_at: int

Unix timestamp (in seconds) when the thread was last updated.

ThreadArchivedMessage

Bases: CodexBaseModel

Notification sent from the server to the client.

Source code in src/codexed/models/v2_protocol.py
class ThreadArchivedMessage(CodexBaseModel):
    """Notification sent from the server to the client."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["thread/archived"] = "thread/archived"
    params: ThreadArchivedNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

ThreadCompactedMessage

Bases: CodexBaseModel

Deprecated: Use ContextCompaction item type instead.

Source code in src/codexed/models/v2_protocol.py
class ThreadCompactedMessage(CodexBaseModel):
    """Deprecated: Use `ContextCompaction` item type instead."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["thread/compacted"] = "thread/compacted"
    params: ContextCompactedNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

ThreadListResponse

Bases: CodexBaseModel

Response for thread/list request.

Source code in src/codexed/models/responses.py
class ThreadListResponse(CodexBaseModel):
    """Response for thread/list request."""

    data: list[Thread]
    next_cursor: str | None = None
    backwards_cursor: str | None = None
    read_states: dict[str, ThreadReadState] | None = None
    """Read state per thread ID."""

read_states class-attribute instance-attribute

read_states: dict[str, ThreadReadState] | None = None

Read state per thread ID.

ThreadNameUpdatedMessage

Bases: CodexBaseModel

Notification sent from the server to the client.

Source code in src/codexed/models/v2_protocol.py
class ThreadNameUpdatedMessage(CodexBaseModel):
    """Notification sent from the server to the client."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["thread/name/updated"] = "thread/name/updated"
    params: ThreadNameUpdatedNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

ThreadReadResponse

Bases: CodexBaseModel

Response for thread/read request.

Source code in src/codexed/models/responses.py
class ThreadReadResponse(CodexBaseModel):
    """Response for thread/read request."""

    thread: Thread
    read_state: ThreadReadState | None = None

ThreadResponse

Bases: CodexBaseModel

Response for thread/start, thread/resume, and thread/fork.

Source code in src/codexed/models/responses.py
class ThreadResponse(CodexBaseModel):
    """Response for thread/start, thread/resume, and thread/fork."""

    thread: Thread
    model: str
    model_provider: str
    cwd: str
    approval_policy: AskForApproval
    sandbox: SandboxPolicy
    reasoning_effort: ReasoningEffort | None = None
    service_tier: str | None = None
    active_permission_profile: ActivePermissionProfile | None = None
    approvals_reviewer: ApprovalsReviewer | None = None
    collaboration_mode: CollaborationMode | None = None
    """Only returned by thread/resume."""
    disabled_plugin_ids: list[str] | None = None
    initial_turns_page: TurnsPage | None = None
    """Only returned by thread/resume."""
    instruction_sources: list[str] | None = None
    items_backwards_cursor: str | None = None
    """Only returned by thread/resume."""
    multi_agent_mode: MultiAgentMode | None = None
    runtime_workspace_roots: list[str] | None = None
    turns_backwards_cursor: str | None = None
    """Only returned by thread/resume."""

collaboration_mode class-attribute instance-attribute

collaboration_mode: CollaborationMode | None = None

Only returned by thread/resume.

initial_turns_page class-attribute instance-attribute

initial_turns_page: TurnsPage | None = None

Only returned by thread/resume.

items_backwards_cursor class-attribute instance-attribute

items_backwards_cursor: str | None = None

Only returned by thread/resume.

turns_backwards_cursor class-attribute instance-attribute

turns_backwards_cursor: str | None = None

Only returned by thread/resume.

ThreadRevertResponse

Bases: CodexBaseModel

Response for thread/revert request.

Source code in src/codexed/models/responses.py
class ThreadRevertResponse(CodexBaseModel):
    """Response for thread/revert request."""

    thread: Thread
    """Updated thread metadata. `turns` is always empty; use `thread/turns/list`."""
    items_backwards_cursor: str | None = None
    """Cursor for hydrating paginated items backwards via `thread/items/list`."""
    turns_backwards_cursor: str | None = None
    """Cursor for hydrating paginated turns backwards via `thread/turns/list`."""

items_backwards_cursor class-attribute instance-attribute

items_backwards_cursor: str | None = None

Cursor for hydrating paginated items backwards via thread/items/list.

thread instance-attribute

thread: Thread

Updated thread metadata. turns is always empty; use thread/turns/list.

turns_backwards_cursor class-attribute instance-attribute

turns_backwards_cursor: str | None = None

Cursor for hydrating paginated turns backwards via thread/turns/list.

ThreadStartedData

Bases: CodexBaseModel

Payload for thread/started notification (V2 protocol).

Source code in src/codexed/models/event_data.py
class ThreadStartedData(CodexBaseModel):
    """Payload for thread/started notification (V2 protocol)."""

    thread: Thread

    @property
    def thread_id(self) -> str:
        """Thread ID derived from the thread object."""
        return self.thread.id

thread_id property

thread_id: str

Thread ID derived from the thread object.

ThreadStartedEvent

Bases: CodexBaseModel

Thread started event.

Source code in src/codexed/models/events.py
class ThreadStartedEvent(CodexBaseModel):
    """Thread started event."""

    method: Literal["thread/started"] = "thread/started"
    params: ThreadStartedData

ThreadStatusChangedMessage

Bases: CodexBaseModel

Notification sent from the server to the client.

Source code in src/codexed/models/v2_protocol.py
class ThreadStatusChangedMessage(CodexBaseModel):
    """Notification sent from the server to the client."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["thread/status/changed"] = "thread/status/changed"
    params: ThreadStatusChangedNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

ThreadUnarchiveResponse

Bases: CodexBaseModel

Response for thread/unarchive request.

Source code in src/codexed/models/responses.py
class ThreadUnarchiveResponse(CodexBaseModel):
    """Response for thread/unarchive request."""

    thread: Thread

ThreadUnarchivedMessage

Bases: CodexBaseModel

Notification sent from the server to the client.

Source code in src/codexed/models/v2_protocol.py
class ThreadUnarchivedMessage(CodexBaseModel):
    """Notification sent from the server to the client."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["thread/unarchived"] = "thread/unarchived"
    params: ThreadUnarchivedNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

TransportClosedError

Bases: CodexProcessError

Raised when the app-server transport closes unexpectedly.

Source code in src/codexed/exceptions.py
class TransportClosedError(CodexProcessError):
    """Raised when the app-server transport closes unexpectedly."""

TurnCompletedData

Bases: CodexBaseModel

Payload for turn/completed notification (V2 protocol).

Source code in src/codexed/models/event_data.py
class TurnCompletedData(CodexBaseModel):
    """Payload for turn/completed notification (V2 protocol)."""

    thread_id: str
    turn: Turn

TurnCompletedEvent

Bases: CodexBaseModel

Turn completed event.

Source code in src/codexed/models/events.py
class TurnCompletedEvent(CodexBaseModel):
    """Turn completed event."""

    method: Literal["turn/completed"] = "turn/completed"
    params: TurnCompletedData

TurnFailedError

Bases: CodexError

Raised when a turn completes with failed status.

Source code in src/codexed/exceptions.py
class TurnFailedError(CodexError):
    """Raised when a turn completes with failed status."""

    def __init__(self, message: str, *, turn_id: str) -> None:
        super().__init__(message)
        self.turn_id = turn_id

TurnPlanUpdatedMessage

Bases: CodexBaseModel

Notification sent from the server to the client.

Source code in src/codexed/models/v2_protocol.py
class TurnPlanUpdatedMessage(CodexBaseModel):
    """Notification sent from the server to the client."""

    emitted_at_ms: int | None = None
    """
    Unix timestamp (in milliseconds) when app-server emitted this notification.
    """
    method: Literal["turn/plan/updated"] = "turn/plan/updated"
    params: TurnPlanUpdatedNotification

emitted_at_ms class-attribute instance-attribute

emitted_at_ms: int | None = None

Unix timestamp (in milliseconds) when app-server emitted this notification.

TurnStartedData

Bases: CodexBaseModel

Payload for turn/started notification (V2 protocol).

Source code in src/codexed/models/event_data.py
class TurnStartedData(CodexBaseModel):
    """Payload for turn/started notification (V2 protocol)."""

    thread_id: str
    turn: Turn

TurnStartedEvent

Bases: CodexBaseModel

Turn started event.

Source code in src/codexed/models/events.py
class TurnStartedEvent(CodexBaseModel):
    """Turn started event."""

    method: Literal["turn/started"] = "turn/started"
    params: TurnStartedData

WebSocketTransport

Transport that connects to a remote Codex app-server via WebSocket.

Requires the websockets package (pip install codexed[websocket]).

Source code in src/codexed/transport.py
class WebSocketTransport:
    """Transport that connects to a remote Codex app-server via WebSocket.

    Requires the ``websockets`` package (``pip install codexed[websocket]``).
    """

    def __init__(
        self,
        url: str,
        *,
        auth_token: str | None = None,
        extra_headers: dict[str, str] | None = None,
    ) -> None:
        self._url = url
        self._auth_token = auth_token
        self._extra_headers = extra_headers or {}
        self._ws: Any = None
        self._writer_lock = asyncio.Lock()

    async def start(self) -> None:
        import websockets

        if self._ws is not None:
            return
        headers = dict(self._extra_headers)
        if self._auth_token:
            headers["Authorization"] = f"Bearer {self._auth_token}"

        self._ws = await websockets.connect(self._url, additional_headers=headers)

    async def stop(self) -> None:
        if self._ws is None:
            return
        with contextlib.suppress(Exception):
            await self._ws.close()
        self._ws = None

    async def send(self, message: dict[str, Any]) -> None:
        if self._ws is None:
            raise TransportClosedError("WebSocket not connected")
        async with self._writer_lock:
            await self._ws.send(anyenv.dump_json(message))

    async def receive(self) -> dict[str, Any] | None:
        if self._ws is None:
            return None
        while True:
            try:
                raw: str | bytes = await self._ws.recv()
            except Exception as exc:  # noqa: BLE001
                logger.debug("WebSocket closed: %s", exc)
                return None
            if isinstance(raw, bytes):
                raw = raw.decode(errors="replace")
            if (message := _parse_line(raw)) is not None:
                return message

    @property
    def is_connected(self) -> bool:
        return self._ws is not None

is_retryable_error

is_retryable_error(exc: BaseException) -> bool

Check if an exception is a transient overload-style error worth retrying.

Parameters:

Name Type Description Default
exc BaseException

The exception to check.

required

Returns:

Type Description
bool

True if the error is transient and the operation should be retried.

Source code in src/codexed/exceptions.py
def is_retryable_error(exc: BaseException) -> bool:
    """Check if an exception is a transient overload-style error worth retrying.

    Args:
        exc: The exception to check.

    Returns:
        True if the error is transient and the operation should be retried.
    """
    if isinstance(exc, ServerBusyError):
        return True
    if isinstance(exc, CodexRequestError):
        return _is_server_overloaded(exc.data)
    return False

tools_to_config_dict

tools_to_config_dict(tools: list[ToolConfig]) -> dict[str, Any]

Convert a list of tool configs into the config dict for ThreadStartParams.

Each tool config contributes its settings to the appropriate config keys. An empty list explicitly disables all builtin tools.

Example::

config = tools_to_config_dict([])  # disable all tools
config = tools_to_config_dict([    # enable only these
    WebSearchToolConfig(mode="live", context_size="high"),
    JsReplToolConfig(),
])
Source code in src/codexed/models/tool_config.py
def tools_to_config_dict(tools: list[ToolConfig]) -> dict[str, Any]:
    """Convert a list of tool configs into the ``config`` dict for ``ThreadStartParams``.

    Each tool config contributes its settings to the appropriate config keys.
    An empty list explicitly disables all builtin tools.

    Example::

        config = tools_to_config_dict([])  # disable all tools
        config = tools_to_config_dict([    # enable only these
            WebSearchToolConfig(mode="live", context_size="high"),
            JsReplToolConfig(),
        ])
    """
    if not tools:
        return _disable_all_tools()

    features: dict[str, bool] = {}
    config: dict[str, Any] = {}
    tools_section: dict[str, Any] = {}
    experimental_tools: list[str] = []

    for tool in tools:
        match tool:
            case ShellToolConfig(allow_login_shell=allow_login):
                features["shell_tool"] = True
                if allow_login is not None:
                    config["allow_login_shell"] = allow_login

            case ApplyPatchToolConfig(variant=variant):
                config["include_apply_patch_tool"] = True
                match variant:
                    case "freeform":
                        features["apply_patch_freeform"] = True
                    case "function":
                        features["apply_patch_freeform"] = False
                    case None:
                        pass
                    case _ as unreachable:
                        assert_never(unreachable)

            case WebSearchToolConfig(
                mode=mode,
                context_size=context_size,
                allowed_domains=allowed_domains,
                location=location,
            ):
                if mode is not None:
                    config["web_search"] = mode
                ws_config: dict[str, Any] = {}
                if context_size is not None:
                    ws_config["context_size"] = context_size
                if allowed_domains is not None:
                    ws_config["allowed_domains"] = allowed_domains
                if location is not None and (loc := location.model_dump(exclude_none=True)):
                    ws_config["location"] = loc
                if ws_config:
                    tools_section["web_search"] = ws_config

            case ImageGenerationToolConfig():
                features["image_generation"] = True

            case ViewImageToolConfig():
                tools_section["view_image"] = True

            case JsReplToolConfig():
                features["js_repl"] = True

            case CollabToolsConfig():
                features["multi_agent"] = True

            case AgentJobsToolsConfig():
                features["enable_fanout"] = True

            case RequestPermissionsToolConfig():
                features["request_permissions_tool"] = True

            case ArtifactsToolConfig():
                features["artifact"] = True

            case ToolSuggestToolConfig():
                features["tool_suggest"] = True

            case GrepFilesToolConfig():
                experimental_tools.append("grep_files")

            case ReadFileToolConfig():
                experimental_tools.append("read_file")

            case ListDirToolConfig():
                experimental_tools.append("list_dir")

            case (
                PlanToolConfig()
                | RequestUserInputToolConfig()
                | ToolSearchToolConfig()
                | McpResourceToolsConfig()
            ):
                pass  # No config keys to emit for these currently

    if features:
        config["features"] = features
    if tools_section:
        config["tools"] = tools_section
    if experimental_tools:
        config["experimental_supported_tools"] = experimental_tools

    return config