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/_goal.py ADDED
@@ -0,0 +1,448 @@
1
+ import asyncio
2
+ import queue
3
+ import threading
4
+ import time
5
+ from collections import deque
6
+ from dataclasses import dataclass, field
7
+ from typing import AsyncIterator, Awaitable, Callable, Iterator
8
+
9
+ from .generated.notification_registry import notification_turn_id
10
+ from .generated.v2_all import (
11
+ ThreadGoalClearedNotification,
12
+ ThreadGoalStatus,
13
+ ThreadGoalUpdatedNotification,
14
+ Turn,
15
+ TurnCompletedNotification,
16
+ TurnStartedNotification,
17
+ TurnStatus,
18
+ )
19
+ from .models import Notification, UnknownNotification
20
+
21
+
22
+ class _GoalStreamClosed(Exception):
23
+ """Wake a notification reader after its logical stream closes."""
24
+
25
+
26
+ def _terminal_goal_status(status: ThreadGoalStatus | None) -> bool:
27
+ return status in {
28
+ ThreadGoalStatus.paused,
29
+ ThreadGoalStatus.blocked,
30
+ ThreadGoalStatus.usage_limited,
31
+ ThreadGoalStatus.budget_limited,
32
+ ThreadGoalStatus.complete,
33
+ }
34
+
35
+
36
+ @dataclass(slots=True)
37
+ class _GoalOperationState:
38
+ """Private state for one goal operation exposed as a logical turn."""
39
+
40
+ thread_id: str
41
+ logical_turn_id: str | None = None
42
+ current_turn_id: str | None = None
43
+ status: ThreadGoalStatus | None = None
44
+ started_turn: Turn | None = None
45
+ completed_turn: Turn | None = None
46
+ interrupted: bool = False
47
+ interrupt_requested: bool = False
48
+ cleared: bool = False
49
+ _condition: threading.Condition = field(default_factory=threading.Condition)
50
+ _notifications: queue.Queue[Notification | BaseException] = field(default_factory=queue.Queue)
51
+ _failure: BaseException | None = None
52
+ _finished: bool = False
53
+ _turn_routing_active: bool = False
54
+
55
+ def observe(self, notification: Notification) -> bool:
56
+ payload = notification.payload
57
+ with self._condition:
58
+ if not self._turn_routing_active and not isinstance(
59
+ payload,
60
+ ThreadGoalClearedNotification | ThreadGoalUpdatedNotification,
61
+ ):
62
+ return False
63
+ if isinstance(payload, TurnStartedNotification):
64
+ if self.logical_turn_id is None:
65
+ self.logical_turn_id = payload.turn.id
66
+ self.current_turn_id = payload.turn.id
67
+ if self.started_turn is None:
68
+ self.started_turn = payload.turn
69
+ elif isinstance(payload, TurnCompletedNotification):
70
+ self.completed_turn = payload.turn
71
+ if self.current_turn_id == payload.turn.id:
72
+ self.current_turn_id = None
73
+ elif isinstance(payload, ThreadGoalUpdatedNotification):
74
+ self.status = payload.goal.status
75
+ if self.status == ThreadGoalStatus.active:
76
+ self.cleared = False
77
+ elif isinstance(payload, ThreadGoalClearedNotification):
78
+ self.cleared = True
79
+ if (
80
+ self.current_turn_id is None
81
+ and self.completed_turn is not None
82
+ and (self.cleared or _terminal_goal_status(self.status))
83
+ ):
84
+ self._finished = True
85
+ self._condition.notify_all()
86
+ self._notifications.put(notification)
87
+ return True
88
+
89
+ def activate_turn_routing(self) -> None:
90
+ """Accept physical turns after the previous stored goal is cleared."""
91
+ with self._condition:
92
+ self._turn_routing_active = True
93
+
94
+ def wait_for_start(self, timeout: float) -> str | None:
95
+ """Wait for the runtime-generated first turn without consuming its event."""
96
+ deadline = time.monotonic() + timeout
97
+ with self._condition:
98
+ while self.started_turn is None or self.logical_turn_id is None:
99
+ if self._failure is not None:
100
+ raise self._failure
101
+ remaining = deadline - time.monotonic()
102
+ if remaining <= 0:
103
+ return None
104
+ self._condition.wait(remaining)
105
+ return self.logical_turn_id
106
+
107
+ def fail(self, exc: BaseException) -> None:
108
+ with self._condition:
109
+ self._failure = exc
110
+ self._condition.notify_all()
111
+ self._notifications.put(exc)
112
+
113
+ def next_notification(self) -> Notification:
114
+ item = self._notifications.get()
115
+ if isinstance(item, BaseException):
116
+ raise item
117
+ return item
118
+
119
+ def finish(self) -> None:
120
+ """Mark the logical operation inactive and wake waiting controls."""
121
+ with self._condition:
122
+ self._finished = True
123
+ self.current_turn_id = None
124
+ self._condition.notify_all()
125
+
126
+ def is_finished(self) -> bool:
127
+ with self._condition:
128
+ return self._finished
129
+
130
+ def begin_interrupt(self) -> bool:
131
+ with self._condition:
132
+ if self._finished:
133
+ return False
134
+ self.interrupt_requested = True
135
+ return True
136
+
137
+ def confirm_interrupt(self) -> None:
138
+ with self._condition:
139
+ self.interrupted = True
140
+ self.interrupt_requested = False
141
+ self._condition.notify_all()
142
+
143
+ def cancel_interrupt(self) -> None:
144
+ with self._condition:
145
+ self.interrupt_requested = False
146
+ self._condition.notify_all()
147
+
148
+ def explicit_interrupt(self) -> bool:
149
+ with self._condition:
150
+ while self.interrupt_requested:
151
+ self._condition.wait()
152
+ return self.interrupted
153
+
154
+ def active_turn(self, *, after: str | None = None) -> str | None:
155
+ """Wait for the current turn, or return None once the goal has ended."""
156
+ with self._condition:
157
+ while True:
158
+ if self._failure is not None:
159
+ raise self._failure
160
+ if self._finished:
161
+ return None
162
+ if self.current_turn_id is not None and self.current_turn_id != after:
163
+ return self.current_turn_id
164
+ if self.cleared or _terminal_goal_status(self.status):
165
+ return None
166
+ self._condition.wait()
167
+
168
+ def current_turn(self) -> str | None:
169
+ """Return the current physical turn without waiting for rollover."""
170
+ with self._condition:
171
+ return self.current_turn_id
172
+
173
+ def resolve_active_turn(self, expected: str, active: str) -> None:
174
+ """Adopt a server-reported active id when routed state is still stale."""
175
+ with self._condition:
176
+ if self.current_turn_id in {None, expected}:
177
+ self.current_turn_id = active
178
+ self._condition.notify_all()
179
+
180
+ def turn_for_interrupt(self) -> str | None:
181
+ """Return an active or stale turn id that can resolve rollover races."""
182
+ with self._condition:
183
+ if self.current_turn_id is not None:
184
+ return self.current_turn_id
185
+ if self.completed_turn is not None:
186
+ return self.completed_turn.id
187
+ if self.started_turn is not None:
188
+ return self.started_turn.id
189
+ return None
190
+
191
+ def wake_notification_reader(self) -> None:
192
+ """Release a reader blocked after its stream has been closed."""
193
+ self._notifications.put(_GoalStreamClosed())
194
+
195
+
196
+ def _logical_notification(notification: Notification, logical_turn_id: str) -> Notification:
197
+ """Return a copy whose turn metadata uses the logical operation id."""
198
+ payload = notification.payload
199
+ if isinstance(payload, UnknownNotification):
200
+ params = dict(payload.params)
201
+ if isinstance(params.get("turnId"), str):
202
+ params["turnId"] = logical_turn_id
203
+ turn = params.get("turn")
204
+ if isinstance(turn, dict) and isinstance(turn.get("id"), str):
205
+ params["turn"] = {**turn, "id": logical_turn_id}
206
+ return Notification(notification.method, UnknownNotification(params))
207
+
208
+ turn_id = notification_turn_id(payload)
209
+ if turn_id is None:
210
+ return notification
211
+ if hasattr(payload, "turn_id"):
212
+ return Notification(
213
+ notification.method,
214
+ payload.model_copy(update={"turn_id": logical_turn_id}),
215
+ )
216
+ if hasattr(payload, "turn"):
217
+ logical_turn = payload.turn.model_copy(update={"id": logical_turn_id})
218
+ return Notification(
219
+ notification.method,
220
+ payload.model_copy(update={"turn": logical_turn}),
221
+ )
222
+ return notification
223
+
224
+
225
+ def _logical_completion(
226
+ completed: TurnCompletedNotification,
227
+ *,
228
+ logical_turn_id: str,
229
+ started: Turn | None,
230
+ interrupted: bool,
231
+ ) -> TurnCompletedNotification:
232
+ """Coalesce the final physical completion into one logical completion."""
233
+ final_turn = completed.turn
234
+ started_at = started.started_at if started is not None else final_turn.started_at
235
+ duration_ms = final_turn.duration_ms
236
+ if started_at is not None and final_turn.completed_at is not None:
237
+ duration_ms = max(0, final_turn.completed_at - started_at) * 1000
238
+ updates: dict[str, object] = {
239
+ "id": logical_turn_id,
240
+ "started_at": started_at,
241
+ "duration_ms": duration_ms,
242
+ }
243
+ if interrupted:
244
+ updates["status"] = TurnStatus.interrupted
245
+ return completed.model_copy(update={"turn": final_turn.model_copy(update=updates)})
246
+
247
+
248
+ @dataclass(slots=True)
249
+ class _GoalStreamCursor:
250
+ """Consume physical goal events as one ordered logical turn stream."""
251
+
252
+ state: _GoalOperationState
253
+ started: Turn | None = None
254
+ last_completed: TurnCompletedNotification | None = None
255
+ failed_completion: TurnCompletedNotification | None = None
256
+ status: ThreadGoalStatus | None = None
257
+ active: bool = False
258
+ cleared: bool = False
259
+
260
+ def process(self, notification: Notification) -> tuple[list[Notification], bool]:
261
+ logical_turn_id = self.state.logical_turn_id
262
+ if logical_turn_id is None:
263
+ raise RuntimeError("goal operation has not been bound to a logical turn id")
264
+
265
+ payload = notification.payload
266
+ if isinstance(payload, TurnStartedNotification):
267
+ self.active = True
268
+ if self.started is not None:
269
+ return [], False
270
+ self.started = payload.turn
271
+ return [_logical_notification(notification, logical_turn_id)], False
272
+
273
+ if isinstance(payload, TurnCompletedNotification):
274
+ self.active = False
275
+ self.last_completed = payload
276
+ if payload.turn.status == TurnStatus.interrupted:
277
+ return [
278
+ self._completion(
279
+ notification.method,
280
+ self.failed_completion or payload,
281
+ )
282
+ ], True
283
+ if payload.turn.status == TurnStatus.failed:
284
+ self.failed_completion = payload
285
+ if self.cleared or _terminal_goal_status(self.status):
286
+ self.state.finish()
287
+ return [self._completion(notification.method, payload)], True
288
+ return [], False
289
+ if self.status is None and not self.cleared:
290
+ raise RuntimeError(
291
+ "the connected Codex runtime did not activate goal mode for this turn"
292
+ )
293
+ if self.cleared or _terminal_goal_status(self.status):
294
+ self.state.finish()
295
+ return [
296
+ self._completion(
297
+ notification.method,
298
+ self.failed_completion or payload,
299
+ )
300
+ ], True
301
+ return [], False
302
+
303
+ events = [_logical_notification(notification, logical_turn_id)]
304
+ if isinstance(payload, ThreadGoalUpdatedNotification):
305
+ self.status = payload.goal.status
306
+ if self.status == ThreadGoalStatus.active:
307
+ self.cleared = False
308
+ events = []
309
+ elif isinstance(payload, ThreadGoalClearedNotification):
310
+ self.cleared = True
311
+ events = []
312
+
313
+ if (
314
+ not self.active
315
+ and self.last_completed is not None
316
+ and (self.cleared or _terminal_goal_status(self.status))
317
+ ):
318
+ self.state.finish()
319
+ events.append(
320
+ self._completion(
321
+ "turn/completed",
322
+ self.failed_completion or self.last_completed,
323
+ )
324
+ )
325
+ return events, True
326
+ return events, False
327
+
328
+ def _completion(
329
+ self,
330
+ method: str,
331
+ payload: TurnCompletedNotification,
332
+ ) -> Notification:
333
+ logical_turn_id = self.state.logical_turn_id
334
+ if logical_turn_id is None:
335
+ raise RuntimeError("goal operation has not been bound to a logical turn id")
336
+ return Notification(
337
+ method,
338
+ _logical_completion(
339
+ payload,
340
+ logical_turn_id=logical_turn_id,
341
+ started=self.started,
342
+ interrupted=self.state.explicit_interrupt(),
343
+ ),
344
+ )
345
+
346
+
347
+ @dataclass(slots=True)
348
+ class _GoalNotificationStream(Iterator[Notification]):
349
+ """Closeable synchronous view of one logical goal operation."""
350
+
351
+ state: _GoalOperationState
352
+ next_notification: Callable[[], Notification]
353
+ unregister: Callable[[], None]
354
+ cancel_goal: Callable[[], None]
355
+ _cursor: _GoalStreamCursor = field(init=False)
356
+ _pending: deque[Notification] = field(default_factory=deque)
357
+ _closed: bool = False
358
+
359
+ def __post_init__(self) -> None:
360
+ self._cursor = _GoalStreamCursor(self.state)
361
+
362
+ def __iter__(self) -> "_GoalNotificationStream":
363
+ return self
364
+
365
+ def __next__(self) -> Notification:
366
+ if self._closed:
367
+ raise StopIteration
368
+ try:
369
+ while not self._pending:
370
+ notification = self.next_notification()
371
+ events, completed = self._cursor.process(notification)
372
+ self._pending.extend(events)
373
+ if completed:
374
+ self._finish()
375
+ return self._pending.popleft()
376
+ except _GoalStreamClosed:
377
+ self.close()
378
+ raise StopIteration from None
379
+ except KeyboardInterrupt:
380
+ self.cancel_goal()
381
+ self.close()
382
+ raise
383
+ except BaseException:
384
+ self.close()
385
+ raise
386
+
387
+ def _finish(self) -> None:
388
+ if self._closed:
389
+ return
390
+ self.state.finish()
391
+ self.state.wake_notification_reader()
392
+ self.unregister()
393
+ self._closed = True
394
+
395
+ def close(self) -> None:
396
+ self._finish()
397
+
398
+
399
+ @dataclass(slots=True)
400
+ class _AsyncGoalNotificationStream(AsyncIterator[Notification]):
401
+ """Closeable asynchronous view of one logical goal operation."""
402
+
403
+ state: _GoalOperationState
404
+ next_notification: Callable[[], Awaitable[Notification]]
405
+ unregister: Callable[[], None]
406
+ cancel_goal: Callable[[], Awaitable[None]]
407
+ _cursor: _GoalStreamCursor = field(init=False)
408
+ _pending: deque[Notification] = field(default_factory=deque)
409
+ _closed: bool = False
410
+
411
+ def __post_init__(self) -> None:
412
+ self._cursor = _GoalStreamCursor(self.state)
413
+
414
+ def __aiter__(self) -> "_AsyncGoalNotificationStream":
415
+ return self
416
+
417
+ async def __anext__(self) -> Notification:
418
+ if self._closed:
419
+ raise StopAsyncIteration
420
+ try:
421
+ while not self._pending:
422
+ notification = await self.next_notification()
423
+ events, completed = self._cursor.process(notification)
424
+ self._pending.extend(events)
425
+ if completed:
426
+ self._finish()
427
+ return self._pending.popleft()
428
+ except _GoalStreamClosed:
429
+ await self.aclose()
430
+ raise StopAsyncIteration from None
431
+ except asyncio.CancelledError:
432
+ await self.cancel_goal()
433
+ await self.aclose()
434
+ raise
435
+ except BaseException:
436
+ await self.aclose()
437
+ raise
438
+
439
+ def _finish(self) -> None:
440
+ if self._closed:
441
+ return
442
+ self.state.finish()
443
+ self.state.wake_notification_reader()
444
+ self.unregister()
445
+ self._closed = True
446
+
447
+ async def aclose(self) -> None:
448
+ self._finish()
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ from .models import InitializeResponse, ServerInfo
4
+
5
+
6
+ def _split_user_agent(user_agent: str) -> tuple[str | None, str | None]:
7
+ raw = user_agent.strip()
8
+ if not raw:
9
+ return None, None
10
+ if "/" in raw:
11
+ name, version = raw.split("/", 1)
12
+ return (name or None), (version or None)
13
+ parts = raw.split(maxsplit=1)
14
+ if len(parts) == 2:
15
+ return parts[0], parts[1]
16
+ return raw, None
17
+
18
+
19
+ def validate_initialize_metadata(payload: InitializeResponse) -> InitializeResponse:
20
+ user_agent = (payload.userAgent or "").strip()
21
+ server = payload.serverInfo
22
+
23
+ server_name: str | None = None
24
+ server_version: str | None = None
25
+
26
+ if server is not None:
27
+ server_name = (server.name or "").strip() or None
28
+ server_version = (server.version or "").strip() or None
29
+
30
+ if (server_name is None or server_version is None) and user_agent:
31
+ parsed_name, parsed_version = _split_user_agent(user_agent)
32
+ if server_name is None:
33
+ server_name = parsed_name
34
+ if server_version is None:
35
+ server_version = parsed_version
36
+
37
+ normalized_server_name = (server_name or "").strip()
38
+ normalized_server_version = (server_version or "").strip()
39
+ if not user_agent or not normalized_server_name or not normalized_server_version:
40
+ raise RuntimeError(
41
+ "initialize response missing required metadata "
42
+ f"(user_agent={user_agent!r}, server_name={normalized_server_name!r}, server_version={normalized_server_version!r})"
43
+ )
44
+
45
+ if server is None:
46
+ payload.serverInfo = ServerInfo(
47
+ name=normalized_server_name,
48
+ version=normalized_server_version,
49
+ )
50
+ else:
51
+ server.name = normalized_server_name
52
+ server.version = normalized_server_version
53
+
54
+ return payload
@@ -0,0 +1,103 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass
5
+
6
+ from .generated.v2_all import FunctionCallOutputContentItem, TurnToolOutput
7
+ from .models import JsonObject
8
+
9
+
10
+ @dataclass(slots=True)
11
+ class TextInput:
12
+ """Text supplied to a turn or steering request."""
13
+
14
+ text: str
15
+
16
+
17
+ @dataclass(slots=True)
18
+ class ImageInput:
19
+ """Image data URL supplied as turn input."""
20
+
21
+ url: str
22
+
23
+
24
+ @dataclass(slots=True)
25
+ class LocalImageInput:
26
+ """Local image path supplied as turn input."""
27
+
28
+ path: str
29
+
30
+
31
+ @dataclass(slots=True)
32
+ class SkillInput:
33
+ """Named skill reference supplied as turn input."""
34
+
35
+ name: str
36
+ path: str
37
+
38
+
39
+ @dataclass(slots=True)
40
+ class MentionInput:
41
+ """Named resource mention supplied as turn input."""
42
+
43
+ name: str
44
+ path: str
45
+
46
+
47
+ @dataclass(slots=True)
48
+ class ExternalMessage:
49
+ """Untrusted content supplied by another agent, tool, or application.
50
+
51
+ Content has tool-level authority, below user and developer instructions. It
52
+ does not establish user authorization or approval. Pass this as the whole
53
+ input to ``thread.run()`` or ``thread.turn()`` to start a turn or join an
54
+ active regular turn. ``tool_name`` identifies the tool delivering it.
55
+
56
+ ``content`` accepts text or Responses-compatible function-output content
57
+ items. Structured items can be dictionaries; no generated wrapper is needed.
58
+ """
59
+
60
+ tool_name: str
61
+ content: str | Sequence[JsonObject | FunctionCallOutputContentItem]
62
+ namespace: str | None = None
63
+
64
+
65
+ InputItem = TextInput | ImageInput | LocalImageInput | SkillInput | MentionInput
66
+ Input = list[InputItem] | InputItem
67
+ RunInput = Input | str | ExternalMessage
68
+
69
+
70
+ def _to_wire_item(item: InputItem) -> JsonObject:
71
+ if isinstance(item, TextInput):
72
+ return {"type": "text", "text": item.text}
73
+ if isinstance(item, ImageInput):
74
+ return {"type": "image", "url": item.url}
75
+ if isinstance(item, LocalImageInput):
76
+ return {"type": "localImage", "path": item.path}
77
+ if isinstance(item, SkillInput):
78
+ return {"type": "skill", "name": item.name, "path": item.path}
79
+ if isinstance(item, MentionInput):
80
+ return {"type": "mention", "name": item.name, "path": item.path}
81
+ raise TypeError(f"unsupported input item: {type(item)!r}")
82
+
83
+
84
+ def _to_wire_input(input: Input) -> list[JsonObject]:
85
+ if isinstance(input, list):
86
+ return [_to_wire_item(i) for i in input]
87
+ return [_to_wire_item(input)]
88
+
89
+
90
+ def _normalize_run_input(input: Input | str) -> Input:
91
+ if isinstance(input, str):
92
+ return TextInput(input)
93
+ return input
94
+
95
+
96
+ def _to_wire_turn_input(input: RunInput) -> tuple[list[JsonObject], TurnToolOutput | None]:
97
+ if isinstance(input, ExternalMessage):
98
+ if not isinstance(input.tool_name, str) or not input.tool_name.strip():
99
+ raise ValueError("ExternalMessage.tool_name must be a nonempty string")
100
+ return [], TurnToolOutput.model_validate(
101
+ {"name": input.tool_name, "namespace": input.namespace, "output": input.content}
102
+ )
103
+ return _to_wire_input(_normalize_run_input(input)), None