circle-codex 0.154.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
openai_codex/client.py ADDED
@@ -0,0 +1,924 @@
1
+ import json
2
+ import os
3
+ import re
4
+ import subprocess
5
+ import threading
6
+ import uuid
7
+ from _thread import LockType
8
+ from collections import deque
9
+ from contextlib import contextmanager
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+ from typing import Callable, Iterator, TypeVar
13
+
14
+ from pydantic import BaseModel
15
+
16
+ from ._goal import _GoalOperationState
17
+ from ._initialize_metadata import _split_user_agent
18
+ from ._message_router import MessageRouter, _TurnSubscription
19
+ from ._runtime_requirements import CheckoutCapabilities, require_runtime_version
20
+ from ._version import __version__ as SDK_VERSION
21
+ from .errors import CodexError, InvalidRequestError, TransportClosedError
22
+ from .generated.notification_registry import NOTIFICATION_MODELS
23
+ from .generated.v2_all import (
24
+ AccountLoginCompletedNotification,
25
+ AgentMessageDeltaNotification,
26
+ CancelLoginAccountResponse,
27
+ ChatgptDeviceCodeLoginAccountResponse,
28
+ ChatgptLoginAccountResponse,
29
+ GetAccountParams as V2GetAccountParams,
30
+ GetAccountResponse,
31
+ IdleThreadStatus,
32
+ LoginAccountParams as V2LoginAccountParams,
33
+ LoginAccountResponse,
34
+ LogoutAccountResponse,
35
+ ModelListResponse,
36
+ ThreadArchiveResponse,
37
+ ThreadCompactStartResponse,
38
+ ThreadForkParams as V2ThreadForkParams,
39
+ ThreadForkResponse,
40
+ ThreadGoalClearResponse,
41
+ ThreadGoalSetResponse,
42
+ ThreadGoalStatus,
43
+ ThreadListParams as V2ThreadListParams,
44
+ ThreadListResponse,
45
+ ThreadReadResponse,
46
+ ThreadResumeParams as V2ThreadResumeParams,
47
+ ThreadResumeResponse,
48
+ ThreadSetNameResponse,
49
+ ThreadStartParams as V2ThreadStartParams,
50
+ ThreadStartResponse,
51
+ ThreadUnarchiveResponse,
52
+ TurnCompletedNotification,
53
+ TurnInterruptResponse,
54
+ TurnStartParams as V2TurnStartParams,
55
+ TurnStartResponse,
56
+ TurnSteerResponse,
57
+ )
58
+ from .models import (
59
+ InitializeResponse,
60
+ JsonObject,
61
+ JsonValue,
62
+ Notification,
63
+ UnknownNotification,
64
+ )
65
+ from .retry import retry_on_overload
66
+
67
+ ModelT = TypeVar("ModelT", bound=BaseModel)
68
+ ApprovalHandler = Callable[[str, JsonObject | None], JsonObject]
69
+ RUNTIME_PKG_NAME = "circle-codex-cli-bin"
70
+ _GOAL_START_TIMEOUT_S = 30.0
71
+
72
+
73
+ @dataclass(slots=True)
74
+ class _ThreadStartLock:
75
+ lock: LockType = field(default_factory=threading.Lock)
76
+ users: int = 0
77
+
78
+
79
+ def _active_turn_id_from_error(exc: InvalidRequestError) -> str | None:
80
+ match = re.search(r" but found `?([^`]+)`?$", exc.message)
81
+ return match.group(1) if match is not None else None
82
+
83
+
84
+ def _params_dict(
85
+ params: (
86
+ V2ThreadStartParams
87
+ | V2ThreadResumeParams
88
+ | V2ThreadListParams
89
+ | V2ThreadForkParams
90
+ | V2TurnStartParams
91
+ | V2GetAccountParams
92
+ | V2LoginAccountParams
93
+ | JsonObject
94
+ | None
95
+ ),
96
+ ) -> JsonObject:
97
+ if params is None:
98
+ return {}
99
+ if hasattr(params, "model_dump"):
100
+ dumped = params.model_dump(
101
+ by_alias=True,
102
+ exclude_none=True,
103
+ mode="json",
104
+ )
105
+ if not isinstance(dumped, dict):
106
+ raise TypeError("Expected model_dump() to return dict")
107
+ return dumped
108
+ if isinstance(params, dict):
109
+ return params
110
+ raise TypeError(f"Expected generated params model or dict, got {type(params).__name__}")
111
+
112
+
113
+ def _installed_codex_path() -> Path:
114
+ try:
115
+ from codex_cli_bin import bundled_codex_path
116
+ except ImportError as exc:
117
+ raise FileNotFoundError(
118
+ "Unable to locate the pinned Codex runtime. Install the published SDK build "
119
+ f"with its {RUNTIME_PKG_NAME} dependency, or set CodexConfig.codex_bin "
120
+ "explicitly."
121
+ ) from exc
122
+
123
+ return bundled_codex_path()
124
+
125
+
126
+ def _installed_codex_path_dirs() -> tuple[Path, ...]:
127
+ try:
128
+ from codex_cli_bin import bundled_path_dir
129
+ except (ImportError, AttributeError):
130
+ return ()
131
+
132
+ path_dir = bundled_path_dir()
133
+ return (path_dir,) if path_dir is not None else ()
134
+
135
+
136
+ def _prepend_path_dirs(env: dict[str, str], path_dirs: tuple[Path, ...]) -> None:
137
+ if not path_dirs:
138
+ return
139
+
140
+ path_key = _path_env_key(env)
141
+ if os.name == "nt":
142
+ for key in list(env):
143
+ if key.upper() == "PATH" and key != path_key:
144
+ env.pop(key)
145
+
146
+ path_sep = os.pathsep
147
+ existing_path = env.get(path_key, "")
148
+ path_dir_values = [str(path_dir) for path_dir in path_dirs]
149
+ existing_entries = [
150
+ entry for entry in existing_path.split(path_sep) if entry and entry not in path_dir_values
151
+ ]
152
+ env[path_key] = path_sep.join([*path_dir_values, *existing_entries])
153
+
154
+
155
+ def _path_env_key(env: dict[str, str]) -> str:
156
+ if os.name != "nt":
157
+ return "PATH"
158
+
159
+ matching_keys = [key for key in env if key.upper() == "PATH"]
160
+ if "Path" in matching_keys:
161
+ return "Path"
162
+ return matching_keys[-1] if matching_keys else "PATH"
163
+
164
+
165
+ @dataclass(frozen=True)
166
+ class CodexBinResolverOps:
167
+ installed_codex_path: Callable[[], Path]
168
+ path_exists: Callable[[Path], bool]
169
+
170
+
171
+ def _default_codex_bin_resolver_ops() -> CodexBinResolverOps:
172
+ return CodexBinResolverOps(
173
+ installed_codex_path=_installed_codex_path,
174
+ path_exists=lambda path: path.exists(),
175
+ )
176
+
177
+
178
+ def resolve_codex_bin(config: "CodexConfig", ops: CodexBinResolverOps) -> Path:
179
+ if config.codex_bin is not None:
180
+ codex_bin = Path(config.codex_bin)
181
+ if not ops.path_exists(codex_bin):
182
+ raise FileNotFoundError(
183
+ f"Codex binary not found at {codex_bin}. Set CodexConfig.codex_bin "
184
+ "to a valid binary path."
185
+ )
186
+ return codex_bin
187
+
188
+ return ops.installed_codex_path()
189
+
190
+
191
+ def _resolve_codex_bin(config: "CodexConfig") -> Path:
192
+ return resolve_codex_bin(config, _default_codex_bin_resolver_ops())
193
+
194
+
195
+ @dataclass(slots=True)
196
+ class CodexConfig:
197
+ """Configuration for launching and identifying the local Codex runtime.
198
+
199
+ Most callers can use ``Codex()`` without configuration. Set ``codex_bin``
200
+ only when intentionally using a specific local Codex executable.
201
+ """
202
+
203
+ codex_bin: str | None = None
204
+ launch_args_override: tuple[str, ...] | None = None
205
+ config_overrides: tuple[str, ...] = ()
206
+ cwd: str | None = None
207
+ env: dict[str, str] | None = None
208
+ client_name: str = "codex_python_sdk"
209
+ client_title: str = "Codex Python SDK"
210
+ client_version: str = SDK_VERSION
211
+ experimental_api: bool = True
212
+
213
+
214
+ class CodexClient:
215
+ """Synchronous typed JSON-RPC client for `codex app-server` over stdio."""
216
+
217
+ def __init__(
218
+ self,
219
+ config: CodexConfig | None = None,
220
+ approval_handler: ApprovalHandler | None = None,
221
+ ) -> None:
222
+ self.config = config or CodexConfig()
223
+ self._approval_handler = approval_handler or self._default_approval_handler
224
+ self._proc: subprocess.Popen[str] | None = None
225
+ self._lock = threading.Lock()
226
+ self._thread_start_locks_guard = threading.Lock()
227
+ self._thread_start_locks: dict[str, _ThreadStartLock] = {}
228
+ self._router = MessageRouter()
229
+ self._stderr_lines: deque[str] = deque(maxlen=400)
230
+ self._stderr_thread: threading.Thread | None = None
231
+ self._reader_thread: threading.Thread | None = None
232
+ self._runtime_version: str | None = None
233
+ self._checkout_capabilities: CheckoutCapabilities | None = None
234
+
235
+ def __enter__(self) -> "CodexClient":
236
+ self.start()
237
+ return self
238
+
239
+ def __exit__(self, _exc_type, _exc, _tb) -> None:
240
+ self.close()
241
+
242
+ def start(self) -> None:
243
+ if self._proc is not None:
244
+ return
245
+
246
+ path_dirs: tuple[Path, ...] = ()
247
+ if self.config.launch_args_override is not None:
248
+ args = list(self.config.launch_args_override)
249
+ else:
250
+ codex_bin = _resolve_codex_bin(self.config)
251
+ if self.config.codex_bin is None:
252
+ path_dirs = _installed_codex_path_dirs()
253
+ args = [str(codex_bin)]
254
+ for kv in self.config.config_overrides:
255
+ args.extend(["--config", kv])
256
+ args.extend(["app-server", "--listen", "stdio://"])
257
+
258
+ env = os.environ.copy()
259
+ if self.config.env:
260
+ env.update(self.config.env)
261
+ _prepend_path_dirs(env, path_dirs)
262
+
263
+ if self.config.launch_args_override is None:
264
+ self._checkout_capabilities = CheckoutCapabilities(
265
+ command=tuple(args[:-2]), cwd=self.config.cwd, env=env.copy()
266
+ )
267
+
268
+ self._proc = subprocess.Popen(
269
+ args,
270
+ stdin=subprocess.PIPE,
271
+ stdout=subprocess.PIPE,
272
+ stderr=subprocess.PIPE,
273
+ text=True,
274
+ encoding="utf-8",
275
+ cwd=self.config.cwd,
276
+ env=env,
277
+ bufsize=1,
278
+ )
279
+
280
+ self._start_stderr_drain_thread()
281
+ self._start_reader_thread()
282
+
283
+ def close(self) -> None:
284
+ self._runtime_version = None
285
+ self._checkout_capabilities = None
286
+ if self._proc is None:
287
+ return
288
+ proc = self._proc
289
+ self._proc = None
290
+
291
+ if proc.stdin:
292
+ proc.stdin.close()
293
+ try:
294
+ proc.terminate()
295
+ proc.wait(timeout=2)
296
+ except Exception:
297
+ proc.kill()
298
+
299
+ if self._stderr_thread and self._stderr_thread.is_alive():
300
+ self._stderr_thread.join(timeout=0.5)
301
+ if self._reader_thread and self._reader_thread.is_alive():
302
+ self._reader_thread.join(timeout=0.5)
303
+
304
+ def initialize(self) -> InitializeResponse:
305
+ self._runtime_version = None
306
+ result = self.request(
307
+ "initialize",
308
+ {
309
+ "clientInfo": {
310
+ "name": self.config.client_name,
311
+ "title": self.config.client_title,
312
+ "version": self.config.client_version,
313
+ },
314
+ "capabilities": {
315
+ "experimentalApi": self.config.experimental_api,
316
+ },
317
+ },
318
+ response_model=InitializeResponse,
319
+ )
320
+ version = result.serverInfo.version if result.serverInfo is not None else None
321
+ if not version or not version.strip():
322
+ _, version = _split_user_agent(result.userAgent or "")
323
+ self._runtime_version = version.split()[0] if version and version.strip() else None
324
+ self.notify("initialized", None)
325
+ return result
326
+
327
+ def request(
328
+ self,
329
+ method: str,
330
+ params: JsonObject | None,
331
+ *,
332
+ response_model: type[ModelT],
333
+ ) -> ModelT:
334
+ runtime_fields = {
335
+ "turn/start": ("toolOutput", "turnTrigger", "serviceTierForTurn"),
336
+ "thread/resume": ("excludeTurns",),
337
+ "thread/fork": ("excludeTurns",),
338
+ }
339
+ supplied_fields = [
340
+ field
341
+ for field in runtime_fields.get(method, ())
342
+ if (params or {}).get(field) is not None
343
+ ]
344
+ if supplied_fields:
345
+ try:
346
+ if self._runtime_version == "0.0.0":
347
+ if self._checkout_capabilities is None:
348
+ raise ValueError(
349
+ "Cannot verify an unversioned CLI with a custom launch command"
350
+ )
351
+ supported = self._checkout_capabilities.fields[method]
352
+ if missing := set(supplied_fields) - supported:
353
+ raise ValueError(
354
+ f"The checkout does not support {', '.join(sorted(missing))}"
355
+ )
356
+ else:
357
+ require_runtime_version(self._runtime_version)
358
+ except ValueError as exc:
359
+ raise CodexError(
360
+ f"{method} with {', '.join(supplied_fields)}: {exc}. "
361
+ "Configure CodexConfig.codex_bin with a supported CLI."
362
+ ) from exc
363
+ result = self._request_raw(method, params)
364
+ if not isinstance(result, dict):
365
+ raise CodexError(f"{method} response must be a JSON object")
366
+ return response_model.model_validate(result)
367
+
368
+ def _request_raw(self, method: str, params: JsonObject | None = None) -> JsonValue:
369
+ """Send a JSON-RPC request and wait for the reader thread to route its response."""
370
+ request_id = str(uuid.uuid4())
371
+ waiter = self._router.create_response_waiter(request_id)
372
+
373
+ try:
374
+ message: JsonObject = {"id": request_id, "method": method}
375
+ if params is not None:
376
+ message["params"] = params
377
+ self._write_message(message)
378
+ except BaseException:
379
+ self._router.discard_response_waiter(request_id)
380
+ raise
381
+
382
+ item = waiter.get()
383
+ if isinstance(item, BaseException):
384
+ raise item
385
+ return item
386
+
387
+ def notify(self, method: str, params: JsonObject | None = None) -> None:
388
+ """Send a JSON-RPC notification without waiting for a response."""
389
+ message: JsonObject = {"method": method}
390
+ if params is not None:
391
+ message["params"] = params
392
+ self._write_message(message)
393
+
394
+ def next_notification(self) -> Notification:
395
+ """Return the next notification that is not scoped to an active turn."""
396
+ return self._router.next_global_notification()
397
+
398
+ def register_login_notifications(self, login_id: str) -> None:
399
+ """Start routing notifications for one interactive login attempt."""
400
+ self._router.register_login(login_id)
401
+
402
+ def unregister_login_notifications(self, login_id: str) -> None:
403
+ """Stop routing notifications for one interactive login attempt."""
404
+ self._router.unregister_login(login_id)
405
+
406
+ def next_login_notification(self, login_id: str) -> Notification:
407
+ """Return the next routed notification for the requested login id."""
408
+ return self._router.next_login_notification(login_id)
409
+
410
+ def _subscribe_turn_notifications(self, turn_id: str) -> _TurnSubscription:
411
+ return self._router.subscribe_turn(turn_id)
412
+
413
+ def register_turn_notifications(self, turn_id: str) -> None:
414
+ """Start routing notifications for one turn into its dedicated queue."""
415
+ self._router.register_turn(turn_id)
416
+
417
+ def unregister_turn_notifications(self, turn_id: str) -> None:
418
+ """Stop routing notifications for one turn into its dedicated queue."""
419
+ self._router.unregister_turn(turn_id)
420
+
421
+ def next_turn_notification(self, turn_id: str) -> Notification:
422
+ """Return the next routed notification for the requested turn id."""
423
+ return self._router.next_turn_notification(turn_id)
424
+
425
+ def register_goal_operation(self, thread_id: str) -> _GoalOperationState:
426
+ """Register a private thread-scoped route for a logical goal turn."""
427
+ return self._router.register_goal(thread_id)
428
+
429
+ def reserve_goal_operation(self, thread_id: str) -> _GoalOperationState:
430
+ """Reserve a private thread route before replacing its stored goal."""
431
+ return self._router.reserve_goal(thread_id)
432
+
433
+ def unregister_goal_operation(self, state: _GoalOperationState) -> None:
434
+ """Release routing state for one logical goal turn."""
435
+ self._router.unregister_goal(state)
436
+
437
+ def next_goal_notification(self, state: _GoalOperationState) -> Notification:
438
+ """Wait for the next notification in a logical goal turn."""
439
+ return state.next_notification()
440
+
441
+ def account_login_start(
442
+ self,
443
+ params: V2LoginAccountParams | JsonObject,
444
+ ) -> LoginAccountResponse:
445
+ response = self.request(
446
+ "account/login/start",
447
+ _params_dict(params),
448
+ response_model=LoginAccountResponse,
449
+ )
450
+ response_root = response.root
451
+ if isinstance(
452
+ response_root,
453
+ ChatgptLoginAccountResponse | ChatgptDeviceCodeLoginAccountResponse,
454
+ ):
455
+ self.register_login_notifications(response_root.login_id)
456
+ return response
457
+
458
+ def account_login_cancel(self, login_id: str) -> CancelLoginAccountResponse:
459
+ return self.request(
460
+ "account/login/cancel",
461
+ {"loginId": login_id},
462
+ response_model=CancelLoginAccountResponse,
463
+ )
464
+
465
+ def account_read(
466
+ self,
467
+ params: V2GetAccountParams | JsonObject | None = None,
468
+ ) -> GetAccountResponse:
469
+ return self.request(
470
+ "account/read",
471
+ _params_dict(params),
472
+ response_model=GetAccountResponse,
473
+ )
474
+
475
+ def account_logout(self) -> LogoutAccountResponse:
476
+ return self.request("account/logout", None, response_model=LogoutAccountResponse)
477
+
478
+ def thread_start(
479
+ self, params: V2ThreadStartParams | JsonObject | None = None
480
+ ) -> ThreadStartResponse:
481
+ return self.request(
482
+ "thread/start", _params_dict(params), response_model=ThreadStartResponse
483
+ )
484
+
485
+ def thread_resume(
486
+ self,
487
+ thread_id: str,
488
+ params: V2ThreadResumeParams | JsonObject | None = None,
489
+ ) -> ThreadResumeResponse:
490
+ payload = {"threadId": thread_id, **_params_dict(params)}
491
+ return self.request("thread/resume", payload, response_model=ThreadResumeResponse)
492
+
493
+ def thread_list(
494
+ self, params: V2ThreadListParams | JsonObject | None = None
495
+ ) -> ThreadListResponse:
496
+ return self.request("thread/list", _params_dict(params), response_model=ThreadListResponse)
497
+
498
+ def thread_read(self, thread_id: str, include_turns: bool = False) -> ThreadReadResponse:
499
+ return self.request(
500
+ "thread/read",
501
+ {"threadId": thread_id, "includeTurns": include_turns},
502
+ response_model=ThreadReadResponse,
503
+ )
504
+
505
+ def thread_fork(
506
+ self,
507
+ thread_id: str,
508
+ params: V2ThreadForkParams | JsonObject | None = None,
509
+ ) -> ThreadForkResponse:
510
+ payload = {"threadId": thread_id, **_params_dict(params)}
511
+ return self.request("thread/fork", payload, response_model=ThreadForkResponse)
512
+
513
+ def thread_archive(self, thread_id: str) -> ThreadArchiveResponse:
514
+ return self.request(
515
+ "thread/archive",
516
+ {"threadId": thread_id},
517
+ response_model=ThreadArchiveResponse,
518
+ )
519
+
520
+ def thread_unarchive(self, thread_id: str) -> ThreadUnarchiveResponse:
521
+ return self.request(
522
+ "thread/unarchive",
523
+ {"threadId": thread_id},
524
+ response_model=ThreadUnarchiveResponse,
525
+ )
526
+
527
+ def thread_set_name(self, thread_id: str, name: str) -> ThreadSetNameResponse:
528
+ return self.request(
529
+ "thread/name/set",
530
+ {"threadId": thread_id, "name": name},
531
+ response_model=ThreadSetNameResponse,
532
+ )
533
+
534
+ def thread_compact(self, thread_id: str) -> ThreadCompactStartResponse:
535
+ return self.request(
536
+ "thread/compact/start",
537
+ {"threadId": thread_id},
538
+ response_model=ThreadCompactStartResponse,
539
+ )
540
+
541
+ def thread_goal_clear(self, thread_id: str) -> ThreadGoalClearResponse:
542
+ """Clear the persisted goal for a thread before replacing it."""
543
+ return self.request(
544
+ "thread/goal/clear",
545
+ {"threadId": thread_id},
546
+ response_model=ThreadGoalClearResponse,
547
+ )
548
+
549
+ def thread_goal_set(
550
+ self,
551
+ thread_id: str,
552
+ *,
553
+ objective: str | None = None,
554
+ status: ThreadGoalStatus | None = None,
555
+ ) -> ThreadGoalSetResponse:
556
+ """Create or update the persisted goal for a thread."""
557
+ payload: JsonObject = {"threadId": thread_id}
558
+ if objective is not None:
559
+ payload["objective"] = objective
560
+ if status is not None:
561
+ payload["status"] = status.value
562
+ return self.request(
563
+ "thread/goal/set",
564
+ payload,
565
+ response_model=ThreadGoalSetResponse,
566
+ )
567
+
568
+ def pause_goal(self, thread_id: str) -> ThreadGoalSetResponse:
569
+ """Pause the active goal used by a logical goal turn."""
570
+ return self.thread_goal_set(thread_id, status=ThreadGoalStatus.paused)
571
+
572
+ def cancel_goal_operation(self, state: _GoalOperationState) -> None:
573
+ """Best-effort cleanup after a logical goal operation is cancelled."""
574
+ try:
575
+ self.pause_goal(state.thread_id)
576
+ except Exception:
577
+ pass
578
+ self._interrupt_goal_operation(state)
579
+
580
+ def _interrupt_goal_operation(self, state: _GoalOperationState) -> None:
581
+ turn_id = state.turn_for_interrupt()
582
+ if turn_id is None:
583
+ return
584
+ try:
585
+ self.turn_interrupt(state.thread_id, turn_id)
586
+ except InvalidRequestError as exc:
587
+ if not exc.message.startswith("expected active turn id"):
588
+ return
589
+ next_turn_id = _active_turn_id_from_error(exc) or state.current_turn()
590
+ if next_turn_id is None or next_turn_id == turn_id:
591
+ return
592
+ try:
593
+ self.turn_interrupt(state.thread_id, next_turn_id)
594
+ except Exception:
595
+ pass
596
+ except Exception:
597
+ pass
598
+
599
+ def start_goal_operation(
600
+ self,
601
+ thread_id: str,
602
+ objective: str,
603
+ ) -> tuple[_GoalOperationState, str]:
604
+ """Start a logical goal and wait for its runtime-generated first turn."""
605
+ with self._thread_start_lock(thread_id):
606
+ return self._start_goal_operation(thread_id, objective)
607
+
608
+ def _start_goal_operation(
609
+ self,
610
+ thread_id: str,
611
+ objective: str,
612
+ ) -> tuple[_GoalOperationState, str]:
613
+ thread = self.thread_read(thread_id).thread
614
+ if not isinstance(thread.status.root, IdleThreadStatus):
615
+ raise InvalidRequestError(
616
+ -32600,
617
+ f"thread must be idle before starting a goal: {thread_id}",
618
+ )
619
+ if thread.ephemeral or thread.path is None:
620
+ raise InvalidRequestError(
621
+ -32600,
622
+ f"thread must be persisted before starting a goal: {thread_id}",
623
+ )
624
+
625
+ state = self.reserve_goal_operation(thread_id)
626
+ activated = False
627
+ try:
628
+ self.thread_goal_clear(thread_id)
629
+ state.activate_turn_routing()
630
+ self.thread_goal_set(
631
+ thread_id,
632
+ objective=objective,
633
+ status=ThreadGoalStatus.active,
634
+ )
635
+ activated = True
636
+ turn_id = state.wait_for_start(_GOAL_START_TIMEOUT_S)
637
+ if turn_id is None:
638
+ raise CodexError(
639
+ "timed out waiting for goal turn to start after "
640
+ f"{int(_GOAL_START_TIMEOUT_S)} seconds"
641
+ )
642
+ return state, turn_id
643
+ except BaseException as exc:
644
+ if activated or not isinstance(exc, InvalidRequestError):
645
+ self.cancel_goal_operation(state)
646
+ state.finish()
647
+ self.unregister_goal_operation(state)
648
+ raise
649
+
650
+ def turn_start(
651
+ self,
652
+ thread_id: str,
653
+ input_items: list[JsonObject] | JsonObject | str,
654
+ params: V2TurnStartParams | JsonObject | None = None,
655
+ ) -> TurnStartResponse:
656
+ """Start a turn and register its notification queue as early as possible."""
657
+ return self._start_turn(thread_id, input_items, params, for_handle=False)[0]
658
+
659
+ def _start_turn(
660
+ self,
661
+ thread_id: str,
662
+ input_items: list[JsonObject] | JsonObject | str,
663
+ params: V2TurnStartParams | JsonObject | None,
664
+ for_handle: bool,
665
+ ) -> tuple[TurnStartResponse, _TurnSubscription | None]:
666
+ with self._thread_start_lock(thread_id):
667
+ if self._router.has_goal(thread_id):
668
+ raise InvalidRequestError(
669
+ -32600,
670
+ f"thread has an active goal operation: {thread_id}",
671
+ )
672
+ payload = {
673
+ **_params_dict(params),
674
+ "threadId": thread_id,
675
+ "input": self._normalize_input_items(input_items),
676
+ }
677
+ with self._router.pending_turn(thread_id) as cursors:
678
+ started = self.request("turn/start", payload, response_model=TurnStartResponse)
679
+ subscription = self._router.prepare_turn(
680
+ started.turn.id, thread_id, cursors, for_handle=for_handle
681
+ )
682
+ return started, subscription
683
+
684
+ @contextmanager
685
+ def _thread_start_lock(self, thread_id: str) -> Iterator[None]:
686
+ with self._thread_start_locks_guard:
687
+ entry = self._thread_start_locks.get(thread_id)
688
+ if entry is None:
689
+ entry = _ThreadStartLock()
690
+ self._thread_start_locks[thread_id] = entry
691
+ entry.users += 1
692
+ try:
693
+ with entry.lock:
694
+ yield
695
+ finally:
696
+ with self._thread_start_locks_guard:
697
+ entry.users -= 1
698
+ if entry.users == 0:
699
+ self._thread_start_locks.pop(thread_id, None)
700
+
701
+ def turn_interrupt(self, thread_id: str, turn_id: str) -> TurnInterruptResponse:
702
+ return self.request(
703
+ "turn/interrupt",
704
+ {"threadId": thread_id, "turnId": turn_id},
705
+ response_model=TurnInterruptResponse,
706
+ )
707
+
708
+ def turn_steer(
709
+ self,
710
+ thread_id: str,
711
+ expected_turn_id: str,
712
+ input_items: list[JsonObject] | JsonObject | str,
713
+ ) -> TurnSteerResponse:
714
+ return self.request(
715
+ "turn/steer",
716
+ {
717
+ "threadId": thread_id,
718
+ "expectedTurnId": expected_turn_id,
719
+ "input": self._normalize_input_items(input_items),
720
+ },
721
+ response_model=TurnSteerResponse,
722
+ )
723
+
724
+ def model_list(self, include_hidden: bool = False) -> ModelListResponse:
725
+ return self.request(
726
+ "model/list",
727
+ {"includeHidden": include_hidden},
728
+ response_model=ModelListResponse,
729
+ )
730
+
731
+ def request_with_retry_on_overload(
732
+ self,
733
+ method: str,
734
+ params: JsonObject | None,
735
+ *,
736
+ response_model: type[ModelT],
737
+ max_attempts: int = 3,
738
+ initial_delay_s: float = 0.25,
739
+ max_delay_s: float = 2.0,
740
+ ) -> ModelT:
741
+ return retry_on_overload(
742
+ lambda: self.request(method, params, response_model=response_model),
743
+ max_attempts=max_attempts,
744
+ initial_delay_s=initial_delay_s,
745
+ max_delay_s=max_delay_s,
746
+ )
747
+
748
+ def wait_for_turn_completed(self, turn_id: str) -> TurnCompletedNotification:
749
+ """Block on the routed turn stream until the matching completion arrives."""
750
+ self.register_turn_notifications(turn_id)
751
+ try:
752
+ while True:
753
+ notification = self.next_turn_notification(turn_id)
754
+ if (
755
+ notification.method == "turn/completed"
756
+ and isinstance(notification.payload, TurnCompletedNotification)
757
+ and notification.payload.turn.id == turn_id
758
+ ):
759
+ return notification.payload
760
+ finally:
761
+ self.unregister_turn_notifications(turn_id)
762
+
763
+ def wait_for_login_completed(
764
+ self,
765
+ login_id: str,
766
+ ) -> AccountLoginCompletedNotification:
767
+ """Block until the matching interactive login attempt completes."""
768
+ self.register_login_notifications(login_id)
769
+ try:
770
+ while True:
771
+ notification = self.next_login_notification(login_id)
772
+ if (
773
+ notification.method == "account/login/completed"
774
+ and isinstance(notification.payload, AccountLoginCompletedNotification)
775
+ and notification.payload.login_id == login_id
776
+ ):
777
+ return notification.payload
778
+ finally:
779
+ self.unregister_login_notifications(login_id)
780
+
781
+ def stream_text(
782
+ self,
783
+ thread_id: str,
784
+ text: str,
785
+ params: V2TurnStartParams | JsonObject | None = None,
786
+ ) -> Iterator[AgentMessageDeltaNotification]:
787
+ """Start a text turn and yield only its agent-message delta payloads."""
788
+ started = self.turn_start(thread_id, text, params=params)
789
+ turn_id = started.turn.id
790
+ self.register_turn_notifications(turn_id)
791
+ try:
792
+ while True:
793
+ notification = self.next_turn_notification(turn_id)
794
+ if (
795
+ notification.method == "item/agentMessage/delta"
796
+ and isinstance(notification.payload, AgentMessageDeltaNotification)
797
+ and notification.payload.turn_id == turn_id
798
+ ):
799
+ yield notification.payload
800
+ continue
801
+ if (
802
+ notification.method == "turn/completed"
803
+ and isinstance(notification.payload, TurnCompletedNotification)
804
+ and notification.payload.turn.id == turn_id
805
+ ):
806
+ break
807
+ finally:
808
+ self.unregister_turn_notifications(turn_id)
809
+
810
+ def _coerce_notification(self, method: str, params: object) -> Notification:
811
+ params_dict = params if isinstance(params, dict) else {}
812
+
813
+ model = NOTIFICATION_MODELS.get(method)
814
+ if model is None:
815
+ return Notification(method=method, payload=UnknownNotification(params=params_dict))
816
+
817
+ try:
818
+ payload = model.model_validate(params_dict)
819
+ except Exception: # noqa: BLE001
820
+ return Notification(method=method, payload=UnknownNotification(params=params_dict))
821
+ return Notification(method=method, payload=payload)
822
+
823
+ def _normalize_input_items(
824
+ self,
825
+ input_items: list[JsonObject] | JsonObject | str,
826
+ ) -> list[JsonObject]:
827
+ if isinstance(input_items, str):
828
+ return [{"type": "text", "text": input_items}]
829
+ if isinstance(input_items, dict):
830
+ return [input_items]
831
+ return input_items
832
+
833
+ def _default_approval_handler(self, method: str, params: JsonObject | None) -> JsonObject:
834
+ """Accept approval requests when the caller did not provide a handler."""
835
+ if method == "item/commandExecution/requestApproval":
836
+ return {"decision": "accept"}
837
+ if method == "item/fileChange/requestApproval":
838
+ return {"decision": "accept"}
839
+ return {}
840
+
841
+ def _start_stderr_drain_thread(self) -> None:
842
+ if self._proc is None or self._proc.stderr is None:
843
+ return
844
+
845
+ def _drain() -> None:
846
+ stderr = self._proc.stderr
847
+ if stderr is None:
848
+ return
849
+ for line in stderr:
850
+ self._stderr_lines.append(line.rstrip("\n"))
851
+
852
+ self._stderr_thread = threading.Thread(target=_drain, daemon=True)
853
+ self._stderr_thread.start()
854
+
855
+ def _start_reader_thread(self) -> None:
856
+ """Start the sole stdout reader that fans messages into router queues."""
857
+ if self._proc is None or self._proc.stdout is None:
858
+ return
859
+
860
+ self._reader_thread = threading.Thread(target=self._reader_loop, daemon=True)
861
+ self._reader_thread.start()
862
+
863
+ def _reader_loop(self) -> None:
864
+ """Continuously classify transport messages into requests, responses, and events."""
865
+ try:
866
+ while True:
867
+ msg = self._read_message()
868
+ if "method" in msg and "id" in msg:
869
+ response = self._handle_server_request(msg)
870
+ self._write_message({"id": msg["id"], "result": response})
871
+ continue
872
+ if "method" in msg and "id" not in msg:
873
+ method = msg["method"]
874
+ if isinstance(method, str):
875
+ self._router.route_notification(
876
+ self._coerce_notification(method, msg.get("params"))
877
+ )
878
+ continue
879
+ self._router.route_response(msg)
880
+ except BaseException as exc:
881
+ self._router.fail_all(exc)
882
+
883
+ def _stderr_tail(self, limit: int = 40) -> str:
884
+ return "\n".join(list(self._stderr_lines)[-limit:])
885
+
886
+ def _handle_server_request(self, msg: dict[str, JsonValue]) -> JsonObject:
887
+ method = msg["method"]
888
+ params = msg.get("params")
889
+ if not isinstance(method, str):
890
+ return {}
891
+ return self._approval_handler(
892
+ method,
893
+ params if isinstance(params, dict) else None,
894
+ )
895
+
896
+ def _write_message(self, payload: JsonObject) -> None:
897
+ if self._proc is None or self._proc.stdin is None:
898
+ raise TransportClosedError("Codex process is not running")
899
+ with self._lock:
900
+ self._proc.stdin.write(json.dumps(payload) + "\n")
901
+ self._proc.stdin.flush()
902
+
903
+ def _read_message(self) -> dict[str, JsonValue]:
904
+ if self._proc is None or self._proc.stdout is None:
905
+ raise TransportClosedError("Codex process is not running")
906
+
907
+ line = self._proc.stdout.readline()
908
+ if not line:
909
+ raise TransportClosedError(
910
+ f"Codex process closed stdout. stderr_tail={self._stderr_tail()[:2000]}"
911
+ )
912
+
913
+ try:
914
+ message = json.loads(line)
915
+ except json.JSONDecodeError as exc:
916
+ raise CodexError(f"Invalid JSON-RPC line: {line!r}") from exc
917
+
918
+ if not isinstance(message, dict):
919
+ raise CodexError(f"Invalid JSON-RPC payload: {message!r}")
920
+ return message
921
+
922
+
923
+ def default_codex_home() -> str:
924
+ return str(Path.home() / ".codex")