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/api.py ADDED
@@ -0,0 +1,901 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from dataclasses import dataclass, field
5
+ from typing import AsyncIterator, Iterator
6
+
7
+ from ._approval_mode import (
8
+ ApprovalMode as ApprovalMode,
9
+ _approval_mode_override_settings,
10
+ _approval_mode_settings,
11
+ )
12
+ from ._initialize_metadata import validate_initialize_metadata
13
+ from ._inputs import (
14
+ ExternalMessage as ExternalMessage,
15
+ ImageInput as ImageInput,
16
+ Input as Input,
17
+ InputItem as InputItem,
18
+ LocalImageInput as LocalImageInput,
19
+ MentionInput as MentionInput,
20
+ RunInput,
21
+ SkillInput as SkillInput,
22
+ TextInput as TextInput,
23
+ _normalize_run_input,
24
+ _to_wire_input,
25
+ _to_wire_turn_input,
26
+ )
27
+ from ._login import (
28
+ AsyncChatgptLoginHandle,
29
+ AsyncDeviceCodeLoginHandle,
30
+ ChatgptLoginHandle,
31
+ DeviceCodeLoginHandle,
32
+ async_start_chatgpt_login,
33
+ async_start_device_code_login,
34
+ start_chatgpt_login,
35
+ start_device_code_login,
36
+ )
37
+ from ._message_router import _TurnSubscription
38
+ from ._run import (
39
+ TurnResult,
40
+ _collect_async_turn_result,
41
+ _collect_turn_result,
42
+ )
43
+ from ._sandbox import Sandbox as Sandbox, _sandbox_mode, _sandbox_policy
44
+ from .async_client import AsyncCodexClient
45
+ from .client import CodexClient, CodexConfig
46
+ from .generated.v2_all import (
47
+ ApiKeyLoginAccountParams,
48
+ GetAccountParams,
49
+ GetAccountResponse,
50
+ LoginAccountParams,
51
+ ModelListResponse,
52
+ Personality,
53
+ ReasoningEffort,
54
+ ReasoningSummary,
55
+ SortDirection,
56
+ ThreadArchiveResponse,
57
+ ThreadCompactStartResponse,
58
+ ThreadForkParams,
59
+ ThreadListCwdFilter,
60
+ ThreadListParams,
61
+ ThreadListResponse,
62
+ ThreadReadResponse,
63
+ ThreadResumeParams,
64
+ ThreadSetNameResponse,
65
+ ThreadSortKey,
66
+ ThreadSource,
67
+ ThreadSourceKind,
68
+ ThreadStartParams,
69
+ ThreadStartSource,
70
+ TurnCompletedNotification,
71
+ TurnInterruptResponse,
72
+ TurnStartParams,
73
+ TurnSteerResponse,
74
+ )
75
+ from .models import InitializeResponse, JsonObject, Notification
76
+
77
+
78
+ class Codex:
79
+ """Synchronous client for creating threads and running Codex turns.
80
+
81
+ The client starts its runtime connection during construction. Use it as a
82
+ context manager so resources are closed promptly.
83
+ """
84
+
85
+ def __init__(self, config: CodexConfig | None = None) -> None:
86
+ self._client = CodexClient(config=config)
87
+ try:
88
+ self._client.start()
89
+ self._init = validate_initialize_metadata(self._client.initialize())
90
+ except Exception:
91
+ self._client.close()
92
+ raise
93
+
94
+ def __enter__(self) -> "Codex":
95
+ return self
96
+
97
+ def __exit__(self, _exc_type, _exc, _tb) -> None:
98
+ self.close()
99
+
100
+ @property
101
+ def metadata(self) -> InitializeResponse:
102
+ return self._init
103
+
104
+ def close(self) -> None:
105
+ self._client.close()
106
+
107
+ def login_api_key(self, api_key: str) -> None:
108
+ """Authenticate Codex with an API key."""
109
+ self._client.account_login_start(
110
+ LoginAccountParams(
111
+ root=ApiKeyLoginAccountParams(
112
+ api_key=api_key,
113
+ type="apiKey",
114
+ )
115
+ )
116
+ )
117
+
118
+ def login_chatgpt(self) -> ChatgptLoginHandle:
119
+ """Start browser-based ChatGPT login and return its live handle."""
120
+ return start_chatgpt_login(self._client)
121
+
122
+ def login_chatgpt_device_code(self) -> DeviceCodeLoginHandle:
123
+ """Start device-code ChatGPT login and return its live handle."""
124
+ return start_device_code_login(self._client)
125
+
126
+ def account(self, *, refresh_token: bool = False) -> GetAccountResponse:
127
+ """Read the current Codex account state."""
128
+ return self._client.account_read(GetAccountParams(refresh_token=refresh_token))
129
+
130
+ def logout(self) -> None:
131
+ """Clear the current Codex account session."""
132
+ self._client.account_logout()
133
+
134
+ # BEGIN GENERATED: Codex.flat_methods
135
+ def thread_start(
136
+ self,
137
+ *,
138
+ approval_mode: ApprovalMode = ApprovalMode.auto_review,
139
+ base_instructions: str | None = None,
140
+ config: JsonObject | None = None,
141
+ cwd: str | None = None,
142
+ developer_instructions: str | None = None,
143
+ ephemeral: bool | None = None,
144
+ model: str | None = None,
145
+ model_provider: str | None = None,
146
+ personality: Personality | None = None,
147
+ sandbox: Sandbox | None = None,
148
+ service_name: str | None = None,
149
+ service_tier: str | None = None,
150
+ session_start_source: ThreadStartSource | None = None,
151
+ thread_source: ThreadSource | None = None,
152
+ ) -> Thread:
153
+ """Create a new Codex conversation thread."""
154
+ approval_policy, approvals_reviewer = _approval_mode_settings(approval_mode)
155
+ params = ThreadStartParams(
156
+ approval_policy=approval_policy,
157
+ approvals_reviewer=approvals_reviewer,
158
+ base_instructions=base_instructions,
159
+ config=config,
160
+ cwd=cwd,
161
+ developer_instructions=developer_instructions,
162
+ ephemeral=ephemeral,
163
+ model=model,
164
+ model_provider=model_provider,
165
+ personality=personality,
166
+ sandbox=_sandbox_mode(sandbox),
167
+ service_name=service_name,
168
+ service_tier=service_tier,
169
+ session_start_source=session_start_source,
170
+ thread_source=thread_source,
171
+ )
172
+ started = self._client.thread_start(params)
173
+ return Thread(self._client, started.thread.id)
174
+
175
+ def thread_list(
176
+ self,
177
+ *,
178
+ archived: bool | None = None,
179
+ cursor: str | None = None,
180
+ cwd: ThreadListCwdFilter | None = None,
181
+ limit: int | None = None,
182
+ model_providers: list[str] | None = None,
183
+ search_term: str | None = None,
184
+ section_id: str | None = None,
185
+ sort_direction: SortDirection | None = None,
186
+ sort_key: ThreadSortKey | None = None,
187
+ source_kinds: list[ThreadSourceKind] | None = None,
188
+ use_state_db_only: bool | None = None,
189
+ ) -> ThreadListResponse:
190
+ """List saved conversation threads."""
191
+ params = ThreadListParams(
192
+ archived=archived,
193
+ cursor=cursor,
194
+ cwd=cwd,
195
+ limit=limit,
196
+ model_providers=model_providers,
197
+ search_term=search_term,
198
+ section_id=section_id,
199
+ sort_direction=sort_direction,
200
+ sort_key=sort_key,
201
+ source_kinds=source_kinds,
202
+ use_state_db_only=use_state_db_only,
203
+ )
204
+ return self._client.thread_list(params)
205
+
206
+ def thread_resume(
207
+ self,
208
+ thread_id: str,
209
+ *,
210
+ approval_mode: ApprovalMode | None = None,
211
+ base_instructions: str | None = None,
212
+ config: JsonObject | None = None,
213
+ cwd: str | None = None,
214
+ developer_instructions: str | None = None,
215
+ include_turns: bool | None = None,
216
+ model: str | None = None,
217
+ model_provider: str | None = None,
218
+ personality: Personality | None = None,
219
+ sandbox: Sandbox | None = None,
220
+ service_tier: str | None = None,
221
+ ) -> Thread:
222
+ """Resume an existing conversation thread by ID.
223
+
224
+ include_turns controls the runtime response history, not model context.
225
+ Omit it to preserve the runtime default. Use thread.read() for history.
226
+ """
227
+ approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode)
228
+ params = ThreadResumeParams(
229
+ thread_id=thread_id,
230
+ approval_policy=approval_policy,
231
+ approvals_reviewer=approvals_reviewer,
232
+ base_instructions=base_instructions,
233
+ config=config,
234
+ cwd=cwd,
235
+ developer_instructions=developer_instructions,
236
+ exclude_turns=None if include_turns is None else not include_turns,
237
+ model=model,
238
+ model_provider=model_provider,
239
+ personality=personality,
240
+ sandbox=_sandbox_mode(sandbox),
241
+ service_tier=service_tier,
242
+ )
243
+ resumed = self._client.thread_resume(thread_id, params)
244
+ return Thread(self._client, resumed.thread.id)
245
+
246
+ def thread_fork(
247
+ self,
248
+ thread_id: str,
249
+ *,
250
+ approval_mode: ApprovalMode | None = None,
251
+ base_instructions: str | None = None,
252
+ config: JsonObject | None = None,
253
+ cwd: str | None = None,
254
+ developer_instructions: str | None = None,
255
+ ephemeral: bool | None = None,
256
+ include_turns: bool | None = None,
257
+ model: str | None = None,
258
+ model_provider: str | None = None,
259
+ sandbox: Sandbox | None = None,
260
+ service_tier: str | None = None,
261
+ thread_source: ThreadSource | None = None,
262
+ ) -> Thread:
263
+ """Create a new thread from an existing thread.
264
+
265
+ include_turns controls the runtime response history, not model context.
266
+ Omit it to preserve the runtime default. Use thread.read() for history.
267
+ """
268
+ approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode)
269
+ params = ThreadForkParams(
270
+ thread_id=thread_id,
271
+ approval_policy=approval_policy,
272
+ approvals_reviewer=approvals_reviewer,
273
+ base_instructions=base_instructions,
274
+ config=config,
275
+ cwd=cwd,
276
+ developer_instructions=developer_instructions,
277
+ ephemeral=ephemeral,
278
+ exclude_turns=None if include_turns is None else not include_turns,
279
+ model=model,
280
+ model_provider=model_provider,
281
+ sandbox=_sandbox_mode(sandbox),
282
+ service_tier=service_tier,
283
+ thread_source=thread_source,
284
+ )
285
+ forked = self._client.thread_fork(thread_id, params)
286
+ return Thread(self._client, forked.thread.id)
287
+
288
+ def thread_archive(self, thread_id: str) -> ThreadArchiveResponse:
289
+ """Archive a stored conversation thread."""
290
+ return self._client.thread_archive(thread_id)
291
+
292
+ def thread_unarchive(self, thread_id: str) -> Thread:
293
+ """Restore an archived conversation thread."""
294
+ unarchived = self._client.thread_unarchive(thread_id)
295
+ return Thread(self._client, unarchived.thread.id)
296
+
297
+ # END GENERATED: Codex.flat_methods
298
+
299
+ def models(self, *, include_hidden: bool = False) -> ModelListResponse:
300
+ """List available models reported by Codex.
301
+
302
+ The deprecated ``Model.supports_personality`` field is always ``False``
303
+ on the current app-server.
304
+ """
305
+ return self._client.model_list(include_hidden=include_hidden)
306
+
307
+
308
+ class AsyncCodex:
309
+ """Async mirror of :class:`Codex`.
310
+
311
+ Prefer ``async with AsyncCodex()`` so initialization and shutdown are
312
+ explicit and paired. The async client initializes lazily on context entry
313
+ or first awaited API use.
314
+ """
315
+
316
+ def __init__(self, config: CodexConfig | None = None) -> None:
317
+ self._client = AsyncCodexClient(config=config)
318
+ self._init: InitializeResponse | None = None
319
+ self._initialized = False
320
+ self._init_lock = asyncio.Lock()
321
+
322
+ async def __aenter__(self) -> "AsyncCodex":
323
+ await self._ensure_initialized()
324
+ return self
325
+
326
+ async def __aexit__(self, _exc_type, _exc, _tb) -> None:
327
+ await self.close()
328
+
329
+ async def _ensure_initialized(self) -> None:
330
+ if self._initialized:
331
+ return
332
+ async with self._init_lock:
333
+ if self._initialized:
334
+ return
335
+ try:
336
+ await self._client.start()
337
+ payload = await self._client.initialize()
338
+ self._init = validate_initialize_metadata(payload)
339
+ self._initialized = True
340
+ except Exception:
341
+ await self._client.close()
342
+ self._init = None
343
+ self._initialized = False
344
+ raise
345
+
346
+ @property
347
+ def metadata(self) -> InitializeResponse:
348
+ if self._init is None:
349
+ raise RuntimeError(
350
+ "AsyncCodex is not initialized yet. Prefer `async with AsyncCodex()`; "
351
+ "initialization also happens on first awaited API use."
352
+ )
353
+ return self._init
354
+
355
+ async def close(self) -> None:
356
+ await self._client.close()
357
+ self._init = None
358
+ self._initialized = False
359
+
360
+ async def login_api_key(self, api_key: str) -> None:
361
+ """Authenticate Codex with an API key."""
362
+ await self._ensure_initialized()
363
+ await self._client.account_login_start(
364
+ LoginAccountParams(
365
+ root=ApiKeyLoginAccountParams(
366
+ api_key=api_key,
367
+ type="apiKey",
368
+ )
369
+ )
370
+ )
371
+
372
+ async def login_chatgpt(self) -> AsyncChatgptLoginHandle:
373
+ """Start browser-based ChatGPT login and return its live handle."""
374
+ await self._ensure_initialized()
375
+ return await async_start_chatgpt_login(self)
376
+
377
+ async def login_chatgpt_device_code(self) -> AsyncDeviceCodeLoginHandle:
378
+ """Start device-code ChatGPT login and return its live handle."""
379
+ await self._ensure_initialized()
380
+ return await async_start_device_code_login(self)
381
+
382
+ async def account(self, *, refresh_token: bool = False) -> GetAccountResponse:
383
+ """Read the current Codex account state."""
384
+ await self._ensure_initialized()
385
+ return await self._client.account_read(GetAccountParams(refresh_token=refresh_token))
386
+
387
+ async def logout(self) -> None:
388
+ """Clear the current Codex account session."""
389
+ await self._ensure_initialized()
390
+ await self._client.account_logout()
391
+
392
+ # BEGIN GENERATED: AsyncCodex.flat_methods
393
+ async def thread_start(
394
+ self,
395
+ *,
396
+ approval_mode: ApprovalMode = ApprovalMode.auto_review,
397
+ base_instructions: str | None = None,
398
+ config: JsonObject | None = None,
399
+ cwd: str | None = None,
400
+ developer_instructions: str | None = None,
401
+ ephemeral: bool | None = None,
402
+ model: str | None = None,
403
+ model_provider: str | None = None,
404
+ personality: Personality | None = None,
405
+ sandbox: Sandbox | None = None,
406
+ service_name: str | None = None,
407
+ service_tier: str | None = None,
408
+ session_start_source: ThreadStartSource | None = None,
409
+ thread_source: ThreadSource | None = None,
410
+ ) -> AsyncThread:
411
+ """Create a new Codex conversation thread."""
412
+ await self._ensure_initialized()
413
+ approval_policy, approvals_reviewer = _approval_mode_settings(approval_mode)
414
+ params = ThreadStartParams(
415
+ approval_policy=approval_policy,
416
+ approvals_reviewer=approvals_reviewer,
417
+ base_instructions=base_instructions,
418
+ config=config,
419
+ cwd=cwd,
420
+ developer_instructions=developer_instructions,
421
+ ephemeral=ephemeral,
422
+ model=model,
423
+ model_provider=model_provider,
424
+ personality=personality,
425
+ sandbox=_sandbox_mode(sandbox),
426
+ service_name=service_name,
427
+ service_tier=service_tier,
428
+ session_start_source=session_start_source,
429
+ thread_source=thread_source,
430
+ )
431
+ started = await self._client.thread_start(params)
432
+ return AsyncThread(self, started.thread.id)
433
+
434
+ async def thread_list(
435
+ self,
436
+ *,
437
+ archived: bool | None = None,
438
+ cursor: str | None = None,
439
+ cwd: ThreadListCwdFilter | None = None,
440
+ limit: int | None = None,
441
+ model_providers: list[str] | None = None,
442
+ search_term: str | None = None,
443
+ section_id: str | None = None,
444
+ sort_direction: SortDirection | None = None,
445
+ sort_key: ThreadSortKey | None = None,
446
+ source_kinds: list[ThreadSourceKind] | None = None,
447
+ use_state_db_only: bool | None = None,
448
+ ) -> ThreadListResponse:
449
+ """List saved conversation threads."""
450
+ await self._ensure_initialized()
451
+ params = ThreadListParams(
452
+ archived=archived,
453
+ cursor=cursor,
454
+ cwd=cwd,
455
+ limit=limit,
456
+ model_providers=model_providers,
457
+ search_term=search_term,
458
+ section_id=section_id,
459
+ sort_direction=sort_direction,
460
+ sort_key=sort_key,
461
+ source_kinds=source_kinds,
462
+ use_state_db_only=use_state_db_only,
463
+ )
464
+ return await self._client.thread_list(params)
465
+
466
+ async def thread_resume(
467
+ self,
468
+ thread_id: str,
469
+ *,
470
+ approval_mode: ApprovalMode | None = None,
471
+ base_instructions: str | None = None,
472
+ config: JsonObject | None = None,
473
+ cwd: str | None = None,
474
+ developer_instructions: str | None = None,
475
+ include_turns: bool | None = None,
476
+ model: str | None = None,
477
+ model_provider: str | None = None,
478
+ personality: Personality | None = None,
479
+ sandbox: Sandbox | None = None,
480
+ service_tier: str | None = None,
481
+ ) -> AsyncThread:
482
+ """Resume an existing conversation thread by ID.
483
+
484
+ include_turns controls the runtime response history, not model context.
485
+ Omit it to preserve the runtime default. Use thread.read() for history.
486
+ """
487
+ await self._ensure_initialized()
488
+ approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode)
489
+ params = ThreadResumeParams(
490
+ thread_id=thread_id,
491
+ approval_policy=approval_policy,
492
+ approvals_reviewer=approvals_reviewer,
493
+ base_instructions=base_instructions,
494
+ config=config,
495
+ cwd=cwd,
496
+ developer_instructions=developer_instructions,
497
+ exclude_turns=None if include_turns is None else not include_turns,
498
+ model=model,
499
+ model_provider=model_provider,
500
+ personality=personality,
501
+ sandbox=_sandbox_mode(sandbox),
502
+ service_tier=service_tier,
503
+ )
504
+ resumed = await self._client.thread_resume(thread_id, params)
505
+ return AsyncThread(self, resumed.thread.id)
506
+
507
+ async def thread_fork(
508
+ self,
509
+ thread_id: str,
510
+ *,
511
+ approval_mode: ApprovalMode | None = None,
512
+ base_instructions: str | None = None,
513
+ config: JsonObject | None = None,
514
+ cwd: str | None = None,
515
+ developer_instructions: str | None = None,
516
+ ephemeral: bool | None = None,
517
+ include_turns: bool | None = None,
518
+ model: str | None = None,
519
+ model_provider: str | None = None,
520
+ sandbox: Sandbox | None = None,
521
+ service_tier: str | None = None,
522
+ thread_source: ThreadSource | None = None,
523
+ ) -> AsyncThread:
524
+ """Create a new thread from an existing thread.
525
+
526
+ include_turns controls the runtime response history, not model context.
527
+ Omit it to preserve the runtime default. Use thread.read() for history.
528
+ """
529
+ await self._ensure_initialized()
530
+ approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode)
531
+ params = ThreadForkParams(
532
+ thread_id=thread_id,
533
+ approval_policy=approval_policy,
534
+ approvals_reviewer=approvals_reviewer,
535
+ base_instructions=base_instructions,
536
+ config=config,
537
+ cwd=cwd,
538
+ developer_instructions=developer_instructions,
539
+ ephemeral=ephemeral,
540
+ exclude_turns=None if include_turns is None else not include_turns,
541
+ model=model,
542
+ model_provider=model_provider,
543
+ sandbox=_sandbox_mode(sandbox),
544
+ service_tier=service_tier,
545
+ thread_source=thread_source,
546
+ )
547
+ forked = await self._client.thread_fork(thread_id, params)
548
+ return AsyncThread(self, forked.thread.id)
549
+
550
+ async def thread_archive(self, thread_id: str) -> ThreadArchiveResponse:
551
+ """Archive a stored conversation thread."""
552
+ await self._ensure_initialized()
553
+ return await self._client.thread_archive(thread_id)
554
+
555
+ async def thread_unarchive(self, thread_id: str) -> AsyncThread:
556
+ """Restore an archived conversation thread."""
557
+ await self._ensure_initialized()
558
+ unarchived = await self._client.thread_unarchive(thread_id)
559
+ return AsyncThread(self, unarchived.thread.id)
560
+
561
+ # END GENERATED: AsyncCodex.flat_methods
562
+
563
+ async def models(self, *, include_hidden: bool = False) -> ModelListResponse:
564
+ """List available models reported by Codex.
565
+
566
+ The deprecated ``Model.supports_personality`` field is always ``False``
567
+ on the current app-server.
568
+ """
569
+ await self._ensure_initialized()
570
+ return await self._client.model_list(include_hidden=include_hidden)
571
+
572
+
573
+ @dataclass(slots=True)
574
+ class Thread:
575
+ """Synchronous conversation thread used to run one or more turns."""
576
+
577
+ _client: CodexClient
578
+ id: str
579
+
580
+ # BEGIN GENERATED: Thread.flat_methods
581
+ def run(
582
+ self,
583
+ input: RunInput,
584
+ *,
585
+ approval_mode: ApprovalMode | None = None,
586
+ cwd: str | None = None,
587
+ effort: ReasoningEffort | None = None,
588
+ model: str | None = None,
589
+ output_schema: JsonObject | None = None,
590
+ personality: Personality | None = None,
591
+ sandbox: Sandbox | None = None,
592
+ service_tier: str | None = None,
593
+ source: str | None = None,
594
+ summary: ReasoningSummary | None = None,
595
+ turn_service_tier: str | None = None,
596
+ ) -> TurnResult:
597
+ """Run a complete turn and collect its final result.
598
+
599
+ Accepts the same input and options as turn(), including ExternalMessage
600
+ for untrusted external content with tool-level authority.
601
+ """
602
+ turn = self.turn(
603
+ input,
604
+ approval_mode=approval_mode,
605
+ cwd=cwd,
606
+ effort=effort,
607
+ model=model,
608
+ output_schema=output_schema,
609
+ personality=personality,
610
+ sandbox=sandbox,
611
+ service_tier=service_tier,
612
+ source=source,
613
+ summary=summary,
614
+ turn_service_tier=turn_service_tier,
615
+ )
616
+ return turn.run()
617
+
618
+ def turn(
619
+ self,
620
+ input: RunInput,
621
+ *,
622
+ approval_mode: ApprovalMode | None = None,
623
+ cwd: str | None = None,
624
+ effort: ReasoningEffort | None = None,
625
+ model: str | None = None,
626
+ output_schema: JsonObject | None = None,
627
+ personality: Personality | None = None,
628
+ sandbox: Sandbox | None = None,
629
+ service_tier: str | None = None,
630
+ source: str | None = None,
631
+ summary: ReasoningSummary | None = None,
632
+ turn_service_tier: str | None = None,
633
+ ) -> TurnHandle:
634
+ """Start a turn or join an active regular turn and return its handle.
635
+
636
+ ExternalMessage supplies untrusted content with tool-level authority;
637
+ it does not establish user authorization or approval.
638
+ turn_service_tier applies only to this new turn; service_tier updates
639
+ the thread default. source labels what initiated a new turn and grants
640
+ no authority. Both turn_service_tier and source are ignored when joining.
641
+ """
642
+ wire_input, tool_output = _to_wire_turn_input(input)
643
+ approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode)
644
+ params = TurnStartParams(
645
+ thread_id=self.id,
646
+ input=wire_input,
647
+ tool_output=tool_output,
648
+ approval_policy=approval_policy,
649
+ approvals_reviewer=approvals_reviewer,
650
+ cwd=cwd,
651
+ effort=effort,
652
+ model=model,
653
+ output_schema=output_schema,
654
+ personality=personality,
655
+ sandbox_policy=_sandbox_policy(sandbox),
656
+ service_tier=service_tier,
657
+ turn_trigger=source,
658
+ summary=summary,
659
+ service_tier_for_turn=turn_service_tier,
660
+ )
661
+ turn, subscription = self._client._start_turn(
662
+ self.id, wire_input, params=params, for_handle=True
663
+ )
664
+ return TurnHandle(self._client, self.id, turn.turn.id, _subscription=subscription)
665
+
666
+ # END GENERATED: Thread.flat_methods
667
+
668
+ def read(self, *, include_turns: bool = False) -> ThreadReadResponse:
669
+ """Read this thread, optionally including its turn history."""
670
+ return self._client.thread_read(self.id, include_turns=include_turns)
671
+
672
+ def set_name(self, name: str) -> ThreadSetNameResponse:
673
+ return self._client.thread_set_name(self.id, name)
674
+
675
+ def compact(self) -> ThreadCompactStartResponse:
676
+ return self._client.thread_compact(self.id)
677
+
678
+
679
+ @dataclass(slots=True)
680
+ class AsyncThread:
681
+ """Asynchronous conversation thread used to run one or more turns."""
682
+
683
+ _codex: AsyncCodex
684
+ id: str
685
+
686
+ # BEGIN GENERATED: AsyncThread.flat_methods
687
+ async def run(
688
+ self,
689
+ input: RunInput,
690
+ *,
691
+ approval_mode: ApprovalMode | None = None,
692
+ cwd: str | None = None,
693
+ effort: ReasoningEffort | None = None,
694
+ model: str | None = None,
695
+ output_schema: JsonObject | None = None,
696
+ personality: Personality | None = None,
697
+ sandbox: Sandbox | None = None,
698
+ service_tier: str | None = None,
699
+ source: str | None = None,
700
+ summary: ReasoningSummary | None = None,
701
+ turn_service_tier: str | None = None,
702
+ ) -> TurnResult:
703
+ """Run a complete turn and collect its final result.
704
+
705
+ Accepts the same input and options as turn(), including ExternalMessage
706
+ for untrusted external content with tool-level authority.
707
+ """
708
+ turn = await self.turn(
709
+ input,
710
+ approval_mode=approval_mode,
711
+ cwd=cwd,
712
+ effort=effort,
713
+ model=model,
714
+ output_schema=output_schema,
715
+ personality=personality,
716
+ sandbox=sandbox,
717
+ service_tier=service_tier,
718
+ source=source,
719
+ summary=summary,
720
+ turn_service_tier=turn_service_tier,
721
+ )
722
+ return await turn.run()
723
+
724
+ async def turn(
725
+ self,
726
+ input: RunInput,
727
+ *,
728
+ approval_mode: ApprovalMode | None = None,
729
+ cwd: str | None = None,
730
+ effort: ReasoningEffort | None = None,
731
+ model: str | None = None,
732
+ output_schema: JsonObject | None = None,
733
+ personality: Personality | None = None,
734
+ sandbox: Sandbox | None = None,
735
+ service_tier: str | None = None,
736
+ source: str | None = None,
737
+ summary: ReasoningSummary | None = None,
738
+ turn_service_tier: str | None = None,
739
+ ) -> AsyncTurnHandle:
740
+ """Start a turn or join an active regular turn and return its handle.
741
+
742
+ ExternalMessage supplies untrusted content with tool-level authority;
743
+ it does not establish user authorization or approval.
744
+ turn_service_tier applies only to this new turn; service_tier updates
745
+ the thread default. source labels what initiated a new turn and grants
746
+ no authority. Both turn_service_tier and source are ignored when joining.
747
+ """
748
+ wire_input, tool_output = _to_wire_turn_input(input)
749
+ await self._codex._ensure_initialized()
750
+ approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode)
751
+ params = TurnStartParams(
752
+ thread_id=self.id,
753
+ input=wire_input,
754
+ tool_output=tool_output,
755
+ approval_policy=approval_policy,
756
+ approvals_reviewer=approvals_reviewer,
757
+ cwd=cwd,
758
+ effort=effort,
759
+ model=model,
760
+ output_schema=output_schema,
761
+ personality=personality,
762
+ sandbox_policy=_sandbox_policy(sandbox),
763
+ service_tier=service_tier,
764
+ turn_trigger=source,
765
+ summary=summary,
766
+ service_tier_for_turn=turn_service_tier,
767
+ )
768
+ turn, subscription = await self._codex._client._start_turn(
769
+ self.id, wire_input, params=params, for_handle=True
770
+ )
771
+ return AsyncTurnHandle(self._codex, self.id, turn.turn.id, _subscription=subscription)
772
+
773
+ # END GENERATED: AsyncThread.flat_methods
774
+
775
+ async def read(self, *, include_turns: bool = False) -> ThreadReadResponse:
776
+ """Read this thread, optionally including its turn history."""
777
+ await self._codex._ensure_initialized()
778
+ return await self._codex._client.thread_read(self.id, include_turns=include_turns)
779
+
780
+ async def set_name(self, name: str) -> ThreadSetNameResponse:
781
+ await self._codex._ensure_initialized()
782
+ return await self._codex._client.thread_set_name(self.id, name)
783
+
784
+ async def compact(self) -> ThreadCompactStartResponse:
785
+ await self._codex._ensure_initialized()
786
+ return await self._codex._client.thread_compact(self.id)
787
+
788
+
789
+ @dataclass(slots=True)
790
+ class TurnHandle:
791
+ """Control and consume a synchronous turn after it has started."""
792
+
793
+ _client: CodexClient
794
+ thread_id: str
795
+ id: str
796
+ _subscription: _TurnSubscription = field(init=False, repr=False, compare=False)
797
+
798
+ def __init__(
799
+ self, _client: CodexClient, thread_id: str, id: str, *, _subscription=None
800
+ ) -> None:
801
+ self._client, self.thread_id, self.id = _client, thread_id, id
802
+ if _subscription is None:
803
+ self.__post_init__()
804
+ else:
805
+ self._subscription = _subscription
806
+
807
+ def __post_init__(self) -> None:
808
+ self._subscription = self._client._subscribe_turn_notifications(self.id)
809
+
810
+ def steer(self, input: Input | str) -> TurnSteerResponse:
811
+ """Send additional user input to this active turn."""
812
+ return self._client.turn_steer(
813
+ self.thread_id,
814
+ self.id,
815
+ _to_wire_input(_normalize_run_input(input)),
816
+ )
817
+
818
+ def interrupt(self) -> TurnInterruptResponse:
819
+ """Request interruption of this active turn."""
820
+ return self._client.turn_interrupt(self.thread_id, self.id)
821
+
822
+ def stream(self) -> Iterator[Notification]:
823
+ """Yield only notifications routed to this turn handle."""
824
+ try:
825
+ while True:
826
+ event = self._subscription.next()
827
+ yield event
828
+ if (
829
+ event.method == "turn/completed"
830
+ and isinstance(event.payload, TurnCompletedNotification)
831
+ and event.payload.turn.id == self.id
832
+ ):
833
+ break
834
+ finally:
835
+ self._subscription.close()
836
+
837
+ def run(self) -> TurnResult:
838
+ """Consume the turn stream and return its completed result."""
839
+ stream = self.stream()
840
+ try:
841
+ return _collect_turn_result(stream, turn_id=self.id)
842
+ finally:
843
+ stream.close()
844
+
845
+
846
+ @dataclass(slots=True)
847
+ class AsyncTurnHandle:
848
+ """Control and consume an asynchronous turn after it has started."""
849
+
850
+ _codex: AsyncCodex
851
+ thread_id: str
852
+ id: str
853
+ _subscription: _TurnSubscription = field(init=False, repr=False, compare=False)
854
+
855
+ def __init__(self, _codex: AsyncCodex, thread_id: str, id: str, *, _subscription=None) -> None:
856
+ self._codex, self.thread_id, self.id = _codex, thread_id, id
857
+ if _subscription is None:
858
+ self.__post_init__()
859
+ else:
860
+ self._subscription = _subscription
861
+
862
+ def __post_init__(self) -> None:
863
+ self._subscription = self._codex._client._subscribe_turn_notifications(self.id)
864
+
865
+ async def steer(self, input: Input | str) -> TurnSteerResponse:
866
+ """Send additional user input to this active turn."""
867
+ await self._codex._ensure_initialized()
868
+ return await self._codex._client.turn_steer(
869
+ self.thread_id,
870
+ self.id,
871
+ _to_wire_input(_normalize_run_input(input)),
872
+ )
873
+
874
+ async def interrupt(self) -> TurnInterruptResponse:
875
+ """Request interruption of this active turn."""
876
+ await self._codex._ensure_initialized()
877
+ return await self._codex._client.turn_interrupt(self.thread_id, self.id)
878
+
879
+ async def stream(self) -> AsyncIterator[Notification]:
880
+ """Yield only notifications routed to this async turn handle."""
881
+ await self._codex._ensure_initialized()
882
+ try:
883
+ while True:
884
+ event = await asyncio.to_thread(self._subscription.next)
885
+ yield event
886
+ if (
887
+ event.method == "turn/completed"
888
+ and isinstance(event.payload, TurnCompletedNotification)
889
+ and event.payload.turn.id == self.id
890
+ ):
891
+ break
892
+ finally:
893
+ self._subscription.close()
894
+
895
+ async def run(self) -> TurnResult:
896
+ """Consume the turn stream and return its completed result."""
897
+ stream = self.stream()
898
+ try:
899
+ return await _collect_async_turn_result(stream, turn_id=self.id)
900
+ finally:
901
+ await stream.aclose()