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.
@@ -0,0 +1,413 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import threading
5
+ from collections.abc import Iterator
6
+ from concurrent.futures import Future, ThreadPoolExecutor
7
+ from contextvars import copy_context
8
+ from typing import AsyncIterator, Callable, ParamSpec, TypeVar
9
+
10
+ from pydantic import BaseModel
11
+
12
+ from ._goal import _GoalOperationState
13
+ from ._message_router import _TurnSubscription
14
+ from .client import CodexClient, CodexConfig
15
+ from .generated.v2_all import (
16
+ AccountLoginCompletedNotification,
17
+ AgentMessageDeltaNotification,
18
+ CancelLoginAccountResponse,
19
+ GetAccountParams as V2GetAccountParams,
20
+ GetAccountResponse,
21
+ LoginAccountParams as V2LoginAccountParams,
22
+ LoginAccountResponse,
23
+ LogoutAccountResponse,
24
+ ModelListResponse,
25
+ ThreadArchiveResponse,
26
+ ThreadCompactStartResponse,
27
+ ThreadForkParams as V2ThreadForkParams,
28
+ ThreadForkResponse,
29
+ ThreadGoalClearResponse,
30
+ ThreadGoalSetResponse,
31
+ ThreadGoalStatus,
32
+ ThreadListParams as V2ThreadListParams,
33
+ ThreadListResponse,
34
+ ThreadReadResponse,
35
+ ThreadResumeParams as V2ThreadResumeParams,
36
+ ThreadResumeResponse,
37
+ ThreadSetNameResponse,
38
+ ThreadStartParams as V2ThreadStartParams,
39
+ ThreadStartResponse,
40
+ ThreadUnarchiveResponse,
41
+ TurnCompletedNotification,
42
+ TurnInterruptResponse,
43
+ TurnStartParams as V2TurnStartParams,
44
+ TurnStartResponse,
45
+ TurnSteerResponse,
46
+ )
47
+ from .models import InitializeResponse, JsonObject, Notification
48
+
49
+ ModelT = TypeVar("ModelT", bound=BaseModel)
50
+ ParamsT = ParamSpec("ParamsT")
51
+ ReturnT = TypeVar("ReturnT")
52
+
53
+ # Bound workers while allowing cancellation cleanup to outlive an asyncio waiter.
54
+ _TURN_START_EXECUTOR = ThreadPoolExecutor(thread_name_prefix="codex-turn-start")
55
+
56
+
57
+ class AsyncCodexClient:
58
+ """Async wrapper around CodexClient using thread offloading."""
59
+
60
+ def __init__(self, config: CodexConfig | None = None) -> None:
61
+ """Create the wrapped sync client that owns the transport process."""
62
+ self._sync = CodexClient(config=config)
63
+
64
+ async def __aenter__(self) -> "AsyncCodexClient":
65
+ """Start the Codex process when entering an async context."""
66
+ await self.start()
67
+ return self
68
+
69
+ async def __aexit__(self, _exc_type, _exc, _tb) -> None:
70
+ """Close the Codex process when leaving an async context."""
71
+ await self.close()
72
+
73
+ async def _call_sync(
74
+ self,
75
+ fn: Callable[ParamsT, ReturnT],
76
+ /,
77
+ *args: ParamsT.args,
78
+ **kwargs: ParamsT.kwargs,
79
+ ) -> ReturnT:
80
+ """Run a blocking sync-client operation without blocking the event loop."""
81
+ return await asyncio.to_thread(fn, *args, **kwargs)
82
+
83
+ @staticmethod
84
+ def _next_from_iterator(
85
+ iterator: Iterator[AgentMessageDeltaNotification],
86
+ ) -> tuple[bool, AgentMessageDeltaNotification | None]:
87
+ """Convert StopIteration into a value that can cross asyncio.to_thread."""
88
+ try:
89
+ return True, next(iterator)
90
+ except StopIteration:
91
+ return False, None
92
+
93
+ async def start(self) -> None:
94
+ """Start the wrapped sync client in a worker thread."""
95
+ await self._call_sync(self._sync.start)
96
+
97
+ async def close(self) -> None:
98
+ """Close the wrapped sync client in a worker thread."""
99
+ await self._call_sync(self._sync.close)
100
+
101
+ async def initialize(self) -> InitializeResponse:
102
+ """Initialize the Codex session."""
103
+ return await self._call_sync(self._sync.initialize)
104
+
105
+ def _subscribe_turn_notifications(self, turn_id: str) -> _TurnSubscription:
106
+ return self._sync._subscribe_turn_notifications(turn_id)
107
+
108
+ def register_turn_notifications(self, turn_id: str) -> None:
109
+ """Register a turn notification queue on the wrapped sync client."""
110
+ self._sync.register_turn_notifications(turn_id)
111
+
112
+ def register_login_notifications(self, login_id: str) -> None:
113
+ """Register a login notification queue on the wrapped sync client."""
114
+ self._sync.register_login_notifications(login_id)
115
+
116
+ def unregister_login_notifications(self, login_id: str) -> None:
117
+ """Unregister a login notification queue on the wrapped sync client."""
118
+ self._sync.unregister_login_notifications(login_id)
119
+
120
+ def unregister_turn_notifications(self, turn_id: str) -> None:
121
+ """Unregister a turn notification queue on the wrapped sync client."""
122
+ self._sync.unregister_turn_notifications(turn_id)
123
+
124
+ def register_goal_operation(self, thread_id: str) -> _GoalOperationState:
125
+ """Register a logical goal route on the wrapped sync client."""
126
+ return self._sync.register_goal_operation(thread_id)
127
+
128
+ def unregister_goal_operation(self, state: _GoalOperationState) -> None:
129
+ """Release one logical goal route."""
130
+ self._sync.unregister_goal_operation(state)
131
+
132
+ async def request(
133
+ self,
134
+ method: str,
135
+ params: JsonObject | None,
136
+ *,
137
+ response_model: type[ModelT],
138
+ ) -> ModelT:
139
+ """Send a typed JSON-RPC request through the wrapped sync client."""
140
+ return await self._call_sync(
141
+ self._sync.request,
142
+ method,
143
+ params,
144
+ response_model=response_model,
145
+ )
146
+
147
+ async def account_login_start(
148
+ self,
149
+ params: V2LoginAccountParams | JsonObject,
150
+ ) -> LoginAccountResponse:
151
+ """Start one account login attempt through the wrapped sync client."""
152
+ return await self._call_sync(self._sync.account_login_start, params)
153
+
154
+ async def account_login_cancel(self, login_id: str) -> CancelLoginAccountResponse:
155
+ """Cancel one active account login attempt through the wrapped sync client."""
156
+ return await self._call_sync(self._sync.account_login_cancel, login_id)
157
+
158
+ async def account_read(
159
+ self,
160
+ params: V2GetAccountParams | JsonObject | None = None,
161
+ ) -> GetAccountResponse:
162
+ """Read current account state through the wrapped sync client."""
163
+ return await self._call_sync(self._sync.account_read, params)
164
+
165
+ async def account_logout(self) -> LogoutAccountResponse:
166
+ """Clear the active account session through the wrapped sync client."""
167
+ return await self._call_sync(self._sync.account_logout)
168
+
169
+ async def thread_start(
170
+ self, params: V2ThreadStartParams | JsonObject | None = None
171
+ ) -> ThreadStartResponse:
172
+ """Start a thread using the wrapped sync client."""
173
+ return await self._call_sync(self._sync.thread_start, params)
174
+
175
+ async def thread_resume(
176
+ self,
177
+ thread_id: str,
178
+ params: V2ThreadResumeParams | JsonObject | None = None,
179
+ ) -> ThreadResumeResponse:
180
+ """Resume a thread using the wrapped sync client."""
181
+ return await self._call_sync(self._sync.thread_resume, thread_id, params)
182
+
183
+ async def thread_list(
184
+ self, params: V2ThreadListParams | JsonObject | None = None
185
+ ) -> ThreadListResponse:
186
+ """List threads using the wrapped sync client."""
187
+ return await self._call_sync(self._sync.thread_list, params)
188
+
189
+ async def thread_read(self, thread_id: str, include_turns: bool = False) -> ThreadReadResponse:
190
+ """Read a thread using the wrapped sync client."""
191
+ return await self._call_sync(self._sync.thread_read, thread_id, include_turns)
192
+
193
+ async def thread_fork(
194
+ self,
195
+ thread_id: str,
196
+ params: V2ThreadForkParams | JsonObject | None = None,
197
+ ) -> ThreadForkResponse:
198
+ """Fork a thread using the wrapped sync client."""
199
+ return await self._call_sync(self._sync.thread_fork, thread_id, params)
200
+
201
+ async def thread_archive(self, thread_id: str) -> ThreadArchiveResponse:
202
+ """Archive a thread using the wrapped sync client."""
203
+ return await self._call_sync(self._sync.thread_archive, thread_id)
204
+
205
+ async def thread_unarchive(self, thread_id: str) -> ThreadUnarchiveResponse:
206
+ """Unarchive a thread using the wrapped sync client."""
207
+ return await self._call_sync(self._sync.thread_unarchive, thread_id)
208
+
209
+ async def thread_set_name(self, thread_id: str, name: str) -> ThreadSetNameResponse:
210
+ """Rename a thread using the wrapped sync client."""
211
+ return await self._call_sync(self._sync.thread_set_name, thread_id, name)
212
+
213
+ async def thread_compact(self, thread_id: str) -> ThreadCompactStartResponse:
214
+ """Start thread compaction using the wrapped sync client."""
215
+ return await self._call_sync(self._sync.thread_compact, thread_id)
216
+
217
+ async def thread_goal_clear(self, thread_id: str) -> ThreadGoalClearResponse:
218
+ """Clear the persisted goal through the wrapped sync client."""
219
+ return await self._call_sync(self._sync.thread_goal_clear, thread_id)
220
+
221
+ async def thread_goal_set(
222
+ self,
223
+ thread_id: str,
224
+ *,
225
+ objective: str | None = None,
226
+ status: ThreadGoalStatus | None = None,
227
+ ) -> ThreadGoalSetResponse:
228
+ """Create or update a persisted goal through the wrapped sync client."""
229
+ return await self._call_sync(
230
+ self._sync.thread_goal_set,
231
+ thread_id,
232
+ objective=objective,
233
+ status=status,
234
+ )
235
+
236
+ async def pause_goal(self, thread_id: str) -> ThreadGoalSetResponse:
237
+ """Pause the active goal through the wrapped sync client."""
238
+ return await self._call_sync(self._sync.pause_goal, thread_id)
239
+
240
+ async def cancel_goal_operation(self, state: _GoalOperationState) -> None:
241
+ """Stop continuation work after a logical goal operation is cancelled."""
242
+ await self._call_sync(self._sync.cancel_goal_operation, state)
243
+
244
+ async def start_goal_operation(
245
+ self,
246
+ thread_id: str,
247
+ objective: str,
248
+ ) -> tuple[_GoalOperationState, str]:
249
+ """Start a logical goal through the wrapped sync client."""
250
+ operation: Future[tuple[_GoalOperationState, str]] = Future()
251
+
252
+ def start_operation() -> None:
253
+ try:
254
+ operation.set_result(self._sync.start_goal_operation(thread_id, objective))
255
+ except BaseException as exc:
256
+ operation.set_exception(exc)
257
+
258
+ worker = threading.Thread(
259
+ target=start_operation,
260
+ name="codex-goal-start",
261
+ daemon=True,
262
+ )
263
+ worker.start()
264
+ try:
265
+ return await asyncio.shield(asyncio.wrap_future(operation))
266
+ except asyncio.CancelledError:
267
+
268
+ def cleanup_cancelled_start(
269
+ completed: Future[tuple[_GoalOperationState, str]],
270
+ ) -> None:
271
+ try:
272
+ state, _ = completed.result()
273
+ except BaseException:
274
+ return
275
+
276
+ def stop_cancelled_goal() -> None:
277
+ try:
278
+ self._sync.cancel_goal_operation(state)
279
+ finally:
280
+ state.finish()
281
+ self._sync.unregister_goal_operation(state)
282
+
283
+ threading.Thread(
284
+ target=stop_cancelled_goal,
285
+ name="codex-goal-start-cleanup",
286
+ daemon=True,
287
+ ).start()
288
+
289
+ operation.add_done_callback(cleanup_cancelled_start)
290
+ raise
291
+
292
+ async def turn_start(
293
+ self,
294
+ thread_id: str,
295
+ input_items: list[JsonObject] | JsonObject | str,
296
+ params: V2TurnStartParams | JsonObject | None = None,
297
+ ) -> TurnStartResponse:
298
+ """Start a turn, releasing an unclaimed result if the caller is cancelled."""
299
+ return (await self._start_turn(thread_id, input_items, params, for_handle=False))[0]
300
+
301
+ async def _start_turn(
302
+ self,
303
+ thread_id: str,
304
+ input_items: list[JsonObject] | JsonObject | str,
305
+ params: V2TurnStartParams | JsonObject | None,
306
+ for_handle: bool,
307
+ ) -> tuple[TurnStartResponse, _TurnSubscription | None]:
308
+ operation = _TURN_START_EXECUTOR.submit(
309
+ copy_context().run, self._sync._start_turn, thread_id, input_items, params, for_handle
310
+ )
311
+ try:
312
+ return await asyncio.wrap_future(operation)
313
+ except asyncio.CancelledError:
314
+
315
+ def discard_cancelled_result(
316
+ completed: Future[tuple[TurnStartResponse, _TurnSubscription | None]],
317
+ ) -> None:
318
+ try:
319
+ _, subscription = completed.result()
320
+ except BaseException:
321
+ return
322
+ if subscription is not None:
323
+ subscription.close()
324
+
325
+ operation.add_done_callback(discard_cancelled_result)
326
+ raise
327
+
328
+ async def turn_interrupt(self, thread_id: str, turn_id: str) -> TurnInterruptResponse:
329
+ """Interrupt a turn using the wrapped sync client."""
330
+ return await self._call_sync(self._sync.turn_interrupt, thread_id, turn_id)
331
+
332
+ async def turn_steer(
333
+ self,
334
+ thread_id: str,
335
+ expected_turn_id: str,
336
+ input_items: list[JsonObject] | JsonObject | str,
337
+ ) -> TurnSteerResponse:
338
+ """Send steering input to a turn using the wrapped sync client."""
339
+ return await self._call_sync(
340
+ self._sync.turn_steer,
341
+ thread_id,
342
+ expected_turn_id,
343
+ input_items,
344
+ )
345
+
346
+ async def model_list(self, include_hidden: bool = False) -> ModelListResponse:
347
+ """List models using the wrapped sync client."""
348
+ return await self._call_sync(self._sync.model_list, include_hidden)
349
+
350
+ async def request_with_retry_on_overload(
351
+ self,
352
+ method: str,
353
+ params: JsonObject | None,
354
+ *,
355
+ response_model: type[ModelT],
356
+ max_attempts: int = 3,
357
+ initial_delay_s: float = 0.25,
358
+ max_delay_s: float = 2.0,
359
+ ) -> ModelT:
360
+ """Send a typed request with the sync client's overload retry policy."""
361
+ return await self._call_sync(
362
+ self._sync.request_with_retry_on_overload,
363
+ method,
364
+ params,
365
+ response_model=response_model,
366
+ max_attempts=max_attempts,
367
+ initial_delay_s=initial_delay_s,
368
+ max_delay_s=max_delay_s,
369
+ )
370
+
371
+ async def next_notification(self) -> Notification:
372
+ """Wait for the next global notification without blocking the event loop."""
373
+ return await self._call_sync(self._sync.next_notification)
374
+
375
+ async def next_login_notification(self, login_id: str) -> Notification:
376
+ """Wait for the next notification routed to one login attempt."""
377
+ return await self._call_sync(self._sync.next_login_notification, login_id)
378
+
379
+ async def next_turn_notification(self, turn_id: str) -> Notification:
380
+ """Wait for the next notification routed to one turn."""
381
+ return await self._call_sync(self._sync.next_turn_notification, turn_id)
382
+
383
+ async def next_goal_notification(self, state: _GoalOperationState) -> Notification:
384
+ """Wait for the next notification in a logical goal turn."""
385
+ return await self._call_sync(self._sync.next_goal_notification, state)
386
+
387
+ async def wait_for_login_completed(
388
+ self,
389
+ login_id: str,
390
+ ) -> AccountLoginCompletedNotification:
391
+ """Wait for the completion notification routed to one login attempt."""
392
+ return await self._call_sync(self._sync.wait_for_login_completed, login_id)
393
+
394
+ async def wait_for_turn_completed(self, turn_id: str) -> TurnCompletedNotification:
395
+ """Wait for the completion notification routed to one turn."""
396
+ return await self._call_sync(self._sync.wait_for_turn_completed, turn_id)
397
+
398
+ async def stream_text(
399
+ self,
400
+ thread_id: str,
401
+ text: str,
402
+ params: V2TurnStartParams | JsonObject | None = None,
403
+ ) -> AsyncIterator[AgentMessageDeltaNotification]:
404
+ """Stream text deltas from one turn without monopolizing the event loop."""
405
+ iterator = self._sync.stream_text(thread_id, text, params)
406
+ while True:
407
+ has_value, chunk = await asyncio.to_thread(
408
+ self._next_from_iterator,
409
+ iterator,
410
+ )
411
+ if not has_value:
412
+ break
413
+ yield chunk