Base: codex-main originale (prima del fork aKode)
This commit is contained in:
95
sdk/python/src/openai_codex/__init__.py
Normal file
95
sdk/python/src/openai_codex/__init__.py
Normal file
@@ -0,0 +1,95 @@
|
||||
"""Python SDK for running Codex workflows.
|
||||
|
||||
Start with :class:`Codex` for synchronous applications or
|
||||
:class:`AsyncCodex` for async applications. Most programs create a thread and
|
||||
run a turn::
|
||||
|
||||
from openai_codex import Codex, Sandbox
|
||||
|
||||
with Codex() as codex:
|
||||
thread = codex.thread_start(sandbox=Sandbox.workspace_write)
|
||||
result = thread.run("Describe this project.")
|
||||
print(result.final_response)
|
||||
"""
|
||||
|
||||
from ._version import __version__
|
||||
from .api import (
|
||||
ApprovalMode,
|
||||
AsyncChatgptLoginHandle,
|
||||
AsyncCodex,
|
||||
AsyncDeviceCodeLoginHandle,
|
||||
AsyncThread,
|
||||
AsyncTurnHandle,
|
||||
ChatgptLoginHandle,
|
||||
Codex,
|
||||
DeviceCodeLoginHandle,
|
||||
ExternalMessage,
|
||||
ImageInput,
|
||||
Input,
|
||||
InputItem,
|
||||
LocalImageInput,
|
||||
MentionInput,
|
||||
RunInput,
|
||||
Sandbox,
|
||||
SkillInput,
|
||||
TextInput,
|
||||
Thread,
|
||||
TurnHandle,
|
||||
TurnResult,
|
||||
)
|
||||
from .client import CodexConfig
|
||||
from .errors import (
|
||||
CodexError,
|
||||
CodexRpcError,
|
||||
InternalRpcError,
|
||||
InvalidParamsError,
|
||||
InvalidRequestError,
|
||||
JsonRpcError,
|
||||
MethodNotFoundError,
|
||||
ParseError,
|
||||
RetryLimitExceededError,
|
||||
ServerBusyError,
|
||||
TransportClosedError,
|
||||
is_retryable_error,
|
||||
)
|
||||
from .retry import retry_on_overload
|
||||
|
||||
__all__ = [
|
||||
"__version__",
|
||||
"CodexConfig",
|
||||
"Codex",
|
||||
"AsyncCodex",
|
||||
"ApprovalMode",
|
||||
"Sandbox",
|
||||
"ChatgptLoginHandle",
|
||||
"DeviceCodeLoginHandle",
|
||||
"AsyncChatgptLoginHandle",
|
||||
"AsyncDeviceCodeLoginHandle",
|
||||
"Thread",
|
||||
"AsyncThread",
|
||||
"TurnHandle",
|
||||
"AsyncTurnHandle",
|
||||
"TurnResult",
|
||||
"Input",
|
||||
"InputItem",
|
||||
"RunInput",
|
||||
"ExternalMessage",
|
||||
"TextInput",
|
||||
"ImageInput",
|
||||
"LocalImageInput",
|
||||
"SkillInput",
|
||||
"MentionInput",
|
||||
"retry_on_overload",
|
||||
"CodexError",
|
||||
"TransportClosedError",
|
||||
"JsonRpcError",
|
||||
"CodexRpcError",
|
||||
"ParseError",
|
||||
"InvalidRequestError",
|
||||
"MethodNotFoundError",
|
||||
"InvalidParamsError",
|
||||
"InternalRpcError",
|
||||
"ServerBusyError",
|
||||
"RetryLimitExceededError",
|
||||
"is_retryable_error",
|
||||
]
|
||||
51
sdk/python/src/openai_codex/_approval_mode.py
Normal file
51
sdk/python/src/openai_codex/_approval_mode.py
Normal file
@@ -0,0 +1,51 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum
|
||||
from typing import NoReturn
|
||||
|
||||
from .generated.v2_all import (
|
||||
ApprovalsReviewer,
|
||||
AskForApproval,
|
||||
AskForApprovalValue,
|
||||
)
|
||||
|
||||
|
||||
class ApprovalMode(str, Enum):
|
||||
"""High-level approval behavior for escalated permission requests."""
|
||||
|
||||
deny_all = "deny_all"
|
||||
auto_review = "auto_review"
|
||||
|
||||
|
||||
def _approval_mode_settings(
|
||||
approval_mode: ApprovalMode,
|
||||
) -> tuple[AskForApproval, ApprovalsReviewer | None]:
|
||||
"""Map the public approval mode to generated app-server start params."""
|
||||
if not isinstance(approval_mode, ApprovalMode):
|
||||
supported = ", ".join(mode.value for mode in ApprovalMode)
|
||||
raise ValueError(f"approval_mode must be one of: {supported}")
|
||||
|
||||
match approval_mode:
|
||||
case ApprovalMode.auto_review:
|
||||
return (
|
||||
AskForApproval(root=AskForApprovalValue.on_request),
|
||||
ApprovalsReviewer.auto_review,
|
||||
)
|
||||
case ApprovalMode.deny_all:
|
||||
return AskForApproval(root=AskForApprovalValue.never), None
|
||||
case _:
|
||||
return _assert_never_approval_mode(approval_mode)
|
||||
|
||||
|
||||
def _assert_never_approval_mode(approval_mode: NoReturn) -> NoReturn:
|
||||
"""Make approval mode mapping exhaustive for static type checkers."""
|
||||
raise AssertionError(f"Unhandled approval mode: {approval_mode!r}")
|
||||
|
||||
|
||||
def _approval_mode_override_settings(
|
||||
approval_mode: ApprovalMode | None,
|
||||
) -> tuple[AskForApproval | None, ApprovalsReviewer | None]:
|
||||
"""Map an optional public approval mode to app-server override params."""
|
||||
if approval_mode is None:
|
||||
return None, None
|
||||
return _approval_mode_settings(approval_mode)
|
||||
448
sdk/python/src/openai_codex/_goal.py
Normal file
448
sdk/python/src/openai_codex/_goal.py
Normal file
@@ -0,0 +1,448 @@
|
||||
import asyncio
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
from typing import AsyncIterator, Awaitable, Callable, Iterator
|
||||
|
||||
from .generated.notification_registry import notification_turn_id
|
||||
from .generated.v2_all import (
|
||||
ThreadGoalClearedNotification,
|
||||
ThreadGoalStatus,
|
||||
ThreadGoalUpdatedNotification,
|
||||
Turn,
|
||||
TurnCompletedNotification,
|
||||
TurnStartedNotification,
|
||||
TurnStatus,
|
||||
)
|
||||
from .models import Notification, UnknownNotification
|
||||
|
||||
|
||||
class _GoalStreamClosed(Exception):
|
||||
"""Wake a notification reader after its logical stream closes."""
|
||||
|
||||
|
||||
def _terminal_goal_status(status: ThreadGoalStatus | None) -> bool:
|
||||
return status in {
|
||||
ThreadGoalStatus.paused,
|
||||
ThreadGoalStatus.blocked,
|
||||
ThreadGoalStatus.usage_limited,
|
||||
ThreadGoalStatus.budget_limited,
|
||||
ThreadGoalStatus.complete,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _GoalOperationState:
|
||||
"""Private state for one goal operation exposed as a logical turn."""
|
||||
|
||||
thread_id: str
|
||||
logical_turn_id: str | None = None
|
||||
current_turn_id: str | None = None
|
||||
status: ThreadGoalStatus | None = None
|
||||
started_turn: Turn | None = None
|
||||
completed_turn: Turn | None = None
|
||||
interrupted: bool = False
|
||||
interrupt_requested: bool = False
|
||||
cleared: bool = False
|
||||
_condition: threading.Condition = field(default_factory=threading.Condition)
|
||||
_notifications: queue.Queue[Notification | BaseException] = field(default_factory=queue.Queue)
|
||||
_failure: BaseException | None = None
|
||||
_finished: bool = False
|
||||
_turn_routing_active: bool = False
|
||||
|
||||
def observe(self, notification: Notification) -> bool:
|
||||
payload = notification.payload
|
||||
with self._condition:
|
||||
if not self._turn_routing_active and not isinstance(
|
||||
payload,
|
||||
ThreadGoalClearedNotification | ThreadGoalUpdatedNotification,
|
||||
):
|
||||
return False
|
||||
if isinstance(payload, TurnStartedNotification):
|
||||
if self.logical_turn_id is None:
|
||||
self.logical_turn_id = payload.turn.id
|
||||
self.current_turn_id = payload.turn.id
|
||||
if self.started_turn is None:
|
||||
self.started_turn = payload.turn
|
||||
elif isinstance(payload, TurnCompletedNotification):
|
||||
self.completed_turn = payload.turn
|
||||
if self.current_turn_id == payload.turn.id:
|
||||
self.current_turn_id = None
|
||||
elif isinstance(payload, ThreadGoalUpdatedNotification):
|
||||
self.status = payload.goal.status
|
||||
if self.status == ThreadGoalStatus.active:
|
||||
self.cleared = False
|
||||
elif isinstance(payload, ThreadGoalClearedNotification):
|
||||
self.cleared = True
|
||||
if (
|
||||
self.current_turn_id is None
|
||||
and self.completed_turn is not None
|
||||
and (self.cleared or _terminal_goal_status(self.status))
|
||||
):
|
||||
self._finished = True
|
||||
self._condition.notify_all()
|
||||
self._notifications.put(notification)
|
||||
return True
|
||||
|
||||
def activate_turn_routing(self) -> None:
|
||||
"""Accept physical turns after the previous stored goal is cleared."""
|
||||
with self._condition:
|
||||
self._turn_routing_active = True
|
||||
|
||||
def wait_for_start(self, timeout: float) -> str | None:
|
||||
"""Wait for the runtime-generated first turn without consuming its event."""
|
||||
deadline = time.monotonic() + timeout
|
||||
with self._condition:
|
||||
while self.started_turn is None or self.logical_turn_id is None:
|
||||
if self._failure is not None:
|
||||
raise self._failure
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
return None
|
||||
self._condition.wait(remaining)
|
||||
return self.logical_turn_id
|
||||
|
||||
def fail(self, exc: BaseException) -> None:
|
||||
with self._condition:
|
||||
self._failure = exc
|
||||
self._condition.notify_all()
|
||||
self._notifications.put(exc)
|
||||
|
||||
def next_notification(self) -> Notification:
|
||||
item = self._notifications.get()
|
||||
if isinstance(item, BaseException):
|
||||
raise item
|
||||
return item
|
||||
|
||||
def finish(self) -> None:
|
||||
"""Mark the logical operation inactive and wake waiting controls."""
|
||||
with self._condition:
|
||||
self._finished = True
|
||||
self.current_turn_id = None
|
||||
self._condition.notify_all()
|
||||
|
||||
def is_finished(self) -> bool:
|
||||
with self._condition:
|
||||
return self._finished
|
||||
|
||||
def begin_interrupt(self) -> bool:
|
||||
with self._condition:
|
||||
if self._finished:
|
||||
return False
|
||||
self.interrupt_requested = True
|
||||
return True
|
||||
|
||||
def confirm_interrupt(self) -> None:
|
||||
with self._condition:
|
||||
self.interrupted = True
|
||||
self.interrupt_requested = False
|
||||
self._condition.notify_all()
|
||||
|
||||
def cancel_interrupt(self) -> None:
|
||||
with self._condition:
|
||||
self.interrupt_requested = False
|
||||
self._condition.notify_all()
|
||||
|
||||
def explicit_interrupt(self) -> bool:
|
||||
with self._condition:
|
||||
while self.interrupt_requested:
|
||||
self._condition.wait()
|
||||
return self.interrupted
|
||||
|
||||
def active_turn(self, *, after: str | None = None) -> str | None:
|
||||
"""Wait for the current turn, or return None once the goal has ended."""
|
||||
with self._condition:
|
||||
while True:
|
||||
if self._failure is not None:
|
||||
raise self._failure
|
||||
if self._finished:
|
||||
return None
|
||||
if self.current_turn_id is not None and self.current_turn_id != after:
|
||||
return self.current_turn_id
|
||||
if self.cleared or _terminal_goal_status(self.status):
|
||||
return None
|
||||
self._condition.wait()
|
||||
|
||||
def current_turn(self) -> str | None:
|
||||
"""Return the current physical turn without waiting for rollover."""
|
||||
with self._condition:
|
||||
return self.current_turn_id
|
||||
|
||||
def resolve_active_turn(self, expected: str, active: str) -> None:
|
||||
"""Adopt a server-reported active id when routed state is still stale."""
|
||||
with self._condition:
|
||||
if self.current_turn_id in {None, expected}:
|
||||
self.current_turn_id = active
|
||||
self._condition.notify_all()
|
||||
|
||||
def turn_for_interrupt(self) -> str | None:
|
||||
"""Return an active or stale turn id that can resolve rollover races."""
|
||||
with self._condition:
|
||||
if self.current_turn_id is not None:
|
||||
return self.current_turn_id
|
||||
if self.completed_turn is not None:
|
||||
return self.completed_turn.id
|
||||
if self.started_turn is not None:
|
||||
return self.started_turn.id
|
||||
return None
|
||||
|
||||
def wake_notification_reader(self) -> None:
|
||||
"""Release a reader blocked after its stream has been closed."""
|
||||
self._notifications.put(_GoalStreamClosed())
|
||||
|
||||
|
||||
def _logical_notification(notification: Notification, logical_turn_id: str) -> Notification:
|
||||
"""Return a copy whose turn metadata uses the logical operation id."""
|
||||
payload = notification.payload
|
||||
if isinstance(payload, UnknownNotification):
|
||||
params = dict(payload.params)
|
||||
if isinstance(params.get("turnId"), str):
|
||||
params["turnId"] = logical_turn_id
|
||||
turn = params.get("turn")
|
||||
if isinstance(turn, dict) and isinstance(turn.get("id"), str):
|
||||
params["turn"] = {**turn, "id": logical_turn_id}
|
||||
return Notification(notification.method, UnknownNotification(params))
|
||||
|
||||
turn_id = notification_turn_id(payload)
|
||||
if turn_id is None:
|
||||
return notification
|
||||
if hasattr(payload, "turn_id"):
|
||||
return Notification(
|
||||
notification.method,
|
||||
payload.model_copy(update={"turn_id": logical_turn_id}),
|
||||
)
|
||||
if hasattr(payload, "turn"):
|
||||
logical_turn = payload.turn.model_copy(update={"id": logical_turn_id})
|
||||
return Notification(
|
||||
notification.method,
|
||||
payload.model_copy(update={"turn": logical_turn}),
|
||||
)
|
||||
return notification
|
||||
|
||||
|
||||
def _logical_completion(
|
||||
completed: TurnCompletedNotification,
|
||||
*,
|
||||
logical_turn_id: str,
|
||||
started: Turn | None,
|
||||
interrupted: bool,
|
||||
) -> TurnCompletedNotification:
|
||||
"""Coalesce the final physical completion into one logical completion."""
|
||||
final_turn = completed.turn
|
||||
started_at = started.started_at if started is not None else final_turn.started_at
|
||||
duration_ms = final_turn.duration_ms
|
||||
if started_at is not None and final_turn.completed_at is not None:
|
||||
duration_ms = max(0, final_turn.completed_at - started_at) * 1000
|
||||
updates: dict[str, object] = {
|
||||
"id": logical_turn_id,
|
||||
"started_at": started_at,
|
||||
"duration_ms": duration_ms,
|
||||
}
|
||||
if interrupted:
|
||||
updates["status"] = TurnStatus.interrupted
|
||||
return completed.model_copy(update={"turn": final_turn.model_copy(update=updates)})
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _GoalStreamCursor:
|
||||
"""Consume physical goal events as one ordered logical turn stream."""
|
||||
|
||||
state: _GoalOperationState
|
||||
started: Turn | None = None
|
||||
last_completed: TurnCompletedNotification | None = None
|
||||
failed_completion: TurnCompletedNotification | None = None
|
||||
status: ThreadGoalStatus | None = None
|
||||
active: bool = False
|
||||
cleared: bool = False
|
||||
|
||||
def process(self, notification: Notification) -> tuple[list[Notification], bool]:
|
||||
logical_turn_id = self.state.logical_turn_id
|
||||
if logical_turn_id is None:
|
||||
raise RuntimeError("goal operation has not been bound to a logical turn id")
|
||||
|
||||
payload = notification.payload
|
||||
if isinstance(payload, TurnStartedNotification):
|
||||
self.active = True
|
||||
if self.started is not None:
|
||||
return [], False
|
||||
self.started = payload.turn
|
||||
return [_logical_notification(notification, logical_turn_id)], False
|
||||
|
||||
if isinstance(payload, TurnCompletedNotification):
|
||||
self.active = False
|
||||
self.last_completed = payload
|
||||
if payload.turn.status == TurnStatus.interrupted:
|
||||
return [
|
||||
self._completion(
|
||||
notification.method,
|
||||
self.failed_completion or payload,
|
||||
)
|
||||
], True
|
||||
if payload.turn.status == TurnStatus.failed:
|
||||
self.failed_completion = payload
|
||||
if self.cleared or _terminal_goal_status(self.status):
|
||||
self.state.finish()
|
||||
return [self._completion(notification.method, payload)], True
|
||||
return [], False
|
||||
if self.status is None and not self.cleared:
|
||||
raise RuntimeError(
|
||||
"the connected Codex runtime did not activate goal mode for this turn"
|
||||
)
|
||||
if self.cleared or _terminal_goal_status(self.status):
|
||||
self.state.finish()
|
||||
return [
|
||||
self._completion(
|
||||
notification.method,
|
||||
self.failed_completion or payload,
|
||||
)
|
||||
], True
|
||||
return [], False
|
||||
|
||||
events = [_logical_notification(notification, logical_turn_id)]
|
||||
if isinstance(payload, ThreadGoalUpdatedNotification):
|
||||
self.status = payload.goal.status
|
||||
if self.status == ThreadGoalStatus.active:
|
||||
self.cleared = False
|
||||
events = []
|
||||
elif isinstance(payload, ThreadGoalClearedNotification):
|
||||
self.cleared = True
|
||||
events = []
|
||||
|
||||
if (
|
||||
not self.active
|
||||
and self.last_completed is not None
|
||||
and (self.cleared or _terminal_goal_status(self.status))
|
||||
):
|
||||
self.state.finish()
|
||||
events.append(
|
||||
self._completion(
|
||||
"turn/completed",
|
||||
self.failed_completion or self.last_completed,
|
||||
)
|
||||
)
|
||||
return events, True
|
||||
return events, False
|
||||
|
||||
def _completion(
|
||||
self,
|
||||
method: str,
|
||||
payload: TurnCompletedNotification,
|
||||
) -> Notification:
|
||||
logical_turn_id = self.state.logical_turn_id
|
||||
if logical_turn_id is None:
|
||||
raise RuntimeError("goal operation has not been bound to a logical turn id")
|
||||
return Notification(
|
||||
method,
|
||||
_logical_completion(
|
||||
payload,
|
||||
logical_turn_id=logical_turn_id,
|
||||
started=self.started,
|
||||
interrupted=self.state.explicit_interrupt(),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _GoalNotificationStream(Iterator[Notification]):
|
||||
"""Closeable synchronous view of one logical goal operation."""
|
||||
|
||||
state: _GoalOperationState
|
||||
next_notification: Callable[[], Notification]
|
||||
unregister: Callable[[], None]
|
||||
cancel_goal: Callable[[], None]
|
||||
_cursor: _GoalStreamCursor = field(init=False)
|
||||
_pending: deque[Notification] = field(default_factory=deque)
|
||||
_closed: bool = False
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self._cursor = _GoalStreamCursor(self.state)
|
||||
|
||||
def __iter__(self) -> "_GoalNotificationStream":
|
||||
return self
|
||||
|
||||
def __next__(self) -> Notification:
|
||||
if self._closed:
|
||||
raise StopIteration
|
||||
try:
|
||||
while not self._pending:
|
||||
notification = self.next_notification()
|
||||
events, completed = self._cursor.process(notification)
|
||||
self._pending.extend(events)
|
||||
if completed:
|
||||
self._finish()
|
||||
return self._pending.popleft()
|
||||
except _GoalStreamClosed:
|
||||
self.close()
|
||||
raise StopIteration from None
|
||||
except KeyboardInterrupt:
|
||||
self.cancel_goal()
|
||||
self.close()
|
||||
raise
|
||||
except BaseException:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def _finish(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self.state.finish()
|
||||
self.state.wake_notification_reader()
|
||||
self.unregister()
|
||||
self._closed = True
|
||||
|
||||
def close(self) -> None:
|
||||
self._finish()
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _AsyncGoalNotificationStream(AsyncIterator[Notification]):
|
||||
"""Closeable asynchronous view of one logical goal operation."""
|
||||
|
||||
state: _GoalOperationState
|
||||
next_notification: Callable[[], Awaitable[Notification]]
|
||||
unregister: Callable[[], None]
|
||||
cancel_goal: Callable[[], Awaitable[None]]
|
||||
_cursor: _GoalStreamCursor = field(init=False)
|
||||
_pending: deque[Notification] = field(default_factory=deque)
|
||||
_closed: bool = False
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self._cursor = _GoalStreamCursor(self.state)
|
||||
|
||||
def __aiter__(self) -> "_AsyncGoalNotificationStream":
|
||||
return self
|
||||
|
||||
async def __anext__(self) -> Notification:
|
||||
if self._closed:
|
||||
raise StopAsyncIteration
|
||||
try:
|
||||
while not self._pending:
|
||||
notification = await self.next_notification()
|
||||
events, completed = self._cursor.process(notification)
|
||||
self._pending.extend(events)
|
||||
if completed:
|
||||
self._finish()
|
||||
return self._pending.popleft()
|
||||
except _GoalStreamClosed:
|
||||
await self.aclose()
|
||||
raise StopAsyncIteration from None
|
||||
except asyncio.CancelledError:
|
||||
await self.cancel_goal()
|
||||
await self.aclose()
|
||||
raise
|
||||
except BaseException:
|
||||
await self.aclose()
|
||||
raise
|
||||
|
||||
def _finish(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self.state.finish()
|
||||
self.state.wake_notification_reader()
|
||||
self.unregister()
|
||||
self._closed = True
|
||||
|
||||
async def aclose(self) -> None:
|
||||
self._finish()
|
||||
54
sdk/python/src/openai_codex/_initialize_metadata.py
Normal file
54
sdk/python/src/openai_codex/_initialize_metadata.py
Normal file
@@ -0,0 +1,54 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from .models import InitializeResponse, ServerInfo
|
||||
|
||||
|
||||
def _split_user_agent(user_agent: str) -> tuple[str | None, str | None]:
|
||||
raw = user_agent.strip()
|
||||
if not raw:
|
||||
return None, None
|
||||
if "/" in raw:
|
||||
name, version = raw.split("/", 1)
|
||||
return (name or None), (version or None)
|
||||
parts = raw.split(maxsplit=1)
|
||||
if len(parts) == 2:
|
||||
return parts[0], parts[1]
|
||||
return raw, None
|
||||
|
||||
|
||||
def validate_initialize_metadata(payload: InitializeResponse) -> InitializeResponse:
|
||||
user_agent = (payload.userAgent or "").strip()
|
||||
server = payload.serverInfo
|
||||
|
||||
server_name: str | None = None
|
||||
server_version: str | None = None
|
||||
|
||||
if server is not None:
|
||||
server_name = (server.name or "").strip() or None
|
||||
server_version = (server.version or "").strip() or None
|
||||
|
||||
if (server_name is None or server_version is None) and user_agent:
|
||||
parsed_name, parsed_version = _split_user_agent(user_agent)
|
||||
if server_name is None:
|
||||
server_name = parsed_name
|
||||
if server_version is None:
|
||||
server_version = parsed_version
|
||||
|
||||
normalized_server_name = (server_name or "").strip()
|
||||
normalized_server_version = (server_version or "").strip()
|
||||
if not user_agent or not normalized_server_name or not normalized_server_version:
|
||||
raise RuntimeError(
|
||||
"initialize response missing required metadata "
|
||||
f"(user_agent={user_agent!r}, server_name={normalized_server_name!r}, server_version={normalized_server_version!r})"
|
||||
)
|
||||
|
||||
if server is None:
|
||||
payload.serverInfo = ServerInfo(
|
||||
name=normalized_server_name,
|
||||
version=normalized_server_version,
|
||||
)
|
||||
else:
|
||||
server.name = normalized_server_name
|
||||
server.version = normalized_server_version
|
||||
|
||||
return payload
|
||||
103
sdk/python/src/openai_codex/_inputs.py
Normal file
103
sdk/python/src/openai_codex/_inputs.py
Normal file
@@ -0,0 +1,103 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .generated.v2_all import FunctionCallOutputContentItem, TurnToolOutput
|
||||
from .models import JsonObject
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class TextInput:
|
||||
"""Text supplied to a turn or steering request."""
|
||||
|
||||
text: str
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ImageInput:
|
||||
"""Image data URL supplied as turn input."""
|
||||
|
||||
url: str
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class LocalImageInput:
|
||||
"""Local image path supplied as turn input."""
|
||||
|
||||
path: str
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class SkillInput:
|
||||
"""Named skill reference supplied as turn input."""
|
||||
|
||||
name: str
|
||||
path: str
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class MentionInput:
|
||||
"""Named resource mention supplied as turn input."""
|
||||
|
||||
name: str
|
||||
path: str
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ExternalMessage:
|
||||
"""Untrusted content supplied by another agent, tool, or application.
|
||||
|
||||
Content has tool-level authority, below user and developer instructions. It
|
||||
does not establish user authorization or approval. Pass this as the whole
|
||||
input to ``thread.run()`` or ``thread.turn()`` to start a turn or join an
|
||||
active regular turn. ``tool_name`` identifies the tool delivering it.
|
||||
|
||||
``content`` accepts text or Responses-compatible function-output content
|
||||
items. Structured items can be dictionaries; no generated wrapper is needed.
|
||||
"""
|
||||
|
||||
tool_name: str
|
||||
content: str | Sequence[JsonObject | FunctionCallOutputContentItem]
|
||||
namespace: str | None = None
|
||||
|
||||
|
||||
InputItem = TextInput | ImageInput | LocalImageInput | SkillInput | MentionInput
|
||||
Input = list[InputItem] | InputItem
|
||||
RunInput = Input | str | ExternalMessage
|
||||
|
||||
|
||||
def _to_wire_item(item: InputItem) -> JsonObject:
|
||||
if isinstance(item, TextInput):
|
||||
return {"type": "text", "text": item.text}
|
||||
if isinstance(item, ImageInput):
|
||||
return {"type": "image", "url": item.url}
|
||||
if isinstance(item, LocalImageInput):
|
||||
return {"type": "localImage", "path": item.path}
|
||||
if isinstance(item, SkillInput):
|
||||
return {"type": "skill", "name": item.name, "path": item.path}
|
||||
if isinstance(item, MentionInput):
|
||||
return {"type": "mention", "name": item.name, "path": item.path}
|
||||
raise TypeError(f"unsupported input item: {type(item)!r}")
|
||||
|
||||
|
||||
def _to_wire_input(input: Input) -> list[JsonObject]:
|
||||
if isinstance(input, list):
|
||||
return [_to_wire_item(i) for i in input]
|
||||
return [_to_wire_item(input)]
|
||||
|
||||
|
||||
def _normalize_run_input(input: Input | str) -> Input:
|
||||
if isinstance(input, str):
|
||||
return TextInput(input)
|
||||
return input
|
||||
|
||||
|
||||
def _to_wire_turn_input(input: RunInput) -> tuple[list[JsonObject], TurnToolOutput | None]:
|
||||
if isinstance(input, ExternalMessage):
|
||||
if not isinstance(input.tool_name, str) or not input.tool_name.strip():
|
||||
raise ValueError("ExternalMessage.tool_name must be a nonempty string")
|
||||
return [], TurnToolOutput.model_validate(
|
||||
{"name": input.tool_name, "namespace": input.namespace, "output": input.content}
|
||||
)
|
||||
return _to_wire_input(_normalize_run_input(input)), None
|
||||
172
sdk/python/src/openai_codex/_login.py
Normal file
172
sdk/python/src/openai_codex/_login.py
Normal file
@@ -0,0 +1,172 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
from .async_client import AsyncCodexClient
|
||||
from .client import CodexClient
|
||||
from .generated.v2_all import (
|
||||
AccountLoginCompletedNotification,
|
||||
CancelLoginAccountResponse,
|
||||
ChatgptDeviceCodeLoginAccountParams,
|
||||
ChatgptDeviceCodeLoginAccountResponse,
|
||||
ChatgptLoginAccountParams,
|
||||
ChatgptLoginAccountResponse,
|
||||
LoginAccountParams,
|
||||
)
|
||||
|
||||
|
||||
class _AsyncLoginOwner(Protocol):
|
||||
"""Subset of AsyncCodex needed by async login handles."""
|
||||
|
||||
_client: AsyncCodexClient
|
||||
|
||||
async def _ensure_initialized(self) -> None:
|
||||
"""Ensure the owning SDK client has a live Codex connection."""
|
||||
...
|
||||
|
||||
|
||||
def start_chatgpt_login(client: CodexClient) -> ChatgptLoginHandle:
|
||||
"""Start browser ChatGPT login and return the handle for that attempt."""
|
||||
response = client.account_login_start(
|
||||
LoginAccountParams(
|
||||
root=ChatgptLoginAccountParams(type="chatgpt"),
|
||||
)
|
||||
)
|
||||
response_root = response.root
|
||||
if not isinstance(response_root, ChatgptLoginAccountResponse):
|
||||
raise RuntimeError(f"unexpected ChatGPT login response: {response_root!r}")
|
||||
return ChatgptLoginHandle(
|
||||
client,
|
||||
response_root.login_id,
|
||||
response_root.auth_url,
|
||||
)
|
||||
|
||||
|
||||
async def async_start_chatgpt_login(owner: _AsyncLoginOwner) -> AsyncChatgptLoginHandle:
|
||||
"""Start async browser ChatGPT login and return that attempt's handle."""
|
||||
response = await owner._client.account_login_start(
|
||||
LoginAccountParams(
|
||||
root=ChatgptLoginAccountParams(type="chatgpt"),
|
||||
)
|
||||
)
|
||||
response_root = response.root
|
||||
if not isinstance(response_root, ChatgptLoginAccountResponse):
|
||||
raise RuntimeError(f"unexpected ChatGPT login response: {response_root!r}")
|
||||
return AsyncChatgptLoginHandle(
|
||||
owner,
|
||||
response_root.login_id,
|
||||
response_root.auth_url,
|
||||
)
|
||||
|
||||
|
||||
def start_device_code_login(client: CodexClient) -> DeviceCodeLoginHandle:
|
||||
"""Start device-code ChatGPT login and return the handle for that attempt."""
|
||||
response = client.account_login_start(
|
||||
LoginAccountParams(
|
||||
root=ChatgptDeviceCodeLoginAccountParams(type="chatgptDeviceCode"),
|
||||
)
|
||||
)
|
||||
response_root = response.root
|
||||
if not isinstance(response_root, ChatgptDeviceCodeLoginAccountResponse):
|
||||
raise RuntimeError(f"unexpected device-code login response: {response_root!r}")
|
||||
return DeviceCodeLoginHandle(
|
||||
client,
|
||||
response_root.login_id,
|
||||
response_root.verification_url,
|
||||
response_root.user_code,
|
||||
)
|
||||
|
||||
|
||||
async def async_start_device_code_login(
|
||||
owner: _AsyncLoginOwner,
|
||||
) -> AsyncDeviceCodeLoginHandle:
|
||||
"""Start async device-code ChatGPT login and return that attempt's handle."""
|
||||
response = await owner._client.account_login_start(
|
||||
LoginAccountParams(
|
||||
root=ChatgptDeviceCodeLoginAccountParams(type="chatgptDeviceCode"),
|
||||
)
|
||||
)
|
||||
response_root = response.root
|
||||
if not isinstance(response_root, ChatgptDeviceCodeLoginAccountResponse):
|
||||
raise RuntimeError(f"unexpected device-code login response: {response_root!r}")
|
||||
return AsyncDeviceCodeLoginHandle(
|
||||
owner,
|
||||
response_root.login_id,
|
||||
response_root.verification_url,
|
||||
response_root.user_code,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ChatgptLoginHandle:
|
||||
"""Live browser-login attempt returned by `Codex.login_chatgpt()`."""
|
||||
|
||||
_client: CodexClient
|
||||
login_id: str
|
||||
auth_url: str
|
||||
|
||||
def wait(self) -> AccountLoginCompletedNotification:
|
||||
"""Wait for this browser login attempt's completion notification."""
|
||||
return self._client.wait_for_login_completed(self.login_id)
|
||||
|
||||
def cancel(self) -> CancelLoginAccountResponse:
|
||||
"""Cancel this browser login attempt."""
|
||||
return self._client.account_login_cancel(self.login_id)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class DeviceCodeLoginHandle:
|
||||
"""Live device-code login attempt returned by `Codex.login_chatgpt_device_code()`."""
|
||||
|
||||
_client: CodexClient
|
||||
login_id: str
|
||||
verification_url: str
|
||||
user_code: str
|
||||
|
||||
def wait(self) -> AccountLoginCompletedNotification:
|
||||
"""Wait for this device-code login attempt's completion notification."""
|
||||
return self._client.wait_for_login_completed(self.login_id)
|
||||
|
||||
def cancel(self) -> CancelLoginAccountResponse:
|
||||
"""Cancel this device-code login attempt."""
|
||||
return self._client.account_login_cancel(self.login_id)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AsyncChatgptLoginHandle:
|
||||
"""Live browser-login attempt returned by `AsyncCodex.login_chatgpt()`."""
|
||||
|
||||
_codex: _AsyncLoginOwner
|
||||
login_id: str
|
||||
auth_url: str
|
||||
|
||||
async def wait(self) -> AccountLoginCompletedNotification:
|
||||
"""Wait for this browser login attempt's completion notification."""
|
||||
await self._codex._ensure_initialized()
|
||||
return await self._codex._client.wait_for_login_completed(self.login_id)
|
||||
|
||||
async def cancel(self) -> CancelLoginAccountResponse:
|
||||
"""Cancel this browser login attempt."""
|
||||
await self._codex._ensure_initialized()
|
||||
return await self._codex._client.account_login_cancel(self.login_id)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AsyncDeviceCodeLoginHandle:
|
||||
"""Live device-code attempt returned by `AsyncCodex.login_chatgpt_device_code()`."""
|
||||
|
||||
_codex: _AsyncLoginOwner
|
||||
login_id: str
|
||||
verification_url: str
|
||||
user_code: str
|
||||
|
||||
async def wait(self) -> AccountLoginCompletedNotification:
|
||||
"""Wait for this device-code login attempt's completion notification."""
|
||||
await self._codex._ensure_initialized()
|
||||
return await self._codex._client.wait_for_login_completed(self.login_id)
|
||||
|
||||
async def cancel(self) -> CancelLoginAccountResponse:
|
||||
"""Cancel this device-code login attempt."""
|
||||
await self._codex._ensure_initialized()
|
||||
return await self._codex._client.account_login_cancel(self.login_id)
|
||||
389
sdk/python/src/openai_codex/_message_router.py
Normal file
389
sdk/python/src/openai_codex/_message_router.py
Normal file
@@ -0,0 +1,389 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
import threading
|
||||
import weakref
|
||||
from collections import deque
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Iterator
|
||||
|
||||
from ._goal import _GoalOperationState
|
||||
from .errors import CodexError, TransportClosedError, map_jsonrpc_error
|
||||
from .generated.notification_registry import notification_turn_id
|
||||
from .generated.v2_all import AccountLoginCompletedNotification
|
||||
from .models import JsonValue, Notification, UnknownNotification
|
||||
|
||||
ResponseQueueItem = JsonValue | BaseException
|
||||
NotificationQueueItem = Notification | BaseException
|
||||
|
||||
|
||||
@dataclass
|
||||
class _TurnState:
|
||||
id: str
|
||||
thread_id: str | None = None
|
||||
events: dict[int, NotificationQueueItem] = field(default_factory=dict)
|
||||
first_event: int = 0
|
||||
next_event: int = 0
|
||||
subscribers: dict[object, int] = field(default_factory=dict)
|
||||
completed: bool = False
|
||||
|
||||
|
||||
class _TurnSubscription:
|
||||
"""One consumer's cursor over shared unread events."""
|
||||
|
||||
def __init__(self, router: MessageRouter, state: _TurnState, cursor: int) -> None:
|
||||
self._router = router
|
||||
self._state = state
|
||||
self._cursor = cursor
|
||||
self._token = object()
|
||||
state.subscribers[self._token] = self._cursor
|
||||
self._closed = False
|
||||
self._release = weakref.finalize(
|
||||
self, router._release_turn, weakref.ref(router), state, self._token
|
||||
)
|
||||
|
||||
def next(self) -> Notification:
|
||||
with self._router._turn_condition:
|
||||
while self._cursor == self._state.next_event and not self._closed:
|
||||
if self._state.completed:
|
||||
raise TransportClosedError("Turn is no longer streaming")
|
||||
self._router._turn_condition.wait()
|
||||
if self._closed:
|
||||
raise TransportClosedError("Turn subscription closed")
|
||||
item = self._state.events[self._cursor]
|
||||
self._cursor += 1
|
||||
self._state.subscribers[self._token] = self._cursor
|
||||
self._router._prune_turn_events(self._state)
|
||||
if isinstance(item, BaseException):
|
||||
raise item
|
||||
return item
|
||||
|
||||
def close(self) -> None:
|
||||
with self._router._turn_condition:
|
||||
self._closed = True
|
||||
self._router._turn_condition.notify_all()
|
||||
self._release()
|
||||
|
||||
|
||||
class MessageRouter:
|
||||
"""Route reader-thread messages to the SDK operation waiting for them.
|
||||
|
||||
The app-server stdio transport is a single ordered stream, so only the
|
||||
reader thread should consume stdout. This router keeps the rest of the SDK
|
||||
from competing for that stream by giving each in-flight JSON-RPC request
|
||||
its own queue and each turn consumer its own event cursor.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Create empty response, turn, and global notification queues."""
|
||||
# GC can release abandoned subscriptions during another routing operation.
|
||||
self._lock = threading.RLock()
|
||||
self._response_waiters: dict[str, queue.Queue[ResponseQueueItem]] = {}
|
||||
self._login_notifications: dict[str, queue.Queue[NotificationQueueItem]] = {}
|
||||
self._pending_login_notifications: dict[str, deque[Notification]] = {}
|
||||
self._turn_condition = threading.Condition(self._lock)
|
||||
self._turn_states: dict[str, _TurnState] = {}
|
||||
self._turn_notifications: dict[str, _TurnSubscription] = {}
|
||||
self._pending_turn_requests: dict[str, BaseException | None] = {}
|
||||
self._goal_operations: dict[str, _GoalOperationState] = {}
|
||||
self._global_notifications: queue.Queue[NotificationQueueItem] = queue.Queue()
|
||||
|
||||
def create_response_waiter(self, request_id: str) -> queue.Queue[ResponseQueueItem]:
|
||||
"""Register a one-shot queue for a JSON-RPC response id."""
|
||||
|
||||
waiter: queue.Queue[ResponseQueueItem] = queue.Queue(maxsize=1)
|
||||
with self._lock:
|
||||
self._response_waiters[request_id] = waiter
|
||||
return waiter
|
||||
|
||||
def discard_response_waiter(self, request_id: str) -> None:
|
||||
"""Remove a response waiter when the request could not be written."""
|
||||
|
||||
with self._lock:
|
||||
self._response_waiters.pop(request_id, None)
|
||||
|
||||
def next_global_notification(self) -> Notification:
|
||||
"""Block until the next notification that is not scoped to a turn."""
|
||||
|
||||
item = self._global_notifications.get()
|
||||
if isinstance(item, BaseException):
|
||||
raise item
|
||||
return item
|
||||
|
||||
def register_login(self, login_id: str) -> None:
|
||||
"""Register a queue for one interactive login attempt."""
|
||||
|
||||
login_queue: queue.Queue[NotificationQueueItem] = queue.Queue()
|
||||
with self._lock:
|
||||
if login_id in self._login_notifications:
|
||||
return
|
||||
pending = self._pending_login_notifications.pop(login_id, deque())
|
||||
self._login_notifications[login_id] = login_queue
|
||||
for notification in pending:
|
||||
login_queue.put(notification)
|
||||
|
||||
def unregister_login(self, login_id: str) -> None:
|
||||
"""Stop routing future notifications for one login attempt."""
|
||||
|
||||
with self._lock:
|
||||
self._login_notifications.pop(login_id, None)
|
||||
|
||||
def next_login_notification(self, login_id: str) -> Notification:
|
||||
"""Block until the next notification for a registered login attempt."""
|
||||
|
||||
with self._lock:
|
||||
login_queue = self._login_notifications.get(login_id)
|
||||
if login_queue is None:
|
||||
raise RuntimeError(f"login {login_id!r} is not registered for waiting")
|
||||
item = login_queue.get()
|
||||
if isinstance(item, BaseException):
|
||||
raise item
|
||||
return item
|
||||
|
||||
@contextmanager
|
||||
def pending_turn(self, thread_id: str) -> Iterator[dict[str, int]]:
|
||||
"""Buffer events from the point a turn/start request is sent."""
|
||||
with self._lock:
|
||||
cursors = {turn_id: state.next_event for turn_id, state in self._turn_states.items()}
|
||||
self._pending_turn_requests[thread_id] = None
|
||||
try:
|
||||
yield cursors
|
||||
finally:
|
||||
with self._lock:
|
||||
del self._pending_turn_requests[thread_id]
|
||||
for state in list(self._turn_states.values()):
|
||||
if state.thread_id in (None, thread_id):
|
||||
self._prune_turn_events(state)
|
||||
|
||||
def prepare_turn(
|
||||
self, turn_id: str, thread_id: str, cursors: dict[str, int], *, for_handle: bool
|
||||
) -> _TurnSubscription | None:
|
||||
"""Attach the requesting handle or the single low-level consumer."""
|
||||
with self._lock:
|
||||
state = self._turn_states.setdefault(turn_id, _TurnState(turn_id, thread_id))
|
||||
state.thread_id = thread_id
|
||||
if not for_handle and turn_id in self._turn_notifications:
|
||||
return None
|
||||
if not state.completed and (err := self._pending_turn_requests[thread_id]) is not None:
|
||||
state.events[state.next_event] = err
|
||||
state.next_event += 1
|
||||
state.completed = True
|
||||
subscription = _TurnSubscription(self, state, cursors.get(turn_id, 0))
|
||||
if not for_handle:
|
||||
self._turn_notifications[turn_id] = subscription
|
||||
return subscription
|
||||
|
||||
def subscribe_turn(self, turn_id: str) -> _TurnSubscription:
|
||||
"""Attach a consumer starting at the next event for this turn."""
|
||||
with self._lock:
|
||||
state = self._turn_states.setdefault(turn_id, _TurnState(turn_id))
|
||||
return _TurnSubscription(self, state, state.next_event)
|
||||
|
||||
@staticmethod
|
||||
def _release_turn(
|
||||
router_ref: weakref.ReferenceType[MessageRouter], state: _TurnState, token: object
|
||||
) -> None:
|
||||
router = router_ref()
|
||||
if router is not None:
|
||||
with router._lock:
|
||||
default = router._turn_notifications.get(state.id)
|
||||
if default is not None and default._token is token:
|
||||
del router._turn_notifications[state.id]
|
||||
state.subscribers.pop(token, None)
|
||||
router._prune_turn_events(state)
|
||||
|
||||
def _prune_turn_events(self, state: _TurnState) -> None:
|
||||
if state.thread_id in self._pending_turn_requests or (
|
||||
state.thread_id is None and self._pending_turn_requests
|
||||
):
|
||||
return
|
||||
consumed = min(state.subscribers.values(), default=state.next_event)
|
||||
while state.first_event < consumed:
|
||||
del state.events[state.first_event]
|
||||
state.first_event += 1
|
||||
if not state.subscribers and self._turn_states.get(state.id) is state:
|
||||
del self._turn_states[state.id]
|
||||
|
||||
def register_turn(self, turn_id: str) -> None:
|
||||
"""Register the default consumer used by the low-level client API."""
|
||||
with self._lock:
|
||||
if turn_id not in self._turn_notifications:
|
||||
self._turn_notifications[turn_id] = self.subscribe_turn(turn_id)
|
||||
|
||||
def unregister_turn(self, turn_id: str) -> None:
|
||||
"""Close only the low-level consumer, leaving other handles subscribed."""
|
||||
with self._lock:
|
||||
if subscription := self._turn_notifications.get(turn_id):
|
||||
subscription.close()
|
||||
|
||||
def next_turn_notification(self, turn_id: str) -> Notification:
|
||||
"""Block until the next event for the default low-level consumer."""
|
||||
with self._lock:
|
||||
subscription = self._turn_notifications.get(turn_id)
|
||||
if subscription is None:
|
||||
raise RuntimeError(f"turn {turn_id!r} is not registered for streaming")
|
||||
return subscription.next()
|
||||
|
||||
def register_goal(self, thread_id: str) -> _GoalOperationState:
|
||||
"""Register one thread-scoped logical goal operation before it starts."""
|
||||
state = _GoalOperationState(thread_id=thread_id)
|
||||
state.activate_turn_routing()
|
||||
return self._register_goal(state)
|
||||
|
||||
def reserve_goal(self, thread_id: str) -> _GoalOperationState:
|
||||
"""Reserve a thread route without accepting physical turns yet."""
|
||||
return self._register_goal(_GoalOperationState(thread_id=thread_id))
|
||||
|
||||
def _register_goal(self, state: _GoalOperationState) -> _GoalOperationState:
|
||||
with self._lock:
|
||||
if state.thread_id in self._goal_operations:
|
||||
raise RuntimeError(
|
||||
f"thread {state.thread_id!r} already has an active goal operation"
|
||||
)
|
||||
self._goal_operations[state.thread_id] = state
|
||||
return state
|
||||
|
||||
def unregister_goal(self, state: _GoalOperationState) -> None:
|
||||
"""Stop routing notifications to a completed logical goal operation."""
|
||||
with self._lock:
|
||||
if self._goal_operations.get(state.thread_id) is state:
|
||||
self._goal_operations.pop(state.thread_id)
|
||||
|
||||
def has_goal(self, thread_id: str) -> bool:
|
||||
"""Return whether a logical goal operation owns this thread route."""
|
||||
with self._lock:
|
||||
return thread_id in self._goal_operations
|
||||
|
||||
def route_response(self, msg: dict[str, JsonValue]) -> None:
|
||||
"""Deliver a JSON-RPC response or error to its request waiter."""
|
||||
|
||||
request_id = msg.get("id")
|
||||
with self._lock:
|
||||
waiter = self._response_waiters.pop(str(request_id), None)
|
||||
if waiter is None:
|
||||
return
|
||||
|
||||
if "error" in msg:
|
||||
err = msg["error"]
|
||||
if isinstance(err, dict):
|
||||
waiter.put(
|
||||
map_jsonrpc_error(
|
||||
int(err.get("code", -32000)),
|
||||
str(err.get("message", "unknown")),
|
||||
err.get("data"),
|
||||
)
|
||||
)
|
||||
else:
|
||||
waiter.put(CodexError("Malformed JSON-RPC error response"))
|
||||
return
|
||||
|
||||
waiter.put(msg.get("result"))
|
||||
|
||||
def route_notification(self, notification: Notification) -> None:
|
||||
"""Deliver a notification to a turn queue or the global queue."""
|
||||
|
||||
login_id = self._notification_login_id(notification)
|
||||
if login_id is not None:
|
||||
with self._lock:
|
||||
login_queue = self._login_notifications.get(login_id)
|
||||
if login_queue is None:
|
||||
self._pending_login_notifications.setdefault(login_id, deque()).append(
|
||||
notification
|
||||
)
|
||||
return
|
||||
login_queue.put(notification)
|
||||
return
|
||||
|
||||
turn_id = self._notification_turn_id(notification)
|
||||
thread_id = self._notification_thread_id(notification)
|
||||
if thread_id is not None:
|
||||
with self._lock:
|
||||
goal_state = self._goal_operations.get(thread_id)
|
||||
if goal_state is not None and (
|
||||
turn_id is not None or notification.method.startswith("thread/goal/")
|
||||
):
|
||||
if goal_state.observe(notification):
|
||||
if goal_state.is_finished():
|
||||
self.unregister_goal(goal_state)
|
||||
return
|
||||
if turn_id is None:
|
||||
self._global_notifications.put(notification)
|
||||
return
|
||||
|
||||
with self._turn_condition:
|
||||
state = self._turn_states.setdefault(turn_id, _TurnState(turn_id, thread_id))
|
||||
state.thread_id = thread_id or state.thread_id
|
||||
state.events[state.next_event] = notification
|
||||
state.next_event += 1
|
||||
if notification.method == "turn/completed":
|
||||
state.completed = True
|
||||
self._prune_turn_events(state)
|
||||
self._turn_condition.notify_all()
|
||||
|
||||
def fail_all(self, exc: BaseException) -> None:
|
||||
"""Wake every blocked waiter when the reader thread exits."""
|
||||
|
||||
with self._lock:
|
||||
response_waiters = list(self._response_waiters.values())
|
||||
self._response_waiters.clear()
|
||||
login_queues = list(self._login_notifications.values())
|
||||
self._login_notifications.clear()
|
||||
self._pending_login_notifications.clear()
|
||||
for thread_id in self._pending_turn_requests:
|
||||
self._pending_turn_requests[thread_id] = exc
|
||||
for state in list(self._turn_states.values()):
|
||||
state.events[state.next_event] = exc
|
||||
state.next_event += 1
|
||||
state.completed = True
|
||||
self._prune_turn_events(state)
|
||||
self._turn_condition.notify_all()
|
||||
goal_operations = list(self._goal_operations.values())
|
||||
self._goal_operations.clear()
|
||||
# Put the same transport failure into every queue so no SDK call blocks
|
||||
# forever waiting for a response that cannot arrive.
|
||||
for waiter in response_waiters:
|
||||
waiter.put(exc)
|
||||
for login_queue in login_queues:
|
||||
login_queue.put(exc)
|
||||
for goal_operation in goal_operations:
|
||||
goal_operation.fail(exc)
|
||||
self._global_notifications.put(exc)
|
||||
|
||||
def _notification_turn_id(self, notification: Notification) -> str | None:
|
||||
"""Extract routing ids from generated metadata or raw unknown payloads."""
|
||||
payload = notification.payload
|
||||
if isinstance(payload, UnknownNotification):
|
||||
raw_turn_id = payload.params.get("turnId")
|
||||
if isinstance(raw_turn_id, str):
|
||||
return raw_turn_id
|
||||
raw_turn = payload.params.get("turn")
|
||||
if isinstance(raw_turn, dict):
|
||||
raw_nested_turn_id = raw_turn.get("id")
|
||||
if isinstance(raw_nested_turn_id, str):
|
||||
return raw_nested_turn_id
|
||||
return None
|
||||
return notification_turn_id(payload)
|
||||
|
||||
def _notification_thread_id(self, notification: Notification) -> str | None:
|
||||
"""Extract thread ids from typed payloads or raw unknown payloads."""
|
||||
payload = notification.payload
|
||||
if isinstance(payload, UnknownNotification):
|
||||
raw_thread_id = payload.params.get("threadId")
|
||||
return raw_thread_id if isinstance(raw_thread_id, str) else None
|
||||
thread_id = getattr(payload, "thread_id", None)
|
||||
return thread_id if isinstance(thread_id, str) else None
|
||||
|
||||
def _notification_login_id(self, notification: Notification) -> str | None:
|
||||
"""Extract the login attempt id from completion notifications."""
|
||||
if notification.method != "account/login/completed":
|
||||
return None
|
||||
|
||||
payload = notification.payload
|
||||
if isinstance(payload, AccountLoginCompletedNotification):
|
||||
return payload.login_id
|
||||
if isinstance(payload, UnknownNotification):
|
||||
raw_login_id = payload.params.get("loginId")
|
||||
if isinstance(raw_login_id, str):
|
||||
return raw_login_id
|
||||
return None
|
||||
135
sdk/python/src/openai_codex/_run.py
Normal file
135
sdk/python/src/openai_codex/_run.py
Normal file
@@ -0,0 +1,135 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import AsyncIterator, Iterator
|
||||
|
||||
from .generated.v2_all import (
|
||||
AgentMessageThreadItem,
|
||||
ItemCompletedNotification,
|
||||
MessagePhase,
|
||||
ThreadItem,
|
||||
ThreadTokenUsage,
|
||||
ThreadTokenUsageUpdatedNotification,
|
||||
Turn,
|
||||
TurnCompletedNotification,
|
||||
TurnError,
|
||||
TurnStatus,
|
||||
)
|
||||
from .models import Notification
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class TurnResult:
|
||||
"""Collected result returned after a turn completes."""
|
||||
|
||||
id: str
|
||||
status: TurnStatus
|
||||
error: TurnError | None
|
||||
started_at: int | None
|
||||
completed_at: int | None
|
||||
duration_ms: int | None
|
||||
final_response: str | None
|
||||
items: list[ThreadItem]
|
||||
usage: ThreadTokenUsage | None
|
||||
|
||||
|
||||
def _agent_message_item_from_thread_item(
|
||||
item: ThreadItem,
|
||||
) -> AgentMessageThreadItem | None:
|
||||
thread_item = item.root if hasattr(item, "root") else item
|
||||
if isinstance(thread_item, AgentMessageThreadItem):
|
||||
return thread_item
|
||||
return None
|
||||
|
||||
|
||||
def _final_assistant_response_from_items(items: list[ThreadItem]) -> str | None:
|
||||
last_unknown_phase_response: str | None = None
|
||||
|
||||
for item in reversed(items):
|
||||
agent_message = _agent_message_item_from_thread_item(item)
|
||||
if agent_message is None:
|
||||
continue
|
||||
if agent_message.phase == MessagePhase.final_answer:
|
||||
return agent_message.text
|
||||
if agent_message.phase is None and last_unknown_phase_response is None:
|
||||
last_unknown_phase_response = agent_message.text
|
||||
|
||||
return last_unknown_phase_response
|
||||
|
||||
|
||||
def _raise_for_failed_turn(turn: Turn) -> None:
|
||||
if turn.status != TurnStatus.failed:
|
||||
return
|
||||
if turn.error is not None and turn.error.message:
|
||||
raise RuntimeError(turn.error.message)
|
||||
raise RuntimeError(f"turn failed with status {turn.status.value}")
|
||||
|
||||
|
||||
def _collect_turn_result(stream: Iterator[Notification], *, turn_id: str) -> TurnResult:
|
||||
completed: TurnCompletedNotification | None = None
|
||||
items: list[ThreadItem] = []
|
||||
usage: ThreadTokenUsage | None = None
|
||||
|
||||
for event in stream:
|
||||
payload = event.payload
|
||||
if isinstance(payload, ItemCompletedNotification) and payload.turn_id == turn_id:
|
||||
items.append(payload.item)
|
||||
continue
|
||||
if isinstance(payload, ThreadTokenUsageUpdatedNotification) and payload.turn_id == turn_id:
|
||||
usage = payload.token_usage
|
||||
continue
|
||||
if isinstance(payload, TurnCompletedNotification) and payload.turn.id == turn_id:
|
||||
completed = payload
|
||||
|
||||
if completed is None:
|
||||
raise RuntimeError("turn completed event not received")
|
||||
|
||||
_raise_for_failed_turn(completed.turn)
|
||||
turn = completed.turn
|
||||
return TurnResult(
|
||||
id=turn.id,
|
||||
status=turn.status,
|
||||
error=turn.error,
|
||||
started_at=turn.started_at,
|
||||
completed_at=turn.completed_at,
|
||||
duration_ms=turn.duration_ms,
|
||||
final_response=_final_assistant_response_from_items(items),
|
||||
items=items,
|
||||
usage=usage,
|
||||
)
|
||||
|
||||
|
||||
async def _collect_async_turn_result(
|
||||
stream: AsyncIterator[Notification], *, turn_id: str
|
||||
) -> TurnResult:
|
||||
completed: TurnCompletedNotification | None = None
|
||||
items: list[ThreadItem] = []
|
||||
usage: ThreadTokenUsage | None = None
|
||||
|
||||
async for event in stream:
|
||||
payload = event.payload
|
||||
if isinstance(payload, ItemCompletedNotification) and payload.turn_id == turn_id:
|
||||
items.append(payload.item)
|
||||
continue
|
||||
if isinstance(payload, ThreadTokenUsageUpdatedNotification) and payload.turn_id == turn_id:
|
||||
usage = payload.token_usage
|
||||
continue
|
||||
if isinstance(payload, TurnCompletedNotification) and payload.turn.id == turn_id:
|
||||
completed = payload
|
||||
|
||||
if completed is None:
|
||||
raise RuntimeError("turn completed event not received")
|
||||
|
||||
_raise_for_failed_turn(completed.turn)
|
||||
turn = completed.turn
|
||||
return TurnResult(
|
||||
id=turn.id,
|
||||
status=turn.status,
|
||||
error=turn.error,
|
||||
started_at=turn.started_at,
|
||||
completed_at=turn.completed_at,
|
||||
duration_ms=turn.duration_ms,
|
||||
final_response=_final_assistant_response_from_items(items),
|
||||
items=items,
|
||||
usage=usage,
|
||||
)
|
||||
64
sdk/python/src/openai_codex/_runtime_requirements.py
Normal file
64
sdk/python/src/openai_codex/_runtime_requirements.py
Normal file
@@ -0,0 +1,64 @@
|
||||
"""Runtime version and checkout-schema requirements for newer SDK options."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from functools import cached_property
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from packaging.version import InvalidVersion, Version
|
||||
|
||||
MINIMUM_RUNTIME_VERSION = "0.151.0"
|
||||
|
||||
|
||||
def require_runtime_version(version: str | None) -> None:
|
||||
"""Reject unknown or unsupported versions, including prereleases at the minimum."""
|
||||
# CLI alpha hotfixes use 0.154.0-alpha.1.2; PEP 440 spells that a1.post2.
|
||||
normalized = re.sub(r"-alpha\.(\d+)\.(\d+)$", r"a\1.post\2", version or "")
|
||||
try:
|
||||
if Version(normalized) >= Version(MINIMUM_RUNTIME_VERSION):
|
||||
return
|
||||
except InvalidVersion:
|
||||
pass
|
||||
raise ValueError(
|
||||
f"Codex CLI {MINIMUM_RUNTIME_VERSION} or newer is required; "
|
||||
f"reported version is {version or 'unknown'!r}"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CheckoutCapabilities:
|
||||
"""Lazily inspect the same executable and configuration as a running checkout."""
|
||||
|
||||
command: tuple[str, ...]
|
||||
cwd: str | None
|
||||
env: dict[str, str]
|
||||
|
||||
@cached_property
|
||||
def fields(self) -> dict[str, frozenset[str]]:
|
||||
try:
|
||||
with TemporaryDirectory(prefix="codex-sdk-schema-") as directory:
|
||||
subprocess.run(
|
||||
[*self.command, "generate-json-schema", "--experimental", "--out", directory],
|
||||
cwd=self.cwd,
|
||||
env=self.env,
|
||||
capture_output=True,
|
||||
check=True,
|
||||
timeout=30,
|
||||
)
|
||||
result = {}
|
||||
for method, name in (
|
||||
("turn/start", "TurnStartParams"),
|
||||
("thread/resume", "ThreadResumeParams"),
|
||||
("thread/fork", "ThreadForkParams"),
|
||||
):
|
||||
schema = json.loads((Path(directory) / "v2" / f"{name}.json").read_text())
|
||||
properties = schema.get("properties") if isinstance(schema, dict) else None
|
||||
if not isinstance(properties, dict):
|
||||
raise ValueError(f"Missing properties in {name} schema")
|
||||
result[method] = frozenset(properties)
|
||||
return result
|
||||
except (OSError, subprocess.SubprocessError, ValueError) as exc:
|
||||
raise ValueError("Could not inspect the unversioned CLI's experimental schema") from exc
|
||||
78
sdk/python/src/openai_codex/_sandbox.py
Normal file
78
sdk/python/src/openai_codex/_sandbox.py
Normal file
@@ -0,0 +1,78 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum
|
||||
from typing import NoReturn
|
||||
|
||||
from .generated.v2_all import (
|
||||
DangerFullAccessSandboxPolicy,
|
||||
ReadOnlySandboxPolicy,
|
||||
SandboxMode,
|
||||
SandboxPolicy,
|
||||
WorkspaceWriteSandboxPolicy,
|
||||
)
|
||||
|
||||
|
||||
class Sandbox(str, Enum):
|
||||
"""Preset filesystem access levels for threads and turns.
|
||||
|
||||
`read_only` allows file reads without writes. `workspace_write` is the
|
||||
normal default for projects with a recorded trust decision and allows
|
||||
writes inside the workspace and configured writable roots. `full_access`
|
||||
removes filesystem access restrictions.
|
||||
"""
|
||||
|
||||
read_only = "read-only"
|
||||
workspace_write = "workspace-write"
|
||||
full_access = "full-access"
|
||||
|
||||
|
||||
def _require_sandbox(sandbox: Sandbox) -> None:
|
||||
if isinstance(sandbox, Sandbox):
|
||||
return
|
||||
options = ", ".join(f"Sandbox.{value.name}" for value in Sandbox)
|
||||
raise ValueError(f"sandbox must be one of: {options}")
|
||||
|
||||
|
||||
def _sandbox_mode(sandbox: Sandbox | None) -> SandboxMode | None:
|
||||
"""Translate a public preset to the thread lifecycle wire mode."""
|
||||
if sandbox is None:
|
||||
return None
|
||||
_require_sandbox(sandbox)
|
||||
|
||||
match sandbox:
|
||||
case Sandbox.read_only:
|
||||
return SandboxMode.read_only
|
||||
case Sandbox.workspace_write:
|
||||
return SandboxMode.workspace_write
|
||||
case Sandbox.full_access:
|
||||
return SandboxMode.danger_full_access
|
||||
case _:
|
||||
return _assert_never_sandbox(sandbox)
|
||||
|
||||
|
||||
def _sandbox_policy(sandbox: Sandbox | None) -> SandboxPolicy | None:
|
||||
"""Translate a public preset to the turn override wire policy."""
|
||||
if sandbox is None:
|
||||
return None
|
||||
_require_sandbox(sandbox)
|
||||
|
||||
match sandbox:
|
||||
case Sandbox.read_only:
|
||||
return SandboxPolicy(
|
||||
root=ReadOnlySandboxPolicy(type="readOnly"),
|
||||
)
|
||||
case Sandbox.workspace_write:
|
||||
return SandboxPolicy(
|
||||
root=WorkspaceWriteSandboxPolicy(type="workspaceWrite"),
|
||||
)
|
||||
case Sandbox.full_access:
|
||||
return SandboxPolicy(
|
||||
root=DangerFullAccessSandboxPolicy(type="dangerFullAccess"),
|
||||
)
|
||||
case _:
|
||||
return _assert_never_sandbox(sandbox)
|
||||
|
||||
|
||||
def _assert_never_sandbox(sandbox: NoReturn) -> NoReturn:
|
||||
"""Make sandbox mapping exhaustive for static type checkers."""
|
||||
raise AssertionError(f"Unhandled sandbox: {sandbox!r}")
|
||||
36
sdk/python/src/openai_codex/_version.py
Normal file
36
sdk/python/src/openai_codex/_version.py
Normal file
@@ -0,0 +1,36 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from importlib.metadata import PackageNotFoundError, version as distribution_version
|
||||
from pathlib import Path
|
||||
|
||||
DISTRIBUTION_NAME = "openai-codex"
|
||||
UNKNOWN_VERSION = "0+unknown"
|
||||
|
||||
|
||||
def package_version() -> str:
|
||||
source_version = _source_tree_project_version()
|
||||
if source_version is not None:
|
||||
return source_version
|
||||
|
||||
try:
|
||||
return distribution_version(DISTRIBUTION_NAME)
|
||||
except PackageNotFoundError:
|
||||
return UNKNOWN_VERSION
|
||||
|
||||
|
||||
def _source_tree_project_version() -> str | None:
|
||||
pyproject_path = Path(__file__).resolve().parents[2] / "pyproject.toml"
|
||||
if not pyproject_path.exists():
|
||||
return None
|
||||
|
||||
match = re.search(
|
||||
r'(?m)^version = "([^"]+)"$',
|
||||
pyproject_path.read_text(encoding="utf-8"),
|
||||
)
|
||||
if match is None:
|
||||
return None
|
||||
return match.group(1)
|
||||
|
||||
|
||||
__version__ = package_version()
|
||||
901
sdk/python/src/openai_codex/api.py
Normal file
901
sdk/python/src/openai_codex/api.py
Normal file
@@ -0,0 +1,901 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from dataclasses import dataclass, field
|
||||
from typing import AsyncIterator, Iterator
|
||||
|
||||
from ._approval_mode import (
|
||||
ApprovalMode as ApprovalMode,
|
||||
_approval_mode_override_settings,
|
||||
_approval_mode_settings,
|
||||
)
|
||||
from ._initialize_metadata import validate_initialize_metadata
|
||||
from ._inputs import (
|
||||
ExternalMessage as ExternalMessage,
|
||||
ImageInput as ImageInput,
|
||||
Input as Input,
|
||||
InputItem as InputItem,
|
||||
LocalImageInput as LocalImageInput,
|
||||
MentionInput as MentionInput,
|
||||
RunInput,
|
||||
SkillInput as SkillInput,
|
||||
TextInput as TextInput,
|
||||
_normalize_run_input,
|
||||
_to_wire_input,
|
||||
_to_wire_turn_input,
|
||||
)
|
||||
from ._login import (
|
||||
AsyncChatgptLoginHandle,
|
||||
AsyncDeviceCodeLoginHandle,
|
||||
ChatgptLoginHandle,
|
||||
DeviceCodeLoginHandle,
|
||||
async_start_chatgpt_login,
|
||||
async_start_device_code_login,
|
||||
start_chatgpt_login,
|
||||
start_device_code_login,
|
||||
)
|
||||
from ._message_router import _TurnSubscription
|
||||
from ._run import (
|
||||
TurnResult,
|
||||
_collect_async_turn_result,
|
||||
_collect_turn_result,
|
||||
)
|
||||
from ._sandbox import Sandbox as Sandbox, _sandbox_mode, _sandbox_policy
|
||||
from .async_client import AsyncCodexClient
|
||||
from .client import CodexClient, CodexConfig
|
||||
from .generated.v2_all import (
|
||||
ApiKeyLoginAccountParams,
|
||||
GetAccountParams,
|
||||
GetAccountResponse,
|
||||
LoginAccountParams,
|
||||
ModelListResponse,
|
||||
Personality,
|
||||
ReasoningEffort,
|
||||
ReasoningSummary,
|
||||
SortDirection,
|
||||
ThreadArchiveResponse,
|
||||
ThreadCompactStartResponse,
|
||||
ThreadForkParams,
|
||||
ThreadListCwdFilter,
|
||||
ThreadListParams,
|
||||
ThreadListResponse,
|
||||
ThreadReadResponse,
|
||||
ThreadResumeParams,
|
||||
ThreadSetNameResponse,
|
||||
ThreadSortKey,
|
||||
ThreadSource,
|
||||
ThreadSourceKind,
|
||||
ThreadStartParams,
|
||||
ThreadStartSource,
|
||||
TurnCompletedNotification,
|
||||
TurnInterruptResponse,
|
||||
TurnStartParams,
|
||||
TurnSteerResponse,
|
||||
)
|
||||
from .models import InitializeResponse, JsonObject, Notification
|
||||
|
||||
|
||||
class Codex:
|
||||
"""Synchronous client for creating threads and running Codex turns.
|
||||
|
||||
The client starts its runtime connection during construction. Use it as a
|
||||
context manager so resources are closed promptly.
|
||||
"""
|
||||
|
||||
def __init__(self, config: CodexConfig | None = None) -> None:
|
||||
self._client = CodexClient(config=config)
|
||||
try:
|
||||
self._client.start()
|
||||
self._init = validate_initialize_metadata(self._client.initialize())
|
||||
except Exception:
|
||||
self._client.close()
|
||||
raise
|
||||
|
||||
def __enter__(self) -> "Codex":
|
||||
return self
|
||||
|
||||
def __exit__(self, _exc_type, _exc, _tb) -> None:
|
||||
self.close()
|
||||
|
||||
@property
|
||||
def metadata(self) -> InitializeResponse:
|
||||
return self._init
|
||||
|
||||
def close(self) -> None:
|
||||
self._client.close()
|
||||
|
||||
def login_api_key(self, api_key: str) -> None:
|
||||
"""Authenticate Codex with an API key."""
|
||||
self._client.account_login_start(
|
||||
LoginAccountParams(
|
||||
root=ApiKeyLoginAccountParams(
|
||||
api_key=api_key,
|
||||
type="apiKey",
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
def login_chatgpt(self) -> ChatgptLoginHandle:
|
||||
"""Start browser-based ChatGPT login and return its live handle."""
|
||||
return start_chatgpt_login(self._client)
|
||||
|
||||
def login_chatgpt_device_code(self) -> DeviceCodeLoginHandle:
|
||||
"""Start device-code ChatGPT login and return its live handle."""
|
||||
return start_device_code_login(self._client)
|
||||
|
||||
def account(self, *, refresh_token: bool = False) -> GetAccountResponse:
|
||||
"""Read the current Codex account state."""
|
||||
return self._client.account_read(GetAccountParams(refresh_token=refresh_token))
|
||||
|
||||
def logout(self) -> None:
|
||||
"""Clear the current Codex account session."""
|
||||
self._client.account_logout()
|
||||
|
||||
# BEGIN GENERATED: Codex.flat_methods
|
||||
def thread_start(
|
||||
self,
|
||||
*,
|
||||
approval_mode: ApprovalMode = ApprovalMode.auto_review,
|
||||
base_instructions: str | None = None,
|
||||
config: JsonObject | None = None,
|
||||
cwd: str | None = None,
|
||||
developer_instructions: str | None = None,
|
||||
ephemeral: bool | None = None,
|
||||
model: str | None = None,
|
||||
model_provider: str | None = None,
|
||||
personality: Personality | None = None,
|
||||
sandbox: Sandbox | None = None,
|
||||
service_name: str | None = None,
|
||||
service_tier: str | None = None,
|
||||
session_start_source: ThreadStartSource | None = None,
|
||||
thread_source: ThreadSource | None = None,
|
||||
) -> Thread:
|
||||
"""Create a new Codex conversation thread."""
|
||||
approval_policy, approvals_reviewer = _approval_mode_settings(approval_mode)
|
||||
params = ThreadStartParams(
|
||||
approval_policy=approval_policy,
|
||||
approvals_reviewer=approvals_reviewer,
|
||||
base_instructions=base_instructions,
|
||||
config=config,
|
||||
cwd=cwd,
|
||||
developer_instructions=developer_instructions,
|
||||
ephemeral=ephemeral,
|
||||
model=model,
|
||||
model_provider=model_provider,
|
||||
personality=personality,
|
||||
sandbox=_sandbox_mode(sandbox),
|
||||
service_name=service_name,
|
||||
service_tier=service_tier,
|
||||
session_start_source=session_start_source,
|
||||
thread_source=thread_source,
|
||||
)
|
||||
started = self._client.thread_start(params)
|
||||
return Thread(self._client, started.thread.id)
|
||||
|
||||
def thread_list(
|
||||
self,
|
||||
*,
|
||||
archived: bool | None = None,
|
||||
cursor: str | None = None,
|
||||
cwd: ThreadListCwdFilter | None = None,
|
||||
limit: int | None = None,
|
||||
model_providers: list[str] | None = None,
|
||||
search_term: str | None = None,
|
||||
section_id: str | None = None,
|
||||
sort_direction: SortDirection | None = None,
|
||||
sort_key: ThreadSortKey | None = None,
|
||||
source_kinds: list[ThreadSourceKind] | None = None,
|
||||
use_state_db_only: bool | None = None,
|
||||
) -> ThreadListResponse:
|
||||
"""List saved conversation threads."""
|
||||
params = ThreadListParams(
|
||||
archived=archived,
|
||||
cursor=cursor,
|
||||
cwd=cwd,
|
||||
limit=limit,
|
||||
model_providers=model_providers,
|
||||
search_term=search_term,
|
||||
section_id=section_id,
|
||||
sort_direction=sort_direction,
|
||||
sort_key=sort_key,
|
||||
source_kinds=source_kinds,
|
||||
use_state_db_only=use_state_db_only,
|
||||
)
|
||||
return self._client.thread_list(params)
|
||||
|
||||
def thread_resume(
|
||||
self,
|
||||
thread_id: str,
|
||||
*,
|
||||
approval_mode: ApprovalMode | None = None,
|
||||
base_instructions: str | None = None,
|
||||
config: JsonObject | None = None,
|
||||
cwd: str | None = None,
|
||||
developer_instructions: str | None = None,
|
||||
include_turns: bool | None = None,
|
||||
model: str | None = None,
|
||||
model_provider: str | None = None,
|
||||
personality: Personality | None = None,
|
||||
sandbox: Sandbox | None = None,
|
||||
service_tier: str | None = None,
|
||||
) -> Thread:
|
||||
"""Resume an existing conversation thread by ID.
|
||||
|
||||
include_turns controls the runtime response history, not model context.
|
||||
Omit it to preserve the runtime default. Use thread.read() for history.
|
||||
"""
|
||||
approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode)
|
||||
params = ThreadResumeParams(
|
||||
thread_id=thread_id,
|
||||
approval_policy=approval_policy,
|
||||
approvals_reviewer=approvals_reviewer,
|
||||
base_instructions=base_instructions,
|
||||
config=config,
|
||||
cwd=cwd,
|
||||
developer_instructions=developer_instructions,
|
||||
exclude_turns=None if include_turns is None else not include_turns,
|
||||
model=model,
|
||||
model_provider=model_provider,
|
||||
personality=personality,
|
||||
sandbox=_sandbox_mode(sandbox),
|
||||
service_tier=service_tier,
|
||||
)
|
||||
resumed = self._client.thread_resume(thread_id, params)
|
||||
return Thread(self._client, resumed.thread.id)
|
||||
|
||||
def thread_fork(
|
||||
self,
|
||||
thread_id: str,
|
||||
*,
|
||||
approval_mode: ApprovalMode | None = None,
|
||||
base_instructions: str | None = None,
|
||||
config: JsonObject | None = None,
|
||||
cwd: str | None = None,
|
||||
developer_instructions: str | None = None,
|
||||
ephemeral: bool | None = None,
|
||||
include_turns: bool | None = None,
|
||||
model: str | None = None,
|
||||
model_provider: str | None = None,
|
||||
sandbox: Sandbox | None = None,
|
||||
service_tier: str | None = None,
|
||||
thread_source: ThreadSource | None = None,
|
||||
) -> Thread:
|
||||
"""Create a new thread from an existing thread.
|
||||
|
||||
include_turns controls the runtime response history, not model context.
|
||||
Omit it to preserve the runtime default. Use thread.read() for history.
|
||||
"""
|
||||
approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode)
|
||||
params = ThreadForkParams(
|
||||
thread_id=thread_id,
|
||||
approval_policy=approval_policy,
|
||||
approvals_reviewer=approvals_reviewer,
|
||||
base_instructions=base_instructions,
|
||||
config=config,
|
||||
cwd=cwd,
|
||||
developer_instructions=developer_instructions,
|
||||
ephemeral=ephemeral,
|
||||
exclude_turns=None if include_turns is None else not include_turns,
|
||||
model=model,
|
||||
model_provider=model_provider,
|
||||
sandbox=_sandbox_mode(sandbox),
|
||||
service_tier=service_tier,
|
||||
thread_source=thread_source,
|
||||
)
|
||||
forked = self._client.thread_fork(thread_id, params)
|
||||
return Thread(self._client, forked.thread.id)
|
||||
|
||||
def thread_archive(self, thread_id: str) -> ThreadArchiveResponse:
|
||||
"""Archive a stored conversation thread."""
|
||||
return self._client.thread_archive(thread_id)
|
||||
|
||||
def thread_unarchive(self, thread_id: str) -> Thread:
|
||||
"""Restore an archived conversation thread."""
|
||||
unarchived = self._client.thread_unarchive(thread_id)
|
||||
return Thread(self._client, unarchived.thread.id)
|
||||
|
||||
# END GENERATED: Codex.flat_methods
|
||||
|
||||
def models(self, *, include_hidden: bool = False) -> ModelListResponse:
|
||||
"""List available models reported by Codex.
|
||||
|
||||
The deprecated ``Model.supports_personality`` field is always ``False``
|
||||
on the current app-server.
|
||||
"""
|
||||
return self._client.model_list(include_hidden=include_hidden)
|
||||
|
||||
|
||||
class AsyncCodex:
|
||||
"""Async mirror of :class:`Codex`.
|
||||
|
||||
Prefer ``async with AsyncCodex()`` so initialization and shutdown are
|
||||
explicit and paired. The async client initializes lazily on context entry
|
||||
or first awaited API use.
|
||||
"""
|
||||
|
||||
def __init__(self, config: CodexConfig | None = None) -> None:
|
||||
self._client = AsyncCodexClient(config=config)
|
||||
self._init: InitializeResponse | None = None
|
||||
self._initialized = False
|
||||
self._init_lock = asyncio.Lock()
|
||||
|
||||
async def __aenter__(self) -> "AsyncCodex":
|
||||
await self._ensure_initialized()
|
||||
return self
|
||||
|
||||
async def __aexit__(self, _exc_type, _exc, _tb) -> None:
|
||||
await self.close()
|
||||
|
||||
async def _ensure_initialized(self) -> None:
|
||||
if self._initialized:
|
||||
return
|
||||
async with self._init_lock:
|
||||
if self._initialized:
|
||||
return
|
||||
try:
|
||||
await self._client.start()
|
||||
payload = await self._client.initialize()
|
||||
self._init = validate_initialize_metadata(payload)
|
||||
self._initialized = True
|
||||
except Exception:
|
||||
await self._client.close()
|
||||
self._init = None
|
||||
self._initialized = False
|
||||
raise
|
||||
|
||||
@property
|
||||
def metadata(self) -> InitializeResponse:
|
||||
if self._init is None:
|
||||
raise RuntimeError(
|
||||
"AsyncCodex is not initialized yet. Prefer `async with AsyncCodex()`; "
|
||||
"initialization also happens on first awaited API use."
|
||||
)
|
||||
return self._init
|
||||
|
||||
async def close(self) -> None:
|
||||
await self._client.close()
|
||||
self._init = None
|
||||
self._initialized = False
|
||||
|
||||
async def login_api_key(self, api_key: str) -> None:
|
||||
"""Authenticate Codex with an API key."""
|
||||
await self._ensure_initialized()
|
||||
await self._client.account_login_start(
|
||||
LoginAccountParams(
|
||||
root=ApiKeyLoginAccountParams(
|
||||
api_key=api_key,
|
||||
type="apiKey",
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
async def login_chatgpt(self) -> AsyncChatgptLoginHandle:
|
||||
"""Start browser-based ChatGPT login and return its live handle."""
|
||||
await self._ensure_initialized()
|
||||
return await async_start_chatgpt_login(self)
|
||||
|
||||
async def login_chatgpt_device_code(self) -> AsyncDeviceCodeLoginHandle:
|
||||
"""Start device-code ChatGPT login and return its live handle."""
|
||||
await self._ensure_initialized()
|
||||
return await async_start_device_code_login(self)
|
||||
|
||||
async def account(self, *, refresh_token: bool = False) -> GetAccountResponse:
|
||||
"""Read the current Codex account state."""
|
||||
await self._ensure_initialized()
|
||||
return await self._client.account_read(GetAccountParams(refresh_token=refresh_token))
|
||||
|
||||
async def logout(self) -> None:
|
||||
"""Clear the current Codex account session."""
|
||||
await self._ensure_initialized()
|
||||
await self._client.account_logout()
|
||||
|
||||
# BEGIN GENERATED: AsyncCodex.flat_methods
|
||||
async def thread_start(
|
||||
self,
|
||||
*,
|
||||
approval_mode: ApprovalMode = ApprovalMode.auto_review,
|
||||
base_instructions: str | None = None,
|
||||
config: JsonObject | None = None,
|
||||
cwd: str | None = None,
|
||||
developer_instructions: str | None = None,
|
||||
ephemeral: bool | None = None,
|
||||
model: str | None = None,
|
||||
model_provider: str | None = None,
|
||||
personality: Personality | None = None,
|
||||
sandbox: Sandbox | None = None,
|
||||
service_name: str | None = None,
|
||||
service_tier: str | None = None,
|
||||
session_start_source: ThreadStartSource | None = None,
|
||||
thread_source: ThreadSource | None = None,
|
||||
) -> AsyncThread:
|
||||
"""Create a new Codex conversation thread."""
|
||||
await self._ensure_initialized()
|
||||
approval_policy, approvals_reviewer = _approval_mode_settings(approval_mode)
|
||||
params = ThreadStartParams(
|
||||
approval_policy=approval_policy,
|
||||
approvals_reviewer=approvals_reviewer,
|
||||
base_instructions=base_instructions,
|
||||
config=config,
|
||||
cwd=cwd,
|
||||
developer_instructions=developer_instructions,
|
||||
ephemeral=ephemeral,
|
||||
model=model,
|
||||
model_provider=model_provider,
|
||||
personality=personality,
|
||||
sandbox=_sandbox_mode(sandbox),
|
||||
service_name=service_name,
|
||||
service_tier=service_tier,
|
||||
session_start_source=session_start_source,
|
||||
thread_source=thread_source,
|
||||
)
|
||||
started = await self._client.thread_start(params)
|
||||
return AsyncThread(self, started.thread.id)
|
||||
|
||||
async def thread_list(
|
||||
self,
|
||||
*,
|
||||
archived: bool | None = None,
|
||||
cursor: str | None = None,
|
||||
cwd: ThreadListCwdFilter | None = None,
|
||||
limit: int | None = None,
|
||||
model_providers: list[str] | None = None,
|
||||
search_term: str | None = None,
|
||||
section_id: str | None = None,
|
||||
sort_direction: SortDirection | None = None,
|
||||
sort_key: ThreadSortKey | None = None,
|
||||
source_kinds: list[ThreadSourceKind] | None = None,
|
||||
use_state_db_only: bool | None = None,
|
||||
) -> ThreadListResponse:
|
||||
"""List saved conversation threads."""
|
||||
await self._ensure_initialized()
|
||||
params = ThreadListParams(
|
||||
archived=archived,
|
||||
cursor=cursor,
|
||||
cwd=cwd,
|
||||
limit=limit,
|
||||
model_providers=model_providers,
|
||||
search_term=search_term,
|
||||
section_id=section_id,
|
||||
sort_direction=sort_direction,
|
||||
sort_key=sort_key,
|
||||
source_kinds=source_kinds,
|
||||
use_state_db_only=use_state_db_only,
|
||||
)
|
||||
return await self._client.thread_list(params)
|
||||
|
||||
async def thread_resume(
|
||||
self,
|
||||
thread_id: str,
|
||||
*,
|
||||
approval_mode: ApprovalMode | None = None,
|
||||
base_instructions: str | None = None,
|
||||
config: JsonObject | None = None,
|
||||
cwd: str | None = None,
|
||||
developer_instructions: str | None = None,
|
||||
include_turns: bool | None = None,
|
||||
model: str | None = None,
|
||||
model_provider: str | None = None,
|
||||
personality: Personality | None = None,
|
||||
sandbox: Sandbox | None = None,
|
||||
service_tier: str | None = None,
|
||||
) -> AsyncThread:
|
||||
"""Resume an existing conversation thread by ID.
|
||||
|
||||
include_turns controls the runtime response history, not model context.
|
||||
Omit it to preserve the runtime default. Use thread.read() for history.
|
||||
"""
|
||||
await self._ensure_initialized()
|
||||
approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode)
|
||||
params = ThreadResumeParams(
|
||||
thread_id=thread_id,
|
||||
approval_policy=approval_policy,
|
||||
approvals_reviewer=approvals_reviewer,
|
||||
base_instructions=base_instructions,
|
||||
config=config,
|
||||
cwd=cwd,
|
||||
developer_instructions=developer_instructions,
|
||||
exclude_turns=None if include_turns is None else not include_turns,
|
||||
model=model,
|
||||
model_provider=model_provider,
|
||||
personality=personality,
|
||||
sandbox=_sandbox_mode(sandbox),
|
||||
service_tier=service_tier,
|
||||
)
|
||||
resumed = await self._client.thread_resume(thread_id, params)
|
||||
return AsyncThread(self, resumed.thread.id)
|
||||
|
||||
async def thread_fork(
|
||||
self,
|
||||
thread_id: str,
|
||||
*,
|
||||
approval_mode: ApprovalMode | None = None,
|
||||
base_instructions: str | None = None,
|
||||
config: JsonObject | None = None,
|
||||
cwd: str | None = None,
|
||||
developer_instructions: str | None = None,
|
||||
ephemeral: bool | None = None,
|
||||
include_turns: bool | None = None,
|
||||
model: str | None = None,
|
||||
model_provider: str | None = None,
|
||||
sandbox: Sandbox | None = None,
|
||||
service_tier: str | None = None,
|
||||
thread_source: ThreadSource | None = None,
|
||||
) -> AsyncThread:
|
||||
"""Create a new thread from an existing thread.
|
||||
|
||||
include_turns controls the runtime response history, not model context.
|
||||
Omit it to preserve the runtime default. Use thread.read() for history.
|
||||
"""
|
||||
await self._ensure_initialized()
|
||||
approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode)
|
||||
params = ThreadForkParams(
|
||||
thread_id=thread_id,
|
||||
approval_policy=approval_policy,
|
||||
approvals_reviewer=approvals_reviewer,
|
||||
base_instructions=base_instructions,
|
||||
config=config,
|
||||
cwd=cwd,
|
||||
developer_instructions=developer_instructions,
|
||||
ephemeral=ephemeral,
|
||||
exclude_turns=None if include_turns is None else not include_turns,
|
||||
model=model,
|
||||
model_provider=model_provider,
|
||||
sandbox=_sandbox_mode(sandbox),
|
||||
service_tier=service_tier,
|
||||
thread_source=thread_source,
|
||||
)
|
||||
forked = await self._client.thread_fork(thread_id, params)
|
||||
return AsyncThread(self, forked.thread.id)
|
||||
|
||||
async def thread_archive(self, thread_id: str) -> ThreadArchiveResponse:
|
||||
"""Archive a stored conversation thread."""
|
||||
await self._ensure_initialized()
|
||||
return await self._client.thread_archive(thread_id)
|
||||
|
||||
async def thread_unarchive(self, thread_id: str) -> AsyncThread:
|
||||
"""Restore an archived conversation thread."""
|
||||
await self._ensure_initialized()
|
||||
unarchived = await self._client.thread_unarchive(thread_id)
|
||||
return AsyncThread(self, unarchived.thread.id)
|
||||
|
||||
# END GENERATED: AsyncCodex.flat_methods
|
||||
|
||||
async def models(self, *, include_hidden: bool = False) -> ModelListResponse:
|
||||
"""List available models reported by Codex.
|
||||
|
||||
The deprecated ``Model.supports_personality`` field is always ``False``
|
||||
on the current app-server.
|
||||
"""
|
||||
await self._ensure_initialized()
|
||||
return await self._client.model_list(include_hidden=include_hidden)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Thread:
|
||||
"""Synchronous conversation thread used to run one or more turns."""
|
||||
|
||||
_client: CodexClient
|
||||
id: str
|
||||
|
||||
# BEGIN GENERATED: Thread.flat_methods
|
||||
def run(
|
||||
self,
|
||||
input: RunInput,
|
||||
*,
|
||||
approval_mode: ApprovalMode | None = None,
|
||||
cwd: str | None = None,
|
||||
effort: ReasoningEffort | None = None,
|
||||
model: str | None = None,
|
||||
output_schema: JsonObject | None = None,
|
||||
personality: Personality | None = None,
|
||||
sandbox: Sandbox | None = None,
|
||||
service_tier: str | None = None,
|
||||
source: str | None = None,
|
||||
summary: ReasoningSummary | None = None,
|
||||
turn_service_tier: str | None = None,
|
||||
) -> TurnResult:
|
||||
"""Run a complete turn and collect its final result.
|
||||
|
||||
Accepts the same input and options as turn(), including ExternalMessage
|
||||
for untrusted external content with tool-level authority.
|
||||
"""
|
||||
turn = self.turn(
|
||||
input,
|
||||
approval_mode=approval_mode,
|
||||
cwd=cwd,
|
||||
effort=effort,
|
||||
model=model,
|
||||
output_schema=output_schema,
|
||||
personality=personality,
|
||||
sandbox=sandbox,
|
||||
service_tier=service_tier,
|
||||
source=source,
|
||||
summary=summary,
|
||||
turn_service_tier=turn_service_tier,
|
||||
)
|
||||
return turn.run()
|
||||
|
||||
def turn(
|
||||
self,
|
||||
input: RunInput,
|
||||
*,
|
||||
approval_mode: ApprovalMode | None = None,
|
||||
cwd: str | None = None,
|
||||
effort: ReasoningEffort | None = None,
|
||||
model: str | None = None,
|
||||
output_schema: JsonObject | None = None,
|
||||
personality: Personality | None = None,
|
||||
sandbox: Sandbox | None = None,
|
||||
service_tier: str | None = None,
|
||||
source: str | None = None,
|
||||
summary: ReasoningSummary | None = None,
|
||||
turn_service_tier: str | None = None,
|
||||
) -> TurnHandle:
|
||||
"""Start a turn or join an active regular turn and return its handle.
|
||||
|
||||
ExternalMessage supplies untrusted content with tool-level authority;
|
||||
it does not establish user authorization or approval.
|
||||
turn_service_tier applies only to this new turn; service_tier updates
|
||||
the thread default. source labels what initiated a new turn and grants
|
||||
no authority. Both turn_service_tier and source are ignored when joining.
|
||||
"""
|
||||
wire_input, tool_output = _to_wire_turn_input(input)
|
||||
approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode)
|
||||
params = TurnStartParams(
|
||||
thread_id=self.id,
|
||||
input=wire_input,
|
||||
tool_output=tool_output,
|
||||
approval_policy=approval_policy,
|
||||
approvals_reviewer=approvals_reviewer,
|
||||
cwd=cwd,
|
||||
effort=effort,
|
||||
model=model,
|
||||
output_schema=output_schema,
|
||||
personality=personality,
|
||||
sandbox_policy=_sandbox_policy(sandbox),
|
||||
service_tier=service_tier,
|
||||
turn_trigger=source,
|
||||
summary=summary,
|
||||
service_tier_for_turn=turn_service_tier,
|
||||
)
|
||||
turn, subscription = self._client._start_turn(
|
||||
self.id, wire_input, params=params, for_handle=True
|
||||
)
|
||||
return TurnHandle(self._client, self.id, turn.turn.id, _subscription=subscription)
|
||||
|
||||
# END GENERATED: Thread.flat_methods
|
||||
|
||||
def read(self, *, include_turns: bool = False) -> ThreadReadResponse:
|
||||
"""Read this thread, optionally including its turn history."""
|
||||
return self._client.thread_read(self.id, include_turns=include_turns)
|
||||
|
||||
def set_name(self, name: str) -> ThreadSetNameResponse:
|
||||
return self._client.thread_set_name(self.id, name)
|
||||
|
||||
def compact(self) -> ThreadCompactStartResponse:
|
||||
return self._client.thread_compact(self.id)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AsyncThread:
|
||||
"""Asynchronous conversation thread used to run one or more turns."""
|
||||
|
||||
_codex: AsyncCodex
|
||||
id: str
|
||||
|
||||
# BEGIN GENERATED: AsyncThread.flat_methods
|
||||
async def run(
|
||||
self,
|
||||
input: RunInput,
|
||||
*,
|
||||
approval_mode: ApprovalMode | None = None,
|
||||
cwd: str | None = None,
|
||||
effort: ReasoningEffort | None = None,
|
||||
model: str | None = None,
|
||||
output_schema: JsonObject | None = None,
|
||||
personality: Personality | None = None,
|
||||
sandbox: Sandbox | None = None,
|
||||
service_tier: str | None = None,
|
||||
source: str | None = None,
|
||||
summary: ReasoningSummary | None = None,
|
||||
turn_service_tier: str | None = None,
|
||||
) -> TurnResult:
|
||||
"""Run a complete turn and collect its final result.
|
||||
|
||||
Accepts the same input and options as turn(), including ExternalMessage
|
||||
for untrusted external content with tool-level authority.
|
||||
"""
|
||||
turn = await self.turn(
|
||||
input,
|
||||
approval_mode=approval_mode,
|
||||
cwd=cwd,
|
||||
effort=effort,
|
||||
model=model,
|
||||
output_schema=output_schema,
|
||||
personality=personality,
|
||||
sandbox=sandbox,
|
||||
service_tier=service_tier,
|
||||
source=source,
|
||||
summary=summary,
|
||||
turn_service_tier=turn_service_tier,
|
||||
)
|
||||
return await turn.run()
|
||||
|
||||
async def turn(
|
||||
self,
|
||||
input: RunInput,
|
||||
*,
|
||||
approval_mode: ApprovalMode | None = None,
|
||||
cwd: str | None = None,
|
||||
effort: ReasoningEffort | None = None,
|
||||
model: str | None = None,
|
||||
output_schema: JsonObject | None = None,
|
||||
personality: Personality | None = None,
|
||||
sandbox: Sandbox | None = None,
|
||||
service_tier: str | None = None,
|
||||
source: str | None = None,
|
||||
summary: ReasoningSummary | None = None,
|
||||
turn_service_tier: str | None = None,
|
||||
) -> AsyncTurnHandle:
|
||||
"""Start a turn or join an active regular turn and return its handle.
|
||||
|
||||
ExternalMessage supplies untrusted content with tool-level authority;
|
||||
it does not establish user authorization or approval.
|
||||
turn_service_tier applies only to this new turn; service_tier updates
|
||||
the thread default. source labels what initiated a new turn and grants
|
||||
no authority. Both turn_service_tier and source are ignored when joining.
|
||||
"""
|
||||
wire_input, tool_output = _to_wire_turn_input(input)
|
||||
await self._codex._ensure_initialized()
|
||||
approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode)
|
||||
params = TurnStartParams(
|
||||
thread_id=self.id,
|
||||
input=wire_input,
|
||||
tool_output=tool_output,
|
||||
approval_policy=approval_policy,
|
||||
approvals_reviewer=approvals_reviewer,
|
||||
cwd=cwd,
|
||||
effort=effort,
|
||||
model=model,
|
||||
output_schema=output_schema,
|
||||
personality=personality,
|
||||
sandbox_policy=_sandbox_policy(sandbox),
|
||||
service_tier=service_tier,
|
||||
turn_trigger=source,
|
||||
summary=summary,
|
||||
service_tier_for_turn=turn_service_tier,
|
||||
)
|
||||
turn, subscription = await self._codex._client._start_turn(
|
||||
self.id, wire_input, params=params, for_handle=True
|
||||
)
|
||||
return AsyncTurnHandle(self._codex, self.id, turn.turn.id, _subscription=subscription)
|
||||
|
||||
# END GENERATED: AsyncThread.flat_methods
|
||||
|
||||
async def read(self, *, include_turns: bool = False) -> ThreadReadResponse:
|
||||
"""Read this thread, optionally including its turn history."""
|
||||
await self._codex._ensure_initialized()
|
||||
return await self._codex._client.thread_read(self.id, include_turns=include_turns)
|
||||
|
||||
async def set_name(self, name: str) -> ThreadSetNameResponse:
|
||||
await self._codex._ensure_initialized()
|
||||
return await self._codex._client.thread_set_name(self.id, name)
|
||||
|
||||
async def compact(self) -> ThreadCompactStartResponse:
|
||||
await self._codex._ensure_initialized()
|
||||
return await self._codex._client.thread_compact(self.id)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class TurnHandle:
|
||||
"""Control and consume a synchronous turn after it has started."""
|
||||
|
||||
_client: CodexClient
|
||||
thread_id: str
|
||||
id: str
|
||||
_subscription: _TurnSubscription = field(init=False, repr=False, compare=False)
|
||||
|
||||
def __init__(
|
||||
self, _client: CodexClient, thread_id: str, id: str, *, _subscription=None
|
||||
) -> None:
|
||||
self._client, self.thread_id, self.id = _client, thread_id, id
|
||||
if _subscription is None:
|
||||
self.__post_init__()
|
||||
else:
|
||||
self._subscription = _subscription
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self._subscription = self._client._subscribe_turn_notifications(self.id)
|
||||
|
||||
def steer(self, input: Input | str) -> TurnSteerResponse:
|
||||
"""Send additional user input to this active turn."""
|
||||
return self._client.turn_steer(
|
||||
self.thread_id,
|
||||
self.id,
|
||||
_to_wire_input(_normalize_run_input(input)),
|
||||
)
|
||||
|
||||
def interrupt(self) -> TurnInterruptResponse:
|
||||
"""Request interruption of this active turn."""
|
||||
return self._client.turn_interrupt(self.thread_id, self.id)
|
||||
|
||||
def stream(self) -> Iterator[Notification]:
|
||||
"""Yield only notifications routed to this turn handle."""
|
||||
try:
|
||||
while True:
|
||||
event = self._subscription.next()
|
||||
yield event
|
||||
if (
|
||||
event.method == "turn/completed"
|
||||
and isinstance(event.payload, TurnCompletedNotification)
|
||||
and event.payload.turn.id == self.id
|
||||
):
|
||||
break
|
||||
finally:
|
||||
self._subscription.close()
|
||||
|
||||
def run(self) -> TurnResult:
|
||||
"""Consume the turn stream and return its completed result."""
|
||||
stream = self.stream()
|
||||
try:
|
||||
return _collect_turn_result(stream, turn_id=self.id)
|
||||
finally:
|
||||
stream.close()
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AsyncTurnHandle:
|
||||
"""Control and consume an asynchronous turn after it has started."""
|
||||
|
||||
_codex: AsyncCodex
|
||||
thread_id: str
|
||||
id: str
|
||||
_subscription: _TurnSubscription = field(init=False, repr=False, compare=False)
|
||||
|
||||
def __init__(self, _codex: AsyncCodex, thread_id: str, id: str, *, _subscription=None) -> None:
|
||||
self._codex, self.thread_id, self.id = _codex, thread_id, id
|
||||
if _subscription is None:
|
||||
self.__post_init__()
|
||||
else:
|
||||
self._subscription = _subscription
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self._subscription = self._codex._client._subscribe_turn_notifications(self.id)
|
||||
|
||||
async def steer(self, input: Input | str) -> TurnSteerResponse:
|
||||
"""Send additional user input to this active turn."""
|
||||
await self._codex._ensure_initialized()
|
||||
return await self._codex._client.turn_steer(
|
||||
self.thread_id,
|
||||
self.id,
|
||||
_to_wire_input(_normalize_run_input(input)),
|
||||
)
|
||||
|
||||
async def interrupt(self) -> TurnInterruptResponse:
|
||||
"""Request interruption of this active turn."""
|
||||
await self._codex._ensure_initialized()
|
||||
return await self._codex._client.turn_interrupt(self.thread_id, self.id)
|
||||
|
||||
async def stream(self) -> AsyncIterator[Notification]:
|
||||
"""Yield only notifications routed to this async turn handle."""
|
||||
await self._codex._ensure_initialized()
|
||||
try:
|
||||
while True:
|
||||
event = await asyncio.to_thread(self._subscription.next)
|
||||
yield event
|
||||
if (
|
||||
event.method == "turn/completed"
|
||||
and isinstance(event.payload, TurnCompletedNotification)
|
||||
and event.payload.turn.id == self.id
|
||||
):
|
||||
break
|
||||
finally:
|
||||
self._subscription.close()
|
||||
|
||||
async def run(self) -> TurnResult:
|
||||
"""Consume the turn stream and return its completed result."""
|
||||
stream = self.stream()
|
||||
try:
|
||||
return await _collect_async_turn_result(stream, turn_id=self.id)
|
||||
finally:
|
||||
await stream.aclose()
|
||||
413
sdk/python/src/openai_codex/async_client.py
Normal file
413
sdk/python/src/openai_codex/async_client.py
Normal file
@@ -0,0 +1,413 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
from collections.abc import Iterator
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from contextvars import copy_context
|
||||
from typing import AsyncIterator, Callable, ParamSpec, TypeVar
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ._goal import _GoalOperationState
|
||||
from ._message_router import _TurnSubscription
|
||||
from .client import CodexClient, CodexConfig
|
||||
from .generated.v2_all import (
|
||||
AccountLoginCompletedNotification,
|
||||
AgentMessageDeltaNotification,
|
||||
CancelLoginAccountResponse,
|
||||
GetAccountParams as V2GetAccountParams,
|
||||
GetAccountResponse,
|
||||
LoginAccountParams as V2LoginAccountParams,
|
||||
LoginAccountResponse,
|
||||
LogoutAccountResponse,
|
||||
ModelListResponse,
|
||||
ThreadArchiveResponse,
|
||||
ThreadCompactStartResponse,
|
||||
ThreadForkParams as V2ThreadForkParams,
|
||||
ThreadForkResponse,
|
||||
ThreadGoalClearResponse,
|
||||
ThreadGoalSetResponse,
|
||||
ThreadGoalStatus,
|
||||
ThreadListParams as V2ThreadListParams,
|
||||
ThreadListResponse,
|
||||
ThreadReadResponse,
|
||||
ThreadResumeParams as V2ThreadResumeParams,
|
||||
ThreadResumeResponse,
|
||||
ThreadSetNameResponse,
|
||||
ThreadStartParams as V2ThreadStartParams,
|
||||
ThreadStartResponse,
|
||||
ThreadUnarchiveResponse,
|
||||
TurnCompletedNotification,
|
||||
TurnInterruptResponse,
|
||||
TurnStartParams as V2TurnStartParams,
|
||||
TurnStartResponse,
|
||||
TurnSteerResponse,
|
||||
)
|
||||
from .models import InitializeResponse, JsonObject, Notification
|
||||
|
||||
ModelT = TypeVar("ModelT", bound=BaseModel)
|
||||
ParamsT = ParamSpec("ParamsT")
|
||||
ReturnT = TypeVar("ReturnT")
|
||||
|
||||
# Bound workers while allowing cancellation cleanup to outlive an asyncio waiter.
|
||||
_TURN_START_EXECUTOR = ThreadPoolExecutor(thread_name_prefix="codex-turn-start")
|
||||
|
||||
|
||||
class AsyncCodexClient:
|
||||
"""Async wrapper around CodexClient using thread offloading."""
|
||||
|
||||
def __init__(self, config: CodexConfig | None = None) -> None:
|
||||
"""Create the wrapped sync client that owns the transport process."""
|
||||
self._sync = CodexClient(config=config)
|
||||
|
||||
async def __aenter__(self) -> "AsyncCodexClient":
|
||||
"""Start the Codex process when entering an async context."""
|
||||
await self.start()
|
||||
return self
|
||||
|
||||
async def __aexit__(self, _exc_type, _exc, _tb) -> None:
|
||||
"""Close the Codex process when leaving an async context."""
|
||||
await self.close()
|
||||
|
||||
async def _call_sync(
|
||||
self,
|
||||
fn: Callable[ParamsT, ReturnT],
|
||||
/,
|
||||
*args: ParamsT.args,
|
||||
**kwargs: ParamsT.kwargs,
|
||||
) -> ReturnT:
|
||||
"""Run a blocking sync-client operation without blocking the event loop."""
|
||||
return await asyncio.to_thread(fn, *args, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def _next_from_iterator(
|
||||
iterator: Iterator[AgentMessageDeltaNotification],
|
||||
) -> tuple[bool, AgentMessageDeltaNotification | None]:
|
||||
"""Convert StopIteration into a value that can cross asyncio.to_thread."""
|
||||
try:
|
||||
return True, next(iterator)
|
||||
except StopIteration:
|
||||
return False, None
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Start the wrapped sync client in a worker thread."""
|
||||
await self._call_sync(self._sync.start)
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Close the wrapped sync client in a worker thread."""
|
||||
await self._call_sync(self._sync.close)
|
||||
|
||||
async def initialize(self) -> InitializeResponse:
|
||||
"""Initialize the Codex session."""
|
||||
return await self._call_sync(self._sync.initialize)
|
||||
|
||||
def _subscribe_turn_notifications(self, turn_id: str) -> _TurnSubscription:
|
||||
return self._sync._subscribe_turn_notifications(turn_id)
|
||||
|
||||
def register_turn_notifications(self, turn_id: str) -> None:
|
||||
"""Register a turn notification queue on the wrapped sync client."""
|
||||
self._sync.register_turn_notifications(turn_id)
|
||||
|
||||
def register_login_notifications(self, login_id: str) -> None:
|
||||
"""Register a login notification queue on the wrapped sync client."""
|
||||
self._sync.register_login_notifications(login_id)
|
||||
|
||||
def unregister_login_notifications(self, login_id: str) -> None:
|
||||
"""Unregister a login notification queue on the wrapped sync client."""
|
||||
self._sync.unregister_login_notifications(login_id)
|
||||
|
||||
def unregister_turn_notifications(self, turn_id: str) -> None:
|
||||
"""Unregister a turn notification queue on the wrapped sync client."""
|
||||
self._sync.unregister_turn_notifications(turn_id)
|
||||
|
||||
def register_goal_operation(self, thread_id: str) -> _GoalOperationState:
|
||||
"""Register a logical goal route on the wrapped sync client."""
|
||||
return self._sync.register_goal_operation(thread_id)
|
||||
|
||||
def unregister_goal_operation(self, state: _GoalOperationState) -> None:
|
||||
"""Release one logical goal route."""
|
||||
self._sync.unregister_goal_operation(state)
|
||||
|
||||
async def request(
|
||||
self,
|
||||
method: str,
|
||||
params: JsonObject | None,
|
||||
*,
|
||||
response_model: type[ModelT],
|
||||
) -> ModelT:
|
||||
"""Send a typed JSON-RPC request through the wrapped sync client."""
|
||||
return await self._call_sync(
|
||||
self._sync.request,
|
||||
method,
|
||||
params,
|
||||
response_model=response_model,
|
||||
)
|
||||
|
||||
async def account_login_start(
|
||||
self,
|
||||
params: V2LoginAccountParams | JsonObject,
|
||||
) -> LoginAccountResponse:
|
||||
"""Start one account login attempt through the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.account_login_start, params)
|
||||
|
||||
async def account_login_cancel(self, login_id: str) -> CancelLoginAccountResponse:
|
||||
"""Cancel one active account login attempt through the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.account_login_cancel, login_id)
|
||||
|
||||
async def account_read(
|
||||
self,
|
||||
params: V2GetAccountParams | JsonObject | None = None,
|
||||
) -> GetAccountResponse:
|
||||
"""Read current account state through the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.account_read, params)
|
||||
|
||||
async def account_logout(self) -> LogoutAccountResponse:
|
||||
"""Clear the active account session through the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.account_logout)
|
||||
|
||||
async def thread_start(
|
||||
self, params: V2ThreadStartParams | JsonObject | None = None
|
||||
) -> ThreadStartResponse:
|
||||
"""Start a thread using the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.thread_start, params)
|
||||
|
||||
async def thread_resume(
|
||||
self,
|
||||
thread_id: str,
|
||||
params: V2ThreadResumeParams | JsonObject | None = None,
|
||||
) -> ThreadResumeResponse:
|
||||
"""Resume a thread using the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.thread_resume, thread_id, params)
|
||||
|
||||
async def thread_list(
|
||||
self, params: V2ThreadListParams | JsonObject | None = None
|
||||
) -> ThreadListResponse:
|
||||
"""List threads using the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.thread_list, params)
|
||||
|
||||
async def thread_read(self, thread_id: str, include_turns: bool = False) -> ThreadReadResponse:
|
||||
"""Read a thread using the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.thread_read, thread_id, include_turns)
|
||||
|
||||
async def thread_fork(
|
||||
self,
|
||||
thread_id: str,
|
||||
params: V2ThreadForkParams | JsonObject | None = None,
|
||||
) -> ThreadForkResponse:
|
||||
"""Fork a thread using the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.thread_fork, thread_id, params)
|
||||
|
||||
async def thread_archive(self, thread_id: str) -> ThreadArchiveResponse:
|
||||
"""Archive a thread using the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.thread_archive, thread_id)
|
||||
|
||||
async def thread_unarchive(self, thread_id: str) -> ThreadUnarchiveResponse:
|
||||
"""Unarchive a thread using the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.thread_unarchive, thread_id)
|
||||
|
||||
async def thread_set_name(self, thread_id: str, name: str) -> ThreadSetNameResponse:
|
||||
"""Rename a thread using the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.thread_set_name, thread_id, name)
|
||||
|
||||
async def thread_compact(self, thread_id: str) -> ThreadCompactStartResponse:
|
||||
"""Start thread compaction using the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.thread_compact, thread_id)
|
||||
|
||||
async def thread_goal_clear(self, thread_id: str) -> ThreadGoalClearResponse:
|
||||
"""Clear the persisted goal through the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.thread_goal_clear, thread_id)
|
||||
|
||||
async def thread_goal_set(
|
||||
self,
|
||||
thread_id: str,
|
||||
*,
|
||||
objective: str | None = None,
|
||||
status: ThreadGoalStatus | None = None,
|
||||
) -> ThreadGoalSetResponse:
|
||||
"""Create or update a persisted goal through the wrapped sync client."""
|
||||
return await self._call_sync(
|
||||
self._sync.thread_goal_set,
|
||||
thread_id,
|
||||
objective=objective,
|
||||
status=status,
|
||||
)
|
||||
|
||||
async def pause_goal(self, thread_id: str) -> ThreadGoalSetResponse:
|
||||
"""Pause the active goal through the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.pause_goal, thread_id)
|
||||
|
||||
async def cancel_goal_operation(self, state: _GoalOperationState) -> None:
|
||||
"""Stop continuation work after a logical goal operation is cancelled."""
|
||||
await self._call_sync(self._sync.cancel_goal_operation, state)
|
||||
|
||||
async def start_goal_operation(
|
||||
self,
|
||||
thread_id: str,
|
||||
objective: str,
|
||||
) -> tuple[_GoalOperationState, str]:
|
||||
"""Start a logical goal through the wrapped sync client."""
|
||||
operation: Future[tuple[_GoalOperationState, str]] = Future()
|
||||
|
||||
def start_operation() -> None:
|
||||
try:
|
||||
operation.set_result(self._sync.start_goal_operation(thread_id, objective))
|
||||
except BaseException as exc:
|
||||
operation.set_exception(exc)
|
||||
|
||||
worker = threading.Thread(
|
||||
target=start_operation,
|
||||
name="codex-goal-start",
|
||||
daemon=True,
|
||||
)
|
||||
worker.start()
|
||||
try:
|
||||
return await asyncio.shield(asyncio.wrap_future(operation))
|
||||
except asyncio.CancelledError:
|
||||
|
||||
def cleanup_cancelled_start(
|
||||
completed: Future[tuple[_GoalOperationState, str]],
|
||||
) -> None:
|
||||
try:
|
||||
state, _ = completed.result()
|
||||
except BaseException:
|
||||
return
|
||||
|
||||
def stop_cancelled_goal() -> None:
|
||||
try:
|
||||
self._sync.cancel_goal_operation(state)
|
||||
finally:
|
||||
state.finish()
|
||||
self._sync.unregister_goal_operation(state)
|
||||
|
||||
threading.Thread(
|
||||
target=stop_cancelled_goal,
|
||||
name="codex-goal-start-cleanup",
|
||||
daemon=True,
|
||||
).start()
|
||||
|
||||
operation.add_done_callback(cleanup_cancelled_start)
|
||||
raise
|
||||
|
||||
async def turn_start(
|
||||
self,
|
||||
thread_id: str,
|
||||
input_items: list[JsonObject] | JsonObject | str,
|
||||
params: V2TurnStartParams | JsonObject | None = None,
|
||||
) -> TurnStartResponse:
|
||||
"""Start a turn, releasing an unclaimed result if the caller is cancelled."""
|
||||
return (await self._start_turn(thread_id, input_items, params, for_handle=False))[0]
|
||||
|
||||
async def _start_turn(
|
||||
self,
|
||||
thread_id: str,
|
||||
input_items: list[JsonObject] | JsonObject | str,
|
||||
params: V2TurnStartParams | JsonObject | None,
|
||||
for_handle: bool,
|
||||
) -> tuple[TurnStartResponse, _TurnSubscription | None]:
|
||||
operation = _TURN_START_EXECUTOR.submit(
|
||||
copy_context().run, self._sync._start_turn, thread_id, input_items, params, for_handle
|
||||
)
|
||||
try:
|
||||
return await asyncio.wrap_future(operation)
|
||||
except asyncio.CancelledError:
|
||||
|
||||
def discard_cancelled_result(
|
||||
completed: Future[tuple[TurnStartResponse, _TurnSubscription | None]],
|
||||
) -> None:
|
||||
try:
|
||||
_, subscription = completed.result()
|
||||
except BaseException:
|
||||
return
|
||||
if subscription is not None:
|
||||
subscription.close()
|
||||
|
||||
operation.add_done_callback(discard_cancelled_result)
|
||||
raise
|
||||
|
||||
async def turn_interrupt(self, thread_id: str, turn_id: str) -> TurnInterruptResponse:
|
||||
"""Interrupt a turn using the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.turn_interrupt, thread_id, turn_id)
|
||||
|
||||
async def turn_steer(
|
||||
self,
|
||||
thread_id: str,
|
||||
expected_turn_id: str,
|
||||
input_items: list[JsonObject] | JsonObject | str,
|
||||
) -> TurnSteerResponse:
|
||||
"""Send steering input to a turn using the wrapped sync client."""
|
||||
return await self._call_sync(
|
||||
self._sync.turn_steer,
|
||||
thread_id,
|
||||
expected_turn_id,
|
||||
input_items,
|
||||
)
|
||||
|
||||
async def model_list(self, include_hidden: bool = False) -> ModelListResponse:
|
||||
"""List models using the wrapped sync client."""
|
||||
return await self._call_sync(self._sync.model_list, include_hidden)
|
||||
|
||||
async def request_with_retry_on_overload(
|
||||
self,
|
||||
method: str,
|
||||
params: JsonObject | None,
|
||||
*,
|
||||
response_model: type[ModelT],
|
||||
max_attempts: int = 3,
|
||||
initial_delay_s: float = 0.25,
|
||||
max_delay_s: float = 2.0,
|
||||
) -> ModelT:
|
||||
"""Send a typed request with the sync client's overload retry policy."""
|
||||
return await self._call_sync(
|
||||
self._sync.request_with_retry_on_overload,
|
||||
method,
|
||||
params,
|
||||
response_model=response_model,
|
||||
max_attempts=max_attempts,
|
||||
initial_delay_s=initial_delay_s,
|
||||
max_delay_s=max_delay_s,
|
||||
)
|
||||
|
||||
async def next_notification(self) -> Notification:
|
||||
"""Wait for the next global notification without blocking the event loop."""
|
||||
return await self._call_sync(self._sync.next_notification)
|
||||
|
||||
async def next_login_notification(self, login_id: str) -> Notification:
|
||||
"""Wait for the next notification routed to one login attempt."""
|
||||
return await self._call_sync(self._sync.next_login_notification, login_id)
|
||||
|
||||
async def next_turn_notification(self, turn_id: str) -> Notification:
|
||||
"""Wait for the next notification routed to one turn."""
|
||||
return await self._call_sync(self._sync.next_turn_notification, turn_id)
|
||||
|
||||
async def next_goal_notification(self, state: _GoalOperationState) -> Notification:
|
||||
"""Wait for the next notification in a logical goal turn."""
|
||||
return await self._call_sync(self._sync.next_goal_notification, state)
|
||||
|
||||
async def wait_for_login_completed(
|
||||
self,
|
||||
login_id: str,
|
||||
) -> AccountLoginCompletedNotification:
|
||||
"""Wait for the completion notification routed to one login attempt."""
|
||||
return await self._call_sync(self._sync.wait_for_login_completed, login_id)
|
||||
|
||||
async def wait_for_turn_completed(self, turn_id: str) -> TurnCompletedNotification:
|
||||
"""Wait for the completion notification routed to one turn."""
|
||||
return await self._call_sync(self._sync.wait_for_turn_completed, turn_id)
|
||||
|
||||
async def stream_text(
|
||||
self,
|
||||
thread_id: str,
|
||||
text: str,
|
||||
params: V2TurnStartParams | JsonObject | None = None,
|
||||
) -> AsyncIterator[AgentMessageDeltaNotification]:
|
||||
"""Stream text deltas from one turn without monopolizing the event loop."""
|
||||
iterator = self._sync.stream_text(thread_id, text, params)
|
||||
while True:
|
||||
has_value, chunk = await asyncio.to_thread(
|
||||
self._next_from_iterator,
|
||||
iterator,
|
||||
)
|
||||
if not has_value:
|
||||
break
|
||||
yield chunk
|
||||
924
sdk/python/src/openai_codex/client.py
Normal file
924
sdk/python/src/openai_codex/client.py
Normal file
@@ -0,0 +1,924 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import uuid
|
||||
from _thread import LockType
|
||||
from collections import deque
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Callable, Iterator, TypeVar
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ._goal import _GoalOperationState
|
||||
from ._initialize_metadata import _split_user_agent
|
||||
from ._message_router import MessageRouter, _TurnSubscription
|
||||
from ._runtime_requirements import CheckoutCapabilities, require_runtime_version
|
||||
from ._version import __version__ as SDK_VERSION
|
||||
from .errors import CodexError, InvalidRequestError, TransportClosedError
|
||||
from .generated.notification_registry import NOTIFICATION_MODELS
|
||||
from .generated.v2_all import (
|
||||
AccountLoginCompletedNotification,
|
||||
AgentMessageDeltaNotification,
|
||||
CancelLoginAccountResponse,
|
||||
ChatgptDeviceCodeLoginAccountResponse,
|
||||
ChatgptLoginAccountResponse,
|
||||
GetAccountParams as V2GetAccountParams,
|
||||
GetAccountResponse,
|
||||
IdleThreadStatus,
|
||||
LoginAccountParams as V2LoginAccountParams,
|
||||
LoginAccountResponse,
|
||||
LogoutAccountResponse,
|
||||
ModelListResponse,
|
||||
ThreadArchiveResponse,
|
||||
ThreadCompactStartResponse,
|
||||
ThreadForkParams as V2ThreadForkParams,
|
||||
ThreadForkResponse,
|
||||
ThreadGoalClearResponse,
|
||||
ThreadGoalSetResponse,
|
||||
ThreadGoalStatus,
|
||||
ThreadListParams as V2ThreadListParams,
|
||||
ThreadListResponse,
|
||||
ThreadReadResponse,
|
||||
ThreadResumeParams as V2ThreadResumeParams,
|
||||
ThreadResumeResponse,
|
||||
ThreadSetNameResponse,
|
||||
ThreadStartParams as V2ThreadStartParams,
|
||||
ThreadStartResponse,
|
||||
ThreadUnarchiveResponse,
|
||||
TurnCompletedNotification,
|
||||
TurnInterruptResponse,
|
||||
TurnStartParams as V2TurnStartParams,
|
||||
TurnStartResponse,
|
||||
TurnSteerResponse,
|
||||
)
|
||||
from .models import (
|
||||
InitializeResponse,
|
||||
JsonObject,
|
||||
JsonValue,
|
||||
Notification,
|
||||
UnknownNotification,
|
||||
)
|
||||
from .retry import retry_on_overload
|
||||
|
||||
ModelT = TypeVar("ModelT", bound=BaseModel)
|
||||
ApprovalHandler = Callable[[str, JsonObject | None], JsonObject]
|
||||
RUNTIME_PKG_NAME = "openai-codex-cli-bin"
|
||||
_GOAL_START_TIMEOUT_S = 30.0
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _ThreadStartLock:
|
||||
lock: LockType = field(default_factory=threading.Lock)
|
||||
users: int = 0
|
||||
|
||||
|
||||
def _active_turn_id_from_error(exc: InvalidRequestError) -> str | None:
|
||||
match = re.search(r" but found `?([^`]+)`?$", exc.message)
|
||||
return match.group(1) if match is not None else None
|
||||
|
||||
|
||||
def _params_dict(
|
||||
params: (
|
||||
V2ThreadStartParams
|
||||
| V2ThreadResumeParams
|
||||
| V2ThreadListParams
|
||||
| V2ThreadForkParams
|
||||
| V2TurnStartParams
|
||||
| V2GetAccountParams
|
||||
| V2LoginAccountParams
|
||||
| JsonObject
|
||||
| None
|
||||
),
|
||||
) -> JsonObject:
|
||||
if params is None:
|
||||
return {}
|
||||
if hasattr(params, "model_dump"):
|
||||
dumped = params.model_dump(
|
||||
by_alias=True,
|
||||
exclude_none=True,
|
||||
mode="json",
|
||||
)
|
||||
if not isinstance(dumped, dict):
|
||||
raise TypeError("Expected model_dump() to return dict")
|
||||
return dumped
|
||||
if isinstance(params, dict):
|
||||
return params
|
||||
raise TypeError(f"Expected generated params model or dict, got {type(params).__name__}")
|
||||
|
||||
|
||||
def _installed_codex_path() -> Path:
|
||||
try:
|
||||
from codex_cli_bin import bundled_codex_path
|
||||
except ImportError as exc:
|
||||
raise FileNotFoundError(
|
||||
"Unable to locate the pinned Codex runtime. Install the published SDK build "
|
||||
f"with its {RUNTIME_PKG_NAME} dependency, or set CodexConfig.codex_bin "
|
||||
"explicitly."
|
||||
) from exc
|
||||
|
||||
return bundled_codex_path()
|
||||
|
||||
|
||||
def _installed_codex_path_dirs() -> tuple[Path, ...]:
|
||||
try:
|
||||
from codex_cli_bin import bundled_path_dir
|
||||
except (ImportError, AttributeError):
|
||||
return ()
|
||||
|
||||
path_dir = bundled_path_dir()
|
||||
return (path_dir,) if path_dir is not None else ()
|
||||
|
||||
|
||||
def _prepend_path_dirs(env: dict[str, str], path_dirs: tuple[Path, ...]) -> None:
|
||||
if not path_dirs:
|
||||
return
|
||||
|
||||
path_key = _path_env_key(env)
|
||||
if os.name == "nt":
|
||||
for key in list(env):
|
||||
if key.upper() == "PATH" and key != path_key:
|
||||
env.pop(key)
|
||||
|
||||
path_sep = os.pathsep
|
||||
existing_path = env.get(path_key, "")
|
||||
path_dir_values = [str(path_dir) for path_dir in path_dirs]
|
||||
existing_entries = [
|
||||
entry for entry in existing_path.split(path_sep) if entry and entry not in path_dir_values
|
||||
]
|
||||
env[path_key] = path_sep.join([*path_dir_values, *existing_entries])
|
||||
|
||||
|
||||
def _path_env_key(env: dict[str, str]) -> str:
|
||||
if os.name != "nt":
|
||||
return "PATH"
|
||||
|
||||
matching_keys = [key for key in env if key.upper() == "PATH"]
|
||||
if "Path" in matching_keys:
|
||||
return "Path"
|
||||
return matching_keys[-1] if matching_keys else "PATH"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CodexBinResolverOps:
|
||||
installed_codex_path: Callable[[], Path]
|
||||
path_exists: Callable[[Path], bool]
|
||||
|
||||
|
||||
def _default_codex_bin_resolver_ops() -> CodexBinResolverOps:
|
||||
return CodexBinResolverOps(
|
||||
installed_codex_path=_installed_codex_path,
|
||||
path_exists=lambda path: path.exists(),
|
||||
)
|
||||
|
||||
|
||||
def resolve_codex_bin(config: "CodexConfig", ops: CodexBinResolverOps) -> Path:
|
||||
if config.codex_bin is not None:
|
||||
codex_bin = Path(config.codex_bin)
|
||||
if not ops.path_exists(codex_bin):
|
||||
raise FileNotFoundError(
|
||||
f"Codex binary not found at {codex_bin}. Set CodexConfig.codex_bin "
|
||||
"to a valid binary path."
|
||||
)
|
||||
return codex_bin
|
||||
|
||||
return ops.installed_codex_path()
|
||||
|
||||
|
||||
def _resolve_codex_bin(config: "CodexConfig") -> Path:
|
||||
return resolve_codex_bin(config, _default_codex_bin_resolver_ops())
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CodexConfig:
|
||||
"""Configuration for launching and identifying the local Codex runtime.
|
||||
|
||||
Most callers can use ``Codex()`` without configuration. Set ``codex_bin``
|
||||
only when intentionally using a specific local Codex executable.
|
||||
"""
|
||||
|
||||
codex_bin: str | None = None
|
||||
launch_args_override: tuple[str, ...] | None = None
|
||||
config_overrides: tuple[str, ...] = ()
|
||||
cwd: str | None = None
|
||||
env: dict[str, str] | None = None
|
||||
client_name: str = "codex_python_sdk"
|
||||
client_title: str = "Codex Python SDK"
|
||||
client_version: str = SDK_VERSION
|
||||
experimental_api: bool = True
|
||||
|
||||
|
||||
class CodexClient:
|
||||
"""Synchronous typed JSON-RPC client for `codex app-server` over stdio."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: CodexConfig | None = None,
|
||||
approval_handler: ApprovalHandler | None = None,
|
||||
) -> None:
|
||||
self.config = config or CodexConfig()
|
||||
self._approval_handler = approval_handler or self._default_approval_handler
|
||||
self._proc: subprocess.Popen[str] | None = None
|
||||
self._lock = threading.Lock()
|
||||
self._thread_start_locks_guard = threading.Lock()
|
||||
self._thread_start_locks: dict[str, _ThreadStartLock] = {}
|
||||
self._router = MessageRouter()
|
||||
self._stderr_lines: deque[str] = deque(maxlen=400)
|
||||
self._stderr_thread: threading.Thread | None = None
|
||||
self._reader_thread: threading.Thread | None = None
|
||||
self._runtime_version: str | None = None
|
||||
self._checkout_capabilities: CheckoutCapabilities | None = None
|
||||
|
||||
def __enter__(self) -> "CodexClient":
|
||||
self.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, _exc_type, _exc, _tb) -> None:
|
||||
self.close()
|
||||
|
||||
def start(self) -> None:
|
||||
if self._proc is not None:
|
||||
return
|
||||
|
||||
path_dirs: tuple[Path, ...] = ()
|
||||
if self.config.launch_args_override is not None:
|
||||
args = list(self.config.launch_args_override)
|
||||
else:
|
||||
codex_bin = _resolve_codex_bin(self.config)
|
||||
if self.config.codex_bin is None:
|
||||
path_dirs = _installed_codex_path_dirs()
|
||||
args = [str(codex_bin)]
|
||||
for kv in self.config.config_overrides:
|
||||
args.extend(["--config", kv])
|
||||
args.extend(["app-server", "--listen", "stdio://"])
|
||||
|
||||
env = os.environ.copy()
|
||||
if self.config.env:
|
||||
env.update(self.config.env)
|
||||
_prepend_path_dirs(env, path_dirs)
|
||||
|
||||
if self.config.launch_args_override is None:
|
||||
self._checkout_capabilities = CheckoutCapabilities(
|
||||
command=tuple(args[:-2]), cwd=self.config.cwd, env=env.copy()
|
||||
)
|
||||
|
||||
self._proc = subprocess.Popen(
|
||||
args,
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
cwd=self.config.cwd,
|
||||
env=env,
|
||||
bufsize=1,
|
||||
)
|
||||
|
||||
self._start_stderr_drain_thread()
|
||||
self._start_reader_thread()
|
||||
|
||||
def close(self) -> None:
|
||||
self._runtime_version = None
|
||||
self._checkout_capabilities = None
|
||||
if self._proc is None:
|
||||
return
|
||||
proc = self._proc
|
||||
self._proc = None
|
||||
|
||||
if proc.stdin:
|
||||
proc.stdin.close()
|
||||
try:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=2)
|
||||
except Exception:
|
||||
proc.kill()
|
||||
|
||||
if self._stderr_thread and self._stderr_thread.is_alive():
|
||||
self._stderr_thread.join(timeout=0.5)
|
||||
if self._reader_thread and self._reader_thread.is_alive():
|
||||
self._reader_thread.join(timeout=0.5)
|
||||
|
||||
def initialize(self) -> InitializeResponse:
|
||||
self._runtime_version = None
|
||||
result = self.request(
|
||||
"initialize",
|
||||
{
|
||||
"clientInfo": {
|
||||
"name": self.config.client_name,
|
||||
"title": self.config.client_title,
|
||||
"version": self.config.client_version,
|
||||
},
|
||||
"capabilities": {
|
||||
"experimentalApi": self.config.experimental_api,
|
||||
},
|
||||
},
|
||||
response_model=InitializeResponse,
|
||||
)
|
||||
version = result.serverInfo.version if result.serverInfo is not None else None
|
||||
if not version or not version.strip():
|
||||
_, version = _split_user_agent(result.userAgent or "")
|
||||
self._runtime_version = version.split()[0] if version and version.strip() else None
|
||||
self.notify("initialized", None)
|
||||
return result
|
||||
|
||||
def request(
|
||||
self,
|
||||
method: str,
|
||||
params: JsonObject | None,
|
||||
*,
|
||||
response_model: type[ModelT],
|
||||
) -> ModelT:
|
||||
runtime_fields = {
|
||||
"turn/start": ("toolOutput", "turnTrigger", "serviceTierForTurn"),
|
||||
"thread/resume": ("excludeTurns",),
|
||||
"thread/fork": ("excludeTurns",),
|
||||
}
|
||||
supplied_fields = [
|
||||
field
|
||||
for field in runtime_fields.get(method, ())
|
||||
if (params or {}).get(field) is not None
|
||||
]
|
||||
if supplied_fields:
|
||||
try:
|
||||
if self._runtime_version == "0.0.0":
|
||||
if self._checkout_capabilities is None:
|
||||
raise ValueError(
|
||||
"Cannot verify an unversioned CLI with a custom launch command"
|
||||
)
|
||||
supported = self._checkout_capabilities.fields[method]
|
||||
if missing := set(supplied_fields) - supported:
|
||||
raise ValueError(
|
||||
f"The checkout does not support {', '.join(sorted(missing))}"
|
||||
)
|
||||
else:
|
||||
require_runtime_version(self._runtime_version)
|
||||
except ValueError as exc:
|
||||
raise CodexError(
|
||||
f"{method} with {', '.join(supplied_fields)}: {exc}. "
|
||||
"Configure CodexConfig.codex_bin with a supported CLI."
|
||||
) from exc
|
||||
result = self._request_raw(method, params)
|
||||
if not isinstance(result, dict):
|
||||
raise CodexError(f"{method} response must be a JSON object")
|
||||
return response_model.model_validate(result)
|
||||
|
||||
def _request_raw(self, method: str, params: JsonObject | None = None) -> JsonValue:
|
||||
"""Send a JSON-RPC request and wait for the reader thread to route its response."""
|
||||
request_id = str(uuid.uuid4())
|
||||
waiter = self._router.create_response_waiter(request_id)
|
||||
|
||||
try:
|
||||
message: JsonObject = {"id": request_id, "method": method}
|
||||
if params is not None:
|
||||
message["params"] = params
|
||||
self._write_message(message)
|
||||
except BaseException:
|
||||
self._router.discard_response_waiter(request_id)
|
||||
raise
|
||||
|
||||
item = waiter.get()
|
||||
if isinstance(item, BaseException):
|
||||
raise item
|
||||
return item
|
||||
|
||||
def notify(self, method: str, params: JsonObject | None = None) -> None:
|
||||
"""Send a JSON-RPC notification without waiting for a response."""
|
||||
message: JsonObject = {"method": method}
|
||||
if params is not None:
|
||||
message["params"] = params
|
||||
self._write_message(message)
|
||||
|
||||
def next_notification(self) -> Notification:
|
||||
"""Return the next notification that is not scoped to an active turn."""
|
||||
return self._router.next_global_notification()
|
||||
|
||||
def register_login_notifications(self, login_id: str) -> None:
|
||||
"""Start routing notifications for one interactive login attempt."""
|
||||
self._router.register_login(login_id)
|
||||
|
||||
def unregister_login_notifications(self, login_id: str) -> None:
|
||||
"""Stop routing notifications for one interactive login attempt."""
|
||||
self._router.unregister_login(login_id)
|
||||
|
||||
def next_login_notification(self, login_id: str) -> Notification:
|
||||
"""Return the next routed notification for the requested login id."""
|
||||
return self._router.next_login_notification(login_id)
|
||||
|
||||
def _subscribe_turn_notifications(self, turn_id: str) -> _TurnSubscription:
|
||||
return self._router.subscribe_turn(turn_id)
|
||||
|
||||
def register_turn_notifications(self, turn_id: str) -> None:
|
||||
"""Start routing notifications for one turn into its dedicated queue."""
|
||||
self._router.register_turn(turn_id)
|
||||
|
||||
def unregister_turn_notifications(self, turn_id: str) -> None:
|
||||
"""Stop routing notifications for one turn into its dedicated queue."""
|
||||
self._router.unregister_turn(turn_id)
|
||||
|
||||
def next_turn_notification(self, turn_id: str) -> Notification:
|
||||
"""Return the next routed notification for the requested turn id."""
|
||||
return self._router.next_turn_notification(turn_id)
|
||||
|
||||
def register_goal_operation(self, thread_id: str) -> _GoalOperationState:
|
||||
"""Register a private thread-scoped route for a logical goal turn."""
|
||||
return self._router.register_goal(thread_id)
|
||||
|
||||
def reserve_goal_operation(self, thread_id: str) -> _GoalOperationState:
|
||||
"""Reserve a private thread route before replacing its stored goal."""
|
||||
return self._router.reserve_goal(thread_id)
|
||||
|
||||
def unregister_goal_operation(self, state: _GoalOperationState) -> None:
|
||||
"""Release routing state for one logical goal turn."""
|
||||
self._router.unregister_goal(state)
|
||||
|
||||
def next_goal_notification(self, state: _GoalOperationState) -> Notification:
|
||||
"""Wait for the next notification in a logical goal turn."""
|
||||
return state.next_notification()
|
||||
|
||||
def account_login_start(
|
||||
self,
|
||||
params: V2LoginAccountParams | JsonObject,
|
||||
) -> LoginAccountResponse:
|
||||
response = self.request(
|
||||
"account/login/start",
|
||||
_params_dict(params),
|
||||
response_model=LoginAccountResponse,
|
||||
)
|
||||
response_root = response.root
|
||||
if isinstance(
|
||||
response_root,
|
||||
ChatgptLoginAccountResponse | ChatgptDeviceCodeLoginAccountResponse,
|
||||
):
|
||||
self.register_login_notifications(response_root.login_id)
|
||||
return response
|
||||
|
||||
def account_login_cancel(self, login_id: str) -> CancelLoginAccountResponse:
|
||||
return self.request(
|
||||
"account/login/cancel",
|
||||
{"loginId": login_id},
|
||||
response_model=CancelLoginAccountResponse,
|
||||
)
|
||||
|
||||
def account_read(
|
||||
self,
|
||||
params: V2GetAccountParams | JsonObject | None = None,
|
||||
) -> GetAccountResponse:
|
||||
return self.request(
|
||||
"account/read",
|
||||
_params_dict(params),
|
||||
response_model=GetAccountResponse,
|
||||
)
|
||||
|
||||
def account_logout(self) -> LogoutAccountResponse:
|
||||
return self.request("account/logout", None, response_model=LogoutAccountResponse)
|
||||
|
||||
def thread_start(
|
||||
self, params: V2ThreadStartParams | JsonObject | None = None
|
||||
) -> ThreadStartResponse:
|
||||
return self.request(
|
||||
"thread/start", _params_dict(params), response_model=ThreadStartResponse
|
||||
)
|
||||
|
||||
def thread_resume(
|
||||
self,
|
||||
thread_id: str,
|
||||
params: V2ThreadResumeParams | JsonObject | None = None,
|
||||
) -> ThreadResumeResponse:
|
||||
payload = {"threadId": thread_id, **_params_dict(params)}
|
||||
return self.request("thread/resume", payload, response_model=ThreadResumeResponse)
|
||||
|
||||
def thread_list(
|
||||
self, params: V2ThreadListParams | JsonObject | None = None
|
||||
) -> ThreadListResponse:
|
||||
return self.request("thread/list", _params_dict(params), response_model=ThreadListResponse)
|
||||
|
||||
def thread_read(self, thread_id: str, include_turns: bool = False) -> ThreadReadResponse:
|
||||
return self.request(
|
||||
"thread/read",
|
||||
{"threadId": thread_id, "includeTurns": include_turns},
|
||||
response_model=ThreadReadResponse,
|
||||
)
|
||||
|
||||
def thread_fork(
|
||||
self,
|
||||
thread_id: str,
|
||||
params: V2ThreadForkParams | JsonObject | None = None,
|
||||
) -> ThreadForkResponse:
|
||||
payload = {"threadId": thread_id, **_params_dict(params)}
|
||||
return self.request("thread/fork", payload, response_model=ThreadForkResponse)
|
||||
|
||||
def thread_archive(self, thread_id: str) -> ThreadArchiveResponse:
|
||||
return self.request(
|
||||
"thread/archive",
|
||||
{"threadId": thread_id},
|
||||
response_model=ThreadArchiveResponse,
|
||||
)
|
||||
|
||||
def thread_unarchive(self, thread_id: str) -> ThreadUnarchiveResponse:
|
||||
return self.request(
|
||||
"thread/unarchive",
|
||||
{"threadId": thread_id},
|
||||
response_model=ThreadUnarchiveResponse,
|
||||
)
|
||||
|
||||
def thread_set_name(self, thread_id: str, name: str) -> ThreadSetNameResponse:
|
||||
return self.request(
|
||||
"thread/name/set",
|
||||
{"threadId": thread_id, "name": name},
|
||||
response_model=ThreadSetNameResponse,
|
||||
)
|
||||
|
||||
def thread_compact(self, thread_id: str) -> ThreadCompactStartResponse:
|
||||
return self.request(
|
||||
"thread/compact/start",
|
||||
{"threadId": thread_id},
|
||||
response_model=ThreadCompactStartResponse,
|
||||
)
|
||||
|
||||
def thread_goal_clear(self, thread_id: str) -> ThreadGoalClearResponse:
|
||||
"""Clear the persisted goal for a thread before replacing it."""
|
||||
return self.request(
|
||||
"thread/goal/clear",
|
||||
{"threadId": thread_id},
|
||||
response_model=ThreadGoalClearResponse,
|
||||
)
|
||||
|
||||
def thread_goal_set(
|
||||
self,
|
||||
thread_id: str,
|
||||
*,
|
||||
objective: str | None = None,
|
||||
status: ThreadGoalStatus | None = None,
|
||||
) -> ThreadGoalSetResponse:
|
||||
"""Create or update the persisted goal for a thread."""
|
||||
payload: JsonObject = {"threadId": thread_id}
|
||||
if objective is not None:
|
||||
payload["objective"] = objective
|
||||
if status is not None:
|
||||
payload["status"] = status.value
|
||||
return self.request(
|
||||
"thread/goal/set",
|
||||
payload,
|
||||
response_model=ThreadGoalSetResponse,
|
||||
)
|
||||
|
||||
def pause_goal(self, thread_id: str) -> ThreadGoalSetResponse:
|
||||
"""Pause the active goal used by a logical goal turn."""
|
||||
return self.thread_goal_set(thread_id, status=ThreadGoalStatus.paused)
|
||||
|
||||
def cancel_goal_operation(self, state: _GoalOperationState) -> None:
|
||||
"""Best-effort cleanup after a logical goal operation is cancelled."""
|
||||
try:
|
||||
self.pause_goal(state.thread_id)
|
||||
except Exception:
|
||||
pass
|
||||
self._interrupt_goal_operation(state)
|
||||
|
||||
def _interrupt_goal_operation(self, state: _GoalOperationState) -> None:
|
||||
turn_id = state.turn_for_interrupt()
|
||||
if turn_id is None:
|
||||
return
|
||||
try:
|
||||
self.turn_interrupt(state.thread_id, turn_id)
|
||||
except InvalidRequestError as exc:
|
||||
if not exc.message.startswith("expected active turn id"):
|
||||
return
|
||||
next_turn_id = _active_turn_id_from_error(exc) or state.current_turn()
|
||||
if next_turn_id is None or next_turn_id == turn_id:
|
||||
return
|
||||
try:
|
||||
self.turn_interrupt(state.thread_id, next_turn_id)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def start_goal_operation(
|
||||
self,
|
||||
thread_id: str,
|
||||
objective: str,
|
||||
) -> tuple[_GoalOperationState, str]:
|
||||
"""Start a logical goal and wait for its runtime-generated first turn."""
|
||||
with self._thread_start_lock(thread_id):
|
||||
return self._start_goal_operation(thread_id, objective)
|
||||
|
||||
def _start_goal_operation(
|
||||
self,
|
||||
thread_id: str,
|
||||
objective: str,
|
||||
) -> tuple[_GoalOperationState, str]:
|
||||
thread = self.thread_read(thread_id).thread
|
||||
if not isinstance(thread.status.root, IdleThreadStatus):
|
||||
raise InvalidRequestError(
|
||||
-32600,
|
||||
f"thread must be idle before starting a goal: {thread_id}",
|
||||
)
|
||||
if thread.ephemeral or thread.path is None:
|
||||
raise InvalidRequestError(
|
||||
-32600,
|
||||
f"thread must be persisted before starting a goal: {thread_id}",
|
||||
)
|
||||
|
||||
state = self.reserve_goal_operation(thread_id)
|
||||
activated = False
|
||||
try:
|
||||
self.thread_goal_clear(thread_id)
|
||||
state.activate_turn_routing()
|
||||
self.thread_goal_set(
|
||||
thread_id,
|
||||
objective=objective,
|
||||
status=ThreadGoalStatus.active,
|
||||
)
|
||||
activated = True
|
||||
turn_id = state.wait_for_start(_GOAL_START_TIMEOUT_S)
|
||||
if turn_id is None:
|
||||
raise CodexError(
|
||||
"timed out waiting for goal turn to start after "
|
||||
f"{int(_GOAL_START_TIMEOUT_S)} seconds"
|
||||
)
|
||||
return state, turn_id
|
||||
except BaseException as exc:
|
||||
if activated or not isinstance(exc, InvalidRequestError):
|
||||
self.cancel_goal_operation(state)
|
||||
state.finish()
|
||||
self.unregister_goal_operation(state)
|
||||
raise
|
||||
|
||||
def turn_start(
|
||||
self,
|
||||
thread_id: str,
|
||||
input_items: list[JsonObject] | JsonObject | str,
|
||||
params: V2TurnStartParams | JsonObject | None = None,
|
||||
) -> TurnStartResponse:
|
||||
"""Start a turn and register its notification queue as early as possible."""
|
||||
return self._start_turn(thread_id, input_items, params, for_handle=False)[0]
|
||||
|
||||
def _start_turn(
|
||||
self,
|
||||
thread_id: str,
|
||||
input_items: list[JsonObject] | JsonObject | str,
|
||||
params: V2TurnStartParams | JsonObject | None,
|
||||
for_handle: bool,
|
||||
) -> tuple[TurnStartResponse, _TurnSubscription | None]:
|
||||
with self._thread_start_lock(thread_id):
|
||||
if self._router.has_goal(thread_id):
|
||||
raise InvalidRequestError(
|
||||
-32600,
|
||||
f"thread has an active goal operation: {thread_id}",
|
||||
)
|
||||
payload = {
|
||||
**_params_dict(params),
|
||||
"threadId": thread_id,
|
||||
"input": self._normalize_input_items(input_items),
|
||||
}
|
||||
with self._router.pending_turn(thread_id) as cursors:
|
||||
started = self.request("turn/start", payload, response_model=TurnStartResponse)
|
||||
subscription = self._router.prepare_turn(
|
||||
started.turn.id, thread_id, cursors, for_handle=for_handle
|
||||
)
|
||||
return started, subscription
|
||||
|
||||
@contextmanager
|
||||
def _thread_start_lock(self, thread_id: str) -> Iterator[None]:
|
||||
with self._thread_start_locks_guard:
|
||||
entry = self._thread_start_locks.get(thread_id)
|
||||
if entry is None:
|
||||
entry = _ThreadStartLock()
|
||||
self._thread_start_locks[thread_id] = entry
|
||||
entry.users += 1
|
||||
try:
|
||||
with entry.lock:
|
||||
yield
|
||||
finally:
|
||||
with self._thread_start_locks_guard:
|
||||
entry.users -= 1
|
||||
if entry.users == 0:
|
||||
self._thread_start_locks.pop(thread_id, None)
|
||||
|
||||
def turn_interrupt(self, thread_id: str, turn_id: str) -> TurnInterruptResponse:
|
||||
return self.request(
|
||||
"turn/interrupt",
|
||||
{"threadId": thread_id, "turnId": turn_id},
|
||||
response_model=TurnInterruptResponse,
|
||||
)
|
||||
|
||||
def turn_steer(
|
||||
self,
|
||||
thread_id: str,
|
||||
expected_turn_id: str,
|
||||
input_items: list[JsonObject] | JsonObject | str,
|
||||
) -> TurnSteerResponse:
|
||||
return self.request(
|
||||
"turn/steer",
|
||||
{
|
||||
"threadId": thread_id,
|
||||
"expectedTurnId": expected_turn_id,
|
||||
"input": self._normalize_input_items(input_items),
|
||||
},
|
||||
response_model=TurnSteerResponse,
|
||||
)
|
||||
|
||||
def model_list(self, include_hidden: bool = False) -> ModelListResponse:
|
||||
return self.request(
|
||||
"model/list",
|
||||
{"includeHidden": include_hidden},
|
||||
response_model=ModelListResponse,
|
||||
)
|
||||
|
||||
def request_with_retry_on_overload(
|
||||
self,
|
||||
method: str,
|
||||
params: JsonObject | None,
|
||||
*,
|
||||
response_model: type[ModelT],
|
||||
max_attempts: int = 3,
|
||||
initial_delay_s: float = 0.25,
|
||||
max_delay_s: float = 2.0,
|
||||
) -> ModelT:
|
||||
return retry_on_overload(
|
||||
lambda: self.request(method, params, response_model=response_model),
|
||||
max_attempts=max_attempts,
|
||||
initial_delay_s=initial_delay_s,
|
||||
max_delay_s=max_delay_s,
|
||||
)
|
||||
|
||||
def wait_for_turn_completed(self, turn_id: str) -> TurnCompletedNotification:
|
||||
"""Block on the routed turn stream until the matching completion arrives."""
|
||||
self.register_turn_notifications(turn_id)
|
||||
try:
|
||||
while True:
|
||||
notification = self.next_turn_notification(turn_id)
|
||||
if (
|
||||
notification.method == "turn/completed"
|
||||
and isinstance(notification.payload, TurnCompletedNotification)
|
||||
and notification.payload.turn.id == turn_id
|
||||
):
|
||||
return notification.payload
|
||||
finally:
|
||||
self.unregister_turn_notifications(turn_id)
|
||||
|
||||
def wait_for_login_completed(
|
||||
self,
|
||||
login_id: str,
|
||||
) -> AccountLoginCompletedNotification:
|
||||
"""Block until the matching interactive login attempt completes."""
|
||||
self.register_login_notifications(login_id)
|
||||
try:
|
||||
while True:
|
||||
notification = self.next_login_notification(login_id)
|
||||
if (
|
||||
notification.method == "account/login/completed"
|
||||
and isinstance(notification.payload, AccountLoginCompletedNotification)
|
||||
and notification.payload.login_id == login_id
|
||||
):
|
||||
return notification.payload
|
||||
finally:
|
||||
self.unregister_login_notifications(login_id)
|
||||
|
||||
def stream_text(
|
||||
self,
|
||||
thread_id: str,
|
||||
text: str,
|
||||
params: V2TurnStartParams | JsonObject | None = None,
|
||||
) -> Iterator[AgentMessageDeltaNotification]:
|
||||
"""Start a text turn and yield only its agent-message delta payloads."""
|
||||
started = self.turn_start(thread_id, text, params=params)
|
||||
turn_id = started.turn.id
|
||||
self.register_turn_notifications(turn_id)
|
||||
try:
|
||||
while True:
|
||||
notification = self.next_turn_notification(turn_id)
|
||||
if (
|
||||
notification.method == "item/agentMessage/delta"
|
||||
and isinstance(notification.payload, AgentMessageDeltaNotification)
|
||||
and notification.payload.turn_id == turn_id
|
||||
):
|
||||
yield notification.payload
|
||||
continue
|
||||
if (
|
||||
notification.method == "turn/completed"
|
||||
and isinstance(notification.payload, TurnCompletedNotification)
|
||||
and notification.payload.turn.id == turn_id
|
||||
):
|
||||
break
|
||||
finally:
|
||||
self.unregister_turn_notifications(turn_id)
|
||||
|
||||
def _coerce_notification(self, method: str, params: object) -> Notification:
|
||||
params_dict = params if isinstance(params, dict) else {}
|
||||
|
||||
model = NOTIFICATION_MODELS.get(method)
|
||||
if model is None:
|
||||
return Notification(method=method, payload=UnknownNotification(params=params_dict))
|
||||
|
||||
try:
|
||||
payload = model.model_validate(params_dict)
|
||||
except Exception: # noqa: BLE001
|
||||
return Notification(method=method, payload=UnknownNotification(params=params_dict))
|
||||
return Notification(method=method, payload=payload)
|
||||
|
||||
def _normalize_input_items(
|
||||
self,
|
||||
input_items: list[JsonObject] | JsonObject | str,
|
||||
) -> list[JsonObject]:
|
||||
if isinstance(input_items, str):
|
||||
return [{"type": "text", "text": input_items}]
|
||||
if isinstance(input_items, dict):
|
||||
return [input_items]
|
||||
return input_items
|
||||
|
||||
def _default_approval_handler(self, method: str, params: JsonObject | None) -> JsonObject:
|
||||
"""Accept approval requests when the caller did not provide a handler."""
|
||||
if method == "item/commandExecution/requestApproval":
|
||||
return {"decision": "accept"}
|
||||
if method == "item/fileChange/requestApproval":
|
||||
return {"decision": "accept"}
|
||||
return {}
|
||||
|
||||
def _start_stderr_drain_thread(self) -> None:
|
||||
if self._proc is None or self._proc.stderr is None:
|
||||
return
|
||||
|
||||
def _drain() -> None:
|
||||
stderr = self._proc.stderr
|
||||
if stderr is None:
|
||||
return
|
||||
for line in stderr:
|
||||
self._stderr_lines.append(line.rstrip("\n"))
|
||||
|
||||
self._stderr_thread = threading.Thread(target=_drain, daemon=True)
|
||||
self._stderr_thread.start()
|
||||
|
||||
def _start_reader_thread(self) -> None:
|
||||
"""Start the sole stdout reader that fans messages into router queues."""
|
||||
if self._proc is None or self._proc.stdout is None:
|
||||
return
|
||||
|
||||
self._reader_thread = threading.Thread(target=self._reader_loop, daemon=True)
|
||||
self._reader_thread.start()
|
||||
|
||||
def _reader_loop(self) -> None:
|
||||
"""Continuously classify transport messages into requests, responses, and events."""
|
||||
try:
|
||||
while True:
|
||||
msg = self._read_message()
|
||||
if "method" in msg and "id" in msg:
|
||||
response = self._handle_server_request(msg)
|
||||
self._write_message({"id": msg["id"], "result": response})
|
||||
continue
|
||||
if "method" in msg and "id" not in msg:
|
||||
method = msg["method"]
|
||||
if isinstance(method, str):
|
||||
self._router.route_notification(
|
||||
self._coerce_notification(method, msg.get("params"))
|
||||
)
|
||||
continue
|
||||
self._router.route_response(msg)
|
||||
except BaseException as exc:
|
||||
self._router.fail_all(exc)
|
||||
|
||||
def _stderr_tail(self, limit: int = 40) -> str:
|
||||
return "\n".join(list(self._stderr_lines)[-limit:])
|
||||
|
||||
def _handle_server_request(self, msg: dict[str, JsonValue]) -> JsonObject:
|
||||
method = msg["method"]
|
||||
params = msg.get("params")
|
||||
if not isinstance(method, str):
|
||||
return {}
|
||||
return self._approval_handler(
|
||||
method,
|
||||
params if isinstance(params, dict) else None,
|
||||
)
|
||||
|
||||
def _write_message(self, payload: JsonObject) -> None:
|
||||
if self._proc is None or self._proc.stdin is None:
|
||||
raise TransportClosedError("Codex process is not running")
|
||||
with self._lock:
|
||||
self._proc.stdin.write(json.dumps(payload) + "\n")
|
||||
self._proc.stdin.flush()
|
||||
|
||||
def _read_message(self) -> dict[str, JsonValue]:
|
||||
if self._proc is None or self._proc.stdout is None:
|
||||
raise TransportClosedError("Codex process is not running")
|
||||
|
||||
line = self._proc.stdout.readline()
|
||||
if not line:
|
||||
raise TransportClosedError(
|
||||
f"Codex process closed stdout. stderr_tail={self._stderr_tail()[:2000]}"
|
||||
)
|
||||
|
||||
try:
|
||||
message = json.loads(line)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise CodexError(f"Invalid JSON-RPC line: {line!r}") from exc
|
||||
|
||||
if not isinstance(message, dict):
|
||||
raise CodexError(f"Invalid JSON-RPC payload: {message!r}")
|
||||
return message
|
||||
|
||||
|
||||
def default_codex_home() -> str:
|
||||
return str(Path.home() / ".codex")
|
||||
121
sdk/python/src/openai_codex/errors.py
Normal file
121
sdk/python/src/openai_codex/errors.py
Normal file
@@ -0,0 +1,121 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
class CodexError(Exception):
|
||||
"""Base exception for SDK errors."""
|
||||
|
||||
|
||||
class JsonRpcError(CodexError):
|
||||
"""Raw JSON-RPC error wrapper from the server."""
|
||||
|
||||
def __init__(self, code: int, message: str, data: Any = None):
|
||||
super().__init__(f"JSON-RPC error {code}: {message}")
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.data = data
|
||||
|
||||
|
||||
class TransportClosedError(CodexError):
|
||||
"""Raised when the Codex transport closes unexpectedly."""
|
||||
|
||||
|
||||
class CodexRpcError(JsonRpcError):
|
||||
"""Base typed error for JSON-RPC failures."""
|
||||
|
||||
|
||||
class ParseError(CodexRpcError):
|
||||
"""Raised when a request or response cannot be parsed."""
|
||||
|
||||
|
||||
class InvalidRequestError(CodexRpcError):
|
||||
"""Raised when the runtime rejects the request shape."""
|
||||
|
||||
|
||||
class MethodNotFoundError(CodexRpcError):
|
||||
"""Raised when the requested operation is unavailable."""
|
||||
|
||||
|
||||
class InvalidParamsError(CodexRpcError):
|
||||
"""Raised when an operation receives invalid parameters."""
|
||||
|
||||
|
||||
class InternalRpcError(CodexRpcError):
|
||||
"""Raised when the runtime reports an internal RPC failure."""
|
||||
|
||||
|
||||
class ServerBusyError(CodexRpcError):
|
||||
"""Server is overloaded / unavailable and caller should retry."""
|
||||
|
||||
|
||||
class RetryLimitExceededError(ServerBusyError):
|
||||
"""Server exhausted internal retry budget for a retryable operation."""
|
||||
|
||||
|
||||
def _contains_retry_limit_text(message: str) -> bool:
|
||||
lowered = message.lower()
|
||||
return "retry limit" in lowered or "too many failed attempts" in lowered
|
||||
|
||||
|
||||
def _is_server_overloaded(data: Any) -> bool:
|
||||
if data is None:
|
||||
return False
|
||||
|
||||
if isinstance(data, str):
|
||||
return data.lower() == "server_overloaded"
|
||||
|
||||
if isinstance(data, dict):
|
||||
direct = data.get("codex_error_info") or data.get("codexErrorInfo") or data.get("errorInfo")
|
||||
if isinstance(direct, str) and direct.lower() == "server_overloaded":
|
||||
return True
|
||||
if isinstance(direct, dict):
|
||||
for value in direct.values():
|
||||
if isinstance(value, str) and value.lower() == "server_overloaded":
|
||||
return True
|
||||
for value in data.values():
|
||||
if _is_server_overloaded(value):
|
||||
return True
|
||||
|
||||
if isinstance(data, list):
|
||||
return any(_is_server_overloaded(value) for value in data)
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def map_jsonrpc_error(code: int, message: str, data: Any = None) -> JsonRpcError:
|
||||
"""Map a raw JSON-RPC error into a richer SDK exception class."""
|
||||
|
||||
if code == -32700:
|
||||
return ParseError(code, message, data)
|
||||
if code == -32600:
|
||||
return InvalidRequestError(code, message, data)
|
||||
if code == -32601:
|
||||
return MethodNotFoundError(code, message, data)
|
||||
if code == -32602:
|
||||
return InvalidParamsError(code, message, data)
|
||||
if code == -32603:
|
||||
return InternalRpcError(code, message, data)
|
||||
|
||||
if -32099 <= code <= -32000:
|
||||
if _is_server_overloaded(data):
|
||||
if _contains_retry_limit_text(message):
|
||||
return RetryLimitExceededError(code, message, data)
|
||||
return ServerBusyError(code, message, data)
|
||||
if _contains_retry_limit_text(message):
|
||||
return RetryLimitExceededError(code, message, data)
|
||||
return CodexRpcError(code, message, data)
|
||||
|
||||
return JsonRpcError(code, message, data)
|
||||
|
||||
|
||||
def is_retryable_error(exc: BaseException) -> bool:
|
||||
"""True if the exception is a transient overload-style error."""
|
||||
|
||||
if isinstance(exc, ServerBusyError):
|
||||
return True
|
||||
|
||||
if isinstance(exc, JsonRpcError):
|
||||
return _is_server_overloaded(exc.data)
|
||||
|
||||
return False
|
||||
1
sdk/python/src/openai_codex/generated/__init__.py
Normal file
1
sdk/python/src/openai_codex/generated/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Auto-generated Python types derived from the app-server schemas."""
|
||||
314
sdk/python/src/openai_codex/generated/notification_registry.py
Normal file
314
sdk/python/src/openai_codex/generated/notification_registry.py
Normal file
@@ -0,0 +1,314 @@
|
||||
# Auto-generated by scripts/update_sdk_artifacts.py
|
||||
# DO NOT EDIT MANUALLY.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TypeAlias
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .v2_all import AccountLoginCompletedNotification
|
||||
from .v2_all import AccountRateLimitsUpdatedNotification
|
||||
from .v2_all import AccountUpdatedNotification
|
||||
from .v2_all import AgentMessageDeltaNotification
|
||||
from .v2_all import AppListUpdatedNotification
|
||||
from .v2_all import AuthRecoveryNotification
|
||||
from .v2_all import CommandExecOutputDeltaNotification
|
||||
from .v2_all import CommandExecutionOutputDeltaNotification
|
||||
from .v2_all import ConfigWarningNotification
|
||||
from .v2_all import ContextCompactedNotification
|
||||
from .v2_all import DeprecationNoticeNotification
|
||||
from .v2_all import EnvironmentConnectionNotification
|
||||
from .v2_all import ErrorNotification
|
||||
from .v2_all import ExternalAgentConfigImportCompletedNotification
|
||||
from .v2_all import ExternalAgentConfigImportProgressNotification
|
||||
from .v2_all import FileChangeOutputDeltaNotification
|
||||
from .v2_all import FileChangePatchUpdatedNotification
|
||||
from .v2_all import FsChangedNotification
|
||||
from .v2_all import FuzzyFileSearchSessionCompletedNotification
|
||||
from .v2_all import FuzzyFileSearchSessionUpdatedNotification
|
||||
from .v2_all import GatewayOAuthChangedNotification
|
||||
from .v2_all import GuardianWarningNotification
|
||||
from .v2_all import HookCompletedNotification
|
||||
from .v2_all import HookStartedNotification
|
||||
from .v2_all import ItemCompletedNotification
|
||||
from .v2_all import ItemGuardianApprovalReviewCompletedNotification
|
||||
from .v2_all import ItemGuardianApprovalReviewStartedNotification
|
||||
from .v2_all import ItemStartedNotification
|
||||
from .v2_all import McpServerEventStreamNotification
|
||||
from .v2_all import McpServerOauthLoginCompletedNotification
|
||||
from .v2_all import McpServerStatusUpdatedNotification
|
||||
from .v2_all import McpToolCallProgressNotification
|
||||
from .v2_all import ModelReroutedNotification
|
||||
from .v2_all import ModelSafetyBufferingUpdatedNotification
|
||||
from .v2_all import ModelVerificationNotification
|
||||
from .v2_all import PlanDeltaNotification
|
||||
from .v2_all import ProcessExitedNotification
|
||||
from .v2_all import ProcessOutputDeltaNotification
|
||||
from .v2_all import ProjectChangedNotification
|
||||
from .v2_all import ReasoningSummaryPartAddedNotification
|
||||
from .v2_all import ReasoningSummaryTextDeltaNotification
|
||||
from .v2_all import ReasoningTextDeltaNotification
|
||||
from .v2_all import RemoteControlStatusChangedNotification
|
||||
from .v2_all import ServerRequestResolvedNotification
|
||||
from .v2_all import SkillsChangedNotification
|
||||
from .v2_all import StrictReviewRequiredNotification
|
||||
from .v2_all import TerminalInteractionNotification
|
||||
from .v2_all import ThreadArchivedNotification
|
||||
from .v2_all import ThreadAttachmentUpdatedNotification
|
||||
from .v2_all import ThreadClosedNotification
|
||||
from .v2_all import ThreadDeletedNotification
|
||||
from .v2_all import ThreadGoalClearedNotification
|
||||
from .v2_all import ThreadGoalUpdatedNotification
|
||||
from .v2_all import ThreadNameUpdatedNotification
|
||||
from .v2_all import ThreadPredictionUpdatedNotification
|
||||
from .v2_all import ThreadProjectUpdatedNotification
|
||||
from .v2_all import ThreadQueueChangedNotification
|
||||
from .v2_all import ThreadReadStateChangedNotification
|
||||
from .v2_all import ThreadRealtimeClosedNotification
|
||||
from .v2_all import ThreadRealtimeErrorNotification
|
||||
from .v2_all import ThreadRealtimeItemAddedNotification
|
||||
from .v2_all import ThreadRealtimeItemCompletedNotification
|
||||
from .v2_all import ThreadRealtimeItemStartedNotification
|
||||
from .v2_all import ThreadRealtimeItemTranscriptDeltaNotification
|
||||
from .v2_all import ThreadRealtimeOutputAudioDeltaNotification
|
||||
from .v2_all import ThreadRealtimeSdpNotification
|
||||
from .v2_all import ThreadRealtimeStartedNotification
|
||||
from .v2_all import ThreadRealtimeTranscriptDeltaNotification
|
||||
from .v2_all import ThreadRealtimeTranscriptDoneNotification
|
||||
from .v2_all import ThreadRevertedNotification
|
||||
from .v2_all import ThreadSectionChangedNotification
|
||||
from .v2_all import ThreadSettingsUpdatedNotification
|
||||
from .v2_all import ThreadStartedNotification
|
||||
from .v2_all import ThreadStatusChangedNotification
|
||||
from .v2_all import ThreadTokenUsageUpdatedNotification
|
||||
from .v2_all import ThreadUnarchivedNotification
|
||||
from .v2_all import TurnCompletedNotification
|
||||
from .v2_all import TurnDiffUpdatedNotification
|
||||
from .v2_all import TurnModerationMetadataNotification
|
||||
from .v2_all import TurnPlanUpdatedNotification
|
||||
from .v2_all import TurnStartedNotification
|
||||
from .v2_all import WarningNotification
|
||||
from .v2_all import WindowsSandboxSetupCompletedNotification
|
||||
from .v2_all import WindowsWorldWritableWarningNotification
|
||||
|
||||
KnownNotificationPayload: TypeAlias = (
|
||||
AccountLoginCompletedNotification
|
||||
| AccountRateLimitsUpdatedNotification
|
||||
| AccountUpdatedNotification
|
||||
| AgentMessageDeltaNotification
|
||||
| AppListUpdatedNotification
|
||||
| AuthRecoveryNotification
|
||||
| CommandExecOutputDeltaNotification
|
||||
| CommandExecutionOutputDeltaNotification
|
||||
| ConfigWarningNotification
|
||||
| ContextCompactedNotification
|
||||
| DeprecationNoticeNotification
|
||||
| EnvironmentConnectionNotification
|
||||
| ErrorNotification
|
||||
| ExternalAgentConfigImportCompletedNotification
|
||||
| ExternalAgentConfigImportProgressNotification
|
||||
| FileChangeOutputDeltaNotification
|
||||
| FileChangePatchUpdatedNotification
|
||||
| FsChangedNotification
|
||||
| FuzzyFileSearchSessionCompletedNotification
|
||||
| FuzzyFileSearchSessionUpdatedNotification
|
||||
| GatewayOAuthChangedNotification
|
||||
| GuardianWarningNotification
|
||||
| HookCompletedNotification
|
||||
| HookStartedNotification
|
||||
| ItemCompletedNotification
|
||||
| ItemGuardianApprovalReviewCompletedNotification
|
||||
| ItemGuardianApprovalReviewStartedNotification
|
||||
| ItemStartedNotification
|
||||
| McpServerEventStreamNotification
|
||||
| McpServerOauthLoginCompletedNotification
|
||||
| McpServerStatusUpdatedNotification
|
||||
| McpToolCallProgressNotification
|
||||
| ModelReroutedNotification
|
||||
| ModelSafetyBufferingUpdatedNotification
|
||||
| ModelVerificationNotification
|
||||
| PlanDeltaNotification
|
||||
| ProcessExitedNotification
|
||||
| ProcessOutputDeltaNotification
|
||||
| ProjectChangedNotification
|
||||
| ReasoningSummaryPartAddedNotification
|
||||
| ReasoningSummaryTextDeltaNotification
|
||||
| ReasoningTextDeltaNotification
|
||||
| RemoteControlStatusChangedNotification
|
||||
| ServerRequestResolvedNotification
|
||||
| SkillsChangedNotification
|
||||
| StrictReviewRequiredNotification
|
||||
| TerminalInteractionNotification
|
||||
| ThreadArchivedNotification
|
||||
| ThreadAttachmentUpdatedNotification
|
||||
| ThreadClosedNotification
|
||||
| ThreadDeletedNotification
|
||||
| ThreadGoalClearedNotification
|
||||
| ThreadGoalUpdatedNotification
|
||||
| ThreadNameUpdatedNotification
|
||||
| ThreadPredictionUpdatedNotification
|
||||
| ThreadProjectUpdatedNotification
|
||||
| ThreadQueueChangedNotification
|
||||
| ThreadReadStateChangedNotification
|
||||
| ThreadRealtimeClosedNotification
|
||||
| ThreadRealtimeErrorNotification
|
||||
| ThreadRealtimeItemAddedNotification
|
||||
| ThreadRealtimeItemCompletedNotification
|
||||
| ThreadRealtimeItemStartedNotification
|
||||
| ThreadRealtimeItemTranscriptDeltaNotification
|
||||
| ThreadRealtimeOutputAudioDeltaNotification
|
||||
| ThreadRealtimeSdpNotification
|
||||
| ThreadRealtimeStartedNotification
|
||||
| ThreadRealtimeTranscriptDeltaNotification
|
||||
| ThreadRealtimeTranscriptDoneNotification
|
||||
| ThreadRevertedNotification
|
||||
| ThreadSectionChangedNotification
|
||||
| ThreadSettingsUpdatedNotification
|
||||
| ThreadStartedNotification
|
||||
| ThreadStatusChangedNotification
|
||||
| ThreadTokenUsageUpdatedNotification
|
||||
| ThreadUnarchivedNotification
|
||||
| TurnCompletedNotification
|
||||
| TurnDiffUpdatedNotification
|
||||
| TurnModerationMetadataNotification
|
||||
| TurnPlanUpdatedNotification
|
||||
| TurnStartedNotification
|
||||
| WarningNotification
|
||||
| WindowsSandboxSetupCompletedNotification
|
||||
| WindowsWorldWritableWarningNotification
|
||||
)
|
||||
|
||||
NOTIFICATION_MODELS: dict[str, type[KnownNotificationPayload]] = {
|
||||
"account/gatewayOAuth/changed": GatewayOAuthChangedNotification,
|
||||
"account/login/completed": AccountLoginCompletedNotification,
|
||||
"account/rateLimits/updated": AccountRateLimitsUpdatedNotification,
|
||||
"account/updated": AccountUpdatedNotification,
|
||||
"app/list/updated": AppListUpdatedNotification,
|
||||
"autoApprovalReview/strictReviewRequired": StrictReviewRequiredNotification,
|
||||
"command/exec/outputDelta": CommandExecOutputDeltaNotification,
|
||||
"configWarning": ConfigWarningNotification,
|
||||
"deprecationNotice": DeprecationNoticeNotification,
|
||||
"error": ErrorNotification,
|
||||
"externalAgentConfig/import/completed": ExternalAgentConfigImportCompletedNotification,
|
||||
"externalAgentConfig/import/progress": ExternalAgentConfigImportProgressNotification,
|
||||
"fs/changed": FsChangedNotification,
|
||||
"fuzzyFileSearch/sessionCompleted": FuzzyFileSearchSessionCompletedNotification,
|
||||
"fuzzyFileSearch/sessionUpdated": FuzzyFileSearchSessionUpdatedNotification,
|
||||
"guardianWarning": GuardianWarningNotification,
|
||||
"hook/completed": HookCompletedNotification,
|
||||
"hook/started": HookStartedNotification,
|
||||
"item/agentMessage/delta": AgentMessageDeltaNotification,
|
||||
"item/autoApprovalReview/completed": ItemGuardianApprovalReviewCompletedNotification,
|
||||
"item/autoApprovalReview/started": ItemGuardianApprovalReviewStartedNotification,
|
||||
"item/commandExecution/outputDelta": CommandExecutionOutputDeltaNotification,
|
||||
"item/commandExecution/terminalInteraction": TerminalInteractionNotification,
|
||||
"item/completed": ItemCompletedNotification,
|
||||
"item/fileChange/outputDelta": FileChangeOutputDeltaNotification,
|
||||
"item/fileChange/patchUpdated": FileChangePatchUpdatedNotification,
|
||||
"item/mcpToolCall/progress": McpToolCallProgressNotification,
|
||||
"item/plan/delta": PlanDeltaNotification,
|
||||
"item/reasoning/summaryPartAdded": ReasoningSummaryPartAddedNotification,
|
||||
"item/reasoning/summaryTextDelta": ReasoningSummaryTextDeltaNotification,
|
||||
"item/reasoning/textDelta": ReasoningTextDeltaNotification,
|
||||
"item/started": ItemStartedNotification,
|
||||
"mcpServer/event/stream/notification": McpServerEventStreamNotification,
|
||||
"mcpServer/oauthLogin/completed": McpServerOauthLoginCompletedNotification,
|
||||
"mcpServer/startupStatus/updated": McpServerStatusUpdatedNotification,
|
||||
"model/rerouted": ModelReroutedNotification,
|
||||
"model/safetyBuffering/updated": ModelSafetyBufferingUpdatedNotification,
|
||||
"model/verification": ModelVerificationNotification,
|
||||
"modelProvider/authRecoveryCompleted": AuthRecoveryNotification,
|
||||
"modelProvider/authRecoveryStarted": AuthRecoveryNotification,
|
||||
"process/exited": ProcessExitedNotification,
|
||||
"process/outputDelta": ProcessOutputDeltaNotification,
|
||||
"project/changed": ProjectChangedNotification,
|
||||
"remoteControl/status/changed": RemoteControlStatusChangedNotification,
|
||||
"serverRequest/resolved": ServerRequestResolvedNotification,
|
||||
"skills/changed": SkillsChangedNotification,
|
||||
"thread/archived": ThreadArchivedNotification,
|
||||
"thread/attachment/updated": ThreadAttachmentUpdatedNotification,
|
||||
"thread/closed": ThreadClosedNotification,
|
||||
"thread/compacted": ContextCompactedNotification,
|
||||
"thread/deleted": ThreadDeletedNotification,
|
||||
"thread/environment/connected": EnvironmentConnectionNotification,
|
||||
"thread/environment/disconnected": EnvironmentConnectionNotification,
|
||||
"thread/goal/cleared": ThreadGoalClearedNotification,
|
||||
"thread/goal/updated": ThreadGoalUpdatedNotification,
|
||||
"thread/name/updated": ThreadNameUpdatedNotification,
|
||||
"thread/prediction/updated": ThreadPredictionUpdatedNotification,
|
||||
"thread/project/updated": ThreadProjectUpdatedNotification,
|
||||
"thread/queue/changed": ThreadQueueChangedNotification,
|
||||
"thread/readState/changed": ThreadReadStateChangedNotification,
|
||||
"thread/realtime/closed": ThreadRealtimeClosedNotification,
|
||||
"thread/realtime/error": ThreadRealtimeErrorNotification,
|
||||
"thread/realtime/item/completed": ThreadRealtimeItemCompletedNotification,
|
||||
"thread/realtime/item/started": ThreadRealtimeItemStartedNotification,
|
||||
"thread/realtime/item/transcript/delta": ThreadRealtimeItemTranscriptDeltaNotification,
|
||||
"thread/realtime/itemAdded": ThreadRealtimeItemAddedNotification,
|
||||
"thread/realtime/outputAudio/delta": ThreadRealtimeOutputAudioDeltaNotification,
|
||||
"thread/realtime/sdp": ThreadRealtimeSdpNotification,
|
||||
"thread/realtime/started": ThreadRealtimeStartedNotification,
|
||||
"thread/realtime/transcript/delta": ThreadRealtimeTranscriptDeltaNotification,
|
||||
"thread/realtime/transcript/done": ThreadRealtimeTranscriptDoneNotification,
|
||||
"thread/reverted": ThreadRevertedNotification,
|
||||
"thread/section/changed": ThreadSectionChangedNotification,
|
||||
"thread/settings/updated": ThreadSettingsUpdatedNotification,
|
||||
"thread/started": ThreadStartedNotification,
|
||||
"thread/status/changed": ThreadStatusChangedNotification,
|
||||
"thread/tokenUsage/updated": ThreadTokenUsageUpdatedNotification,
|
||||
"thread/unarchived": ThreadUnarchivedNotification,
|
||||
"turn/completed": TurnCompletedNotification,
|
||||
"turn/diff/updated": TurnDiffUpdatedNotification,
|
||||
"turn/moderationMetadata": TurnModerationMetadataNotification,
|
||||
"turn/plan/updated": TurnPlanUpdatedNotification,
|
||||
"turn/started": TurnStartedNotification,
|
||||
"warning": WarningNotification,
|
||||
"windows/worldWritableWarning": WindowsWorldWritableWarningNotification,
|
||||
"windowsSandbox/setupCompleted": WindowsSandboxSetupCompletedNotification,
|
||||
}
|
||||
|
||||
DIRECT_TURN_ID_NOTIFICATION_TYPES: tuple[type[BaseModel], ...] = (
|
||||
AgentMessageDeltaNotification,
|
||||
AuthRecoveryNotification,
|
||||
CommandExecutionOutputDeltaNotification,
|
||||
ContextCompactedNotification,
|
||||
ErrorNotification,
|
||||
FileChangeOutputDeltaNotification,
|
||||
FileChangePatchUpdatedNotification,
|
||||
HookCompletedNotification,
|
||||
HookStartedNotification,
|
||||
ItemCompletedNotification,
|
||||
ItemGuardianApprovalReviewCompletedNotification,
|
||||
ItemGuardianApprovalReviewStartedNotification,
|
||||
ItemStartedNotification,
|
||||
McpToolCallProgressNotification,
|
||||
ModelReroutedNotification,
|
||||
ModelSafetyBufferingUpdatedNotification,
|
||||
ModelVerificationNotification,
|
||||
PlanDeltaNotification,
|
||||
ReasoningSummaryPartAddedNotification,
|
||||
ReasoningSummaryTextDeltaNotification,
|
||||
ReasoningTextDeltaNotification,
|
||||
StrictReviewRequiredNotification,
|
||||
TerminalInteractionNotification,
|
||||
ThreadGoalUpdatedNotification,
|
||||
ThreadTokenUsageUpdatedNotification,
|
||||
TurnDiffUpdatedNotification,
|
||||
TurnModerationMetadataNotification,
|
||||
TurnPlanUpdatedNotification,
|
||||
)
|
||||
|
||||
NESTED_TURN_NOTIFICATION_TYPES: tuple[type[BaseModel], ...] = (
|
||||
TurnCompletedNotification,
|
||||
TurnStartedNotification,
|
||||
)
|
||||
|
||||
|
||||
def notification_turn_id(payload: BaseModel) -> str | None:
|
||||
"""Return the turn id carried by generated notification payload metadata."""
|
||||
if isinstance(payload, DIRECT_TURN_ID_NOTIFICATION_TYPES):
|
||||
return payload.turn_id if isinstance(payload.turn_id, str) else None
|
||||
if isinstance(payload, NESTED_TURN_NOTIFICATION_TYPES):
|
||||
return payload.turn.id
|
||||
return None
|
||||
14242
sdk/python/src/openai_codex/generated/v2_all.py
Normal file
14242
sdk/python/src/openai_codex/generated/v2_all.py
Normal file
File diff suppressed because it is too large
Load Diff
76
sdk/python/src/openai_codex/models.py
Normal file
76
sdk/python/src/openai_codex/models.py
Normal file
@@ -0,0 +1,76 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import TypeAlias
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .generated.notification_registry import KnownNotificationPayload as _KnownNotificationPayload
|
||||
|
||||
# Preserve the notification names previously importable from this module.
|
||||
from .generated.v2_all import (
|
||||
AccountLoginCompletedNotification as AccountLoginCompletedNotification,
|
||||
AccountRateLimitsUpdatedNotification as AccountRateLimitsUpdatedNotification,
|
||||
AccountUpdatedNotification as AccountUpdatedNotification,
|
||||
AgentMessageDeltaNotification as AgentMessageDeltaNotification,
|
||||
AppListUpdatedNotification as AppListUpdatedNotification,
|
||||
CommandExecutionOutputDeltaNotification as CommandExecutionOutputDeltaNotification,
|
||||
ConfigWarningNotification as ConfigWarningNotification,
|
||||
ContextCompactedNotification as ContextCompactedNotification,
|
||||
DeprecationNoticeNotification as DeprecationNoticeNotification,
|
||||
ErrorNotification as ErrorNotification,
|
||||
FileChangeOutputDeltaNotification as FileChangeOutputDeltaNotification,
|
||||
ItemCompletedNotification as ItemCompletedNotification,
|
||||
ItemStartedNotification as ItemStartedNotification,
|
||||
McpServerOauthLoginCompletedNotification as McpServerOauthLoginCompletedNotification,
|
||||
McpToolCallProgressNotification as McpToolCallProgressNotification,
|
||||
PlanDeltaNotification as PlanDeltaNotification,
|
||||
RawResponseItemCompletedNotification as RawResponseItemCompletedNotification,
|
||||
ReasoningSummaryPartAddedNotification as ReasoningSummaryPartAddedNotification,
|
||||
ReasoningSummaryTextDeltaNotification as ReasoningSummaryTextDeltaNotification,
|
||||
ReasoningTextDeltaNotification as ReasoningTextDeltaNotification,
|
||||
TerminalInteractionNotification as TerminalInteractionNotification,
|
||||
ThreadGoalClearedNotification as ThreadGoalClearedNotification,
|
||||
ThreadGoalUpdatedNotification as ThreadGoalUpdatedNotification,
|
||||
ThreadNameUpdatedNotification as ThreadNameUpdatedNotification,
|
||||
ThreadStartedNotification as ThreadStartedNotification,
|
||||
ThreadTokenUsageUpdatedNotification as ThreadTokenUsageUpdatedNotification,
|
||||
TurnCompletedNotification as TurnCompletedNotification,
|
||||
TurnDiffUpdatedNotification as TurnDiffUpdatedNotification,
|
||||
TurnPlanUpdatedNotification as TurnPlanUpdatedNotification,
|
||||
TurnStartedNotification as TurnStartedNotification,
|
||||
WindowsWorldWritableWarningNotification as WindowsWorldWritableWarningNotification,
|
||||
)
|
||||
|
||||
JsonScalar: TypeAlias = str | int | float | bool | None
|
||||
JsonValue: TypeAlias = JsonScalar | dict[str, "JsonValue"] | list["JsonValue"]
|
||||
JsonObject: TypeAlias = dict[str, JsonValue]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class UnknownNotification:
|
||||
params: JsonObject
|
||||
|
||||
|
||||
# Preserve the existing raw-item type, which app-server omits from its notification schema.
|
||||
NotificationPayload: TypeAlias = (
|
||||
_KnownNotificationPayload | RawResponseItemCompletedNotification | UnknownNotification
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Notification:
|
||||
method: str
|
||||
payload: NotificationPayload
|
||||
|
||||
|
||||
class ServerInfo(BaseModel):
|
||||
name: str | None = None
|
||||
version: str | None = None
|
||||
|
||||
|
||||
class InitializeResponse(BaseModel):
|
||||
serverInfo: ServerInfo | None = None
|
||||
userAgent: str | None = None
|
||||
platformFamily: str | None = None
|
||||
platformOs: str | None = None
|
||||
0
sdk/python/src/openai_codex/py.typed
Normal file
0
sdk/python/src/openai_codex/py.typed
Normal file
41
sdk/python/src/openai_codex/retry.py
Normal file
41
sdk/python/src/openai_codex/retry.py
Normal file
@@ -0,0 +1,41 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import time
|
||||
from typing import Callable, TypeVar
|
||||
|
||||
from .errors import is_retryable_error
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
def retry_on_overload(
|
||||
op: Callable[[], T],
|
||||
*,
|
||||
max_attempts: int = 3,
|
||||
initial_delay_s: float = 0.25,
|
||||
max_delay_s: float = 2.0,
|
||||
jitter_ratio: float = 0.2,
|
||||
) -> T:
|
||||
"""Retry helper for transient server-overload errors."""
|
||||
|
||||
if max_attempts < 1:
|
||||
raise ValueError("max_attempts must be >= 1")
|
||||
|
||||
delay = initial_delay_s
|
||||
attempt = 0
|
||||
while True:
|
||||
attempt += 1
|
||||
try:
|
||||
return op()
|
||||
except Exception as exc:
|
||||
if attempt >= max_attempts:
|
||||
raise
|
||||
if not is_retryable_error(exc):
|
||||
raise
|
||||
|
||||
jitter = delay * jitter_ratio
|
||||
sleep_for = min(max_delay_s, delay) + random.uniform(-jitter, jitter)
|
||||
if sleep_for > 0:
|
||||
time.sleep(sleep_for)
|
||||
delay = min(max_delay_s, delay * 2)
|
||||
81
sdk/python/src/openai_codex/types.py
Normal file
81
sdk/python/src/openai_codex/types.py
Normal file
@@ -0,0 +1,81 @@
|
||||
"""Public Codex protocol model exports for type annotations and matching."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .generated.v2_all import (
|
||||
Account,
|
||||
AccountLoginCompletedNotification,
|
||||
ApprovalsReviewer,
|
||||
AskForApproval,
|
||||
CancelLoginAccountResponse,
|
||||
CancelLoginAccountStatus,
|
||||
GetAccountResponse,
|
||||
ModelListResponse,
|
||||
Personality,
|
||||
PlanType,
|
||||
ReasoningEffort,
|
||||
ReasoningSummary,
|
||||
SandboxMode,
|
||||
SandboxPolicy,
|
||||
SortDirection,
|
||||
ThreadArchiveResponse,
|
||||
ThreadCompactStartResponse,
|
||||
ThreadItem,
|
||||
ThreadListCwdFilter,
|
||||
ThreadListResponse,
|
||||
ThreadReadResponse,
|
||||
ThreadSetNameResponse,
|
||||
ThreadSortKey,
|
||||
ThreadSource,
|
||||
ThreadSourceKind,
|
||||
ThreadStartSource,
|
||||
ThreadTokenUsage,
|
||||
ThreadTokenUsageUpdatedNotification,
|
||||
Turn,
|
||||
TurnCompletedNotification,
|
||||
TurnError,
|
||||
TurnInterruptResponse,
|
||||
TurnStatus,
|
||||
TurnSteerResponse,
|
||||
)
|
||||
from .models import InitializeResponse, JsonObject, Notification
|
||||
|
||||
__all__ = [
|
||||
"Account",
|
||||
"AccountLoginCompletedNotification",
|
||||
"ApprovalsReviewer",
|
||||
"AskForApproval",
|
||||
"CancelLoginAccountResponse",
|
||||
"CancelLoginAccountStatus",
|
||||
"GetAccountResponse",
|
||||
"InitializeResponse",
|
||||
"JsonObject",
|
||||
"ModelListResponse",
|
||||
"Notification",
|
||||
"Personality",
|
||||
"PlanType",
|
||||
"ReasoningEffort",
|
||||
"ReasoningSummary",
|
||||
"SandboxMode",
|
||||
"SandboxPolicy",
|
||||
"SortDirection",
|
||||
"ThreadArchiveResponse",
|
||||
"ThreadCompactStartResponse",
|
||||
"ThreadItem",
|
||||
"ThreadListCwdFilter",
|
||||
"ThreadListResponse",
|
||||
"ThreadReadResponse",
|
||||
"ThreadSetNameResponse",
|
||||
"ThreadSortKey",
|
||||
"ThreadSource",
|
||||
"ThreadSourceKind",
|
||||
"ThreadStartSource",
|
||||
"ThreadTokenUsage",
|
||||
"ThreadTokenUsageUpdatedNotification",
|
||||
"Turn",
|
||||
"TurnCompletedNotification",
|
||||
"TurnError",
|
||||
"TurnInterruptResponse",
|
||||
"TurnStatus",
|
||||
"TurnSteerResponse",
|
||||
]
|
||||
Reference in New Issue
Block a user