Base: codex-main originale (prima del fork aKode)
This commit is contained in:
462
sdk/python/tests/app_server_harness.py
Normal file
462
sdk/python/tests/app_server_harness.py
Normal file
@@ -0,0 +1,462 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from openai_codex import CodexConfig
|
||||
|
||||
Json = dict[str, Any]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CapturedResponsesRequest:
|
||||
"""Recorded request sent by app-server to the mock Responses API."""
|
||||
|
||||
method: str
|
||||
path: str
|
||||
headers: dict[str, str]
|
||||
body: bytes
|
||||
|
||||
def body_json(self) -> Json:
|
||||
"""Decode the request body as JSON."""
|
||||
return json.loads(self.body.decode("utf-8"))
|
||||
|
||||
def input(self) -> list[Json]:
|
||||
"""Return the Responses API input array from the request."""
|
||||
value = self.body_json().get("input")
|
||||
if not isinstance(value, list):
|
||||
raise AssertionError(f"expected input list, got {value!r}")
|
||||
return value
|
||||
|
||||
def message_input_texts(self, role: str) -> list[str]:
|
||||
"""Return all input_text strings for message inputs matching one role."""
|
||||
texts: list[str] = []
|
||||
for item in self.input():
|
||||
if item.get("type") != "message" or item.get("role") != role:
|
||||
continue
|
||||
content = item.get("content")
|
||||
if isinstance(content, str):
|
||||
texts.append(content)
|
||||
continue
|
||||
if not isinstance(content, list):
|
||||
continue
|
||||
for span in content:
|
||||
if isinstance(span, dict) and span.get("type") == "input_text":
|
||||
text = span.get("text")
|
||||
if isinstance(text, str):
|
||||
texts.append(text)
|
||||
return texts
|
||||
|
||||
def message_content_items(self, role: str) -> list[Json]:
|
||||
"""Return structured content items for message inputs matching one role."""
|
||||
items: list[Json] = []
|
||||
for item in self.input():
|
||||
if item.get("type") != "message" or item.get("role") != role:
|
||||
continue
|
||||
content = item.get("content")
|
||||
if not isinstance(content, list):
|
||||
continue
|
||||
items.extend(part for part in content if isinstance(part, dict))
|
||||
return items
|
||||
|
||||
def message_image_urls(self, role: str) -> list[str]:
|
||||
"""Return all input_image URLs for message inputs matching one role."""
|
||||
urls: list[str] = []
|
||||
for item in self.message_content_items(role):
|
||||
if item.get("type") != "input_image":
|
||||
continue
|
||||
image_url = item.get("image_url")
|
||||
if isinstance(image_url, str):
|
||||
urls.append(image_url)
|
||||
return urls
|
||||
|
||||
def header(self, name: str) -> str | None:
|
||||
"""Return a captured request header by case-insensitive name."""
|
||||
return self.headers.get(name.lower())
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MockSseResponse:
|
||||
"""One queued SSE response served by the mock Responses API."""
|
||||
|
||||
body: str
|
||||
delay_between_events_s: float = 0.0
|
||||
|
||||
def chunks(self) -> list[bytes]:
|
||||
"""Split an SSE body into event chunks while preserving framing."""
|
||||
chunks: list[bytes] = []
|
||||
for part in self.body.split("\n\n"):
|
||||
if not part:
|
||||
continue
|
||||
chunks.append(f"{part}\n\n".encode("utf-8"))
|
||||
return chunks
|
||||
|
||||
|
||||
class MockResponsesServer:
|
||||
"""Local HTTP server that records `/v1/responses` requests and returns SSE."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._responses: queue.Queue[MockSseResponse] = queue.Queue()
|
||||
self._requests: list[CapturedResponsesRequest] = []
|
||||
self._requests_lock = threading.Lock()
|
||||
self._server = _ResponsesHttpServer(("127.0.0.1", 0), _ResponsesHandler, self)
|
||||
self._thread = threading.Thread(
|
||||
target=self._server.serve_forever,
|
||||
name="mock-responses-api",
|
||||
daemon=True,
|
||||
)
|
||||
|
||||
def __enter__(self) -> MockResponsesServer:
|
||||
self._thread.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, _exc_type: object, _exc: object, _tb: object) -> None:
|
||||
self.close()
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
"""Return the base URL for app-server config."""
|
||||
host, port = self._server.server_address
|
||||
return f"http://{host}:{port}"
|
||||
|
||||
def close(self) -> None:
|
||||
"""Stop the background HTTP server thread."""
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
self._thread.join(timeout=2)
|
||||
|
||||
def enqueue_sse(
|
||||
self,
|
||||
body: str,
|
||||
*,
|
||||
delay_between_events_s: float = 0.0,
|
||||
) -> None:
|
||||
"""Queue one SSE body for the next `/v1/responses` request."""
|
||||
self._responses.put(
|
||||
MockSseResponse(
|
||||
body=body,
|
||||
delay_between_events_s=delay_between_events_s,
|
||||
)
|
||||
)
|
||||
|
||||
def enqueue_assistant_message(self, text: str, *, response_id: str = "resp-1") -> None:
|
||||
"""Queue a completed assistant-message model response."""
|
||||
self.enqueue_sse(
|
||||
sse(
|
||||
[
|
||||
ev_response_created(response_id),
|
||||
ev_assistant_message(f"msg-{response_id}", text),
|
||||
ev_completed(response_id),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
def requests(self) -> list[CapturedResponsesRequest]:
|
||||
"""Return all recorded Responses API requests."""
|
||||
with self._requests_lock:
|
||||
return list(self._requests)
|
||||
|
||||
def single_request(self) -> CapturedResponsesRequest:
|
||||
"""Return the only recorded request, failing if the count differs."""
|
||||
requests = self.requests()
|
||||
if len(requests) != 1:
|
||||
raise AssertionError(f"expected 1 request, got {len(requests)}")
|
||||
return requests[0]
|
||||
|
||||
def wait_for_requests(
|
||||
self,
|
||||
count: int,
|
||||
*,
|
||||
timeout_s: float = 5.0,
|
||||
) -> list[CapturedResponsesRequest]:
|
||||
"""Wait until at least `count` requests have been recorded."""
|
||||
deadline = time.monotonic() + timeout_s
|
||||
while time.monotonic() < deadline:
|
||||
requests = self.requests()
|
||||
if len(requests) >= count:
|
||||
return requests
|
||||
time.sleep(0.01)
|
||||
requests = self.requests()
|
||||
raise AssertionError(f"expected {count} requests, got {len(requests)}")
|
||||
|
||||
def _record_request(self, handler: BaseHTTPRequestHandler, body: bytes) -> None:
|
||||
"""Record one inbound HTTP request from app-server."""
|
||||
headers = {key.lower(): value for key, value in handler.headers.items()}
|
||||
request = CapturedResponsesRequest(
|
||||
method=handler.command,
|
||||
path=handler.path,
|
||||
headers=headers,
|
||||
body=body,
|
||||
)
|
||||
with self._requests_lock:
|
||||
self._requests.append(request)
|
||||
|
||||
def _next_response(self) -> MockSseResponse:
|
||||
"""Return the next queued SSE response or fail the HTTP request."""
|
||||
return self._responses.get_nowait()
|
||||
|
||||
|
||||
class AppServerHarness:
|
||||
"""Test fixture that points the checkout's app-server at MockResponsesServer."""
|
||||
|
||||
def __init__(self, tmp_path: Path, *, requires_openai_auth: bool = False) -> None:
|
||||
self.tmp_path = tmp_path
|
||||
self.codex_home = tmp_path / "codex-home"
|
||||
self.workspace = tmp_path / "workspace"
|
||||
self.requires_openai_auth = requires_openai_auth
|
||||
self.responses = MockResponsesServer()
|
||||
|
||||
def __enter__(self) -> AppServerHarness:
|
||||
self.codex_home.mkdir()
|
||||
self.workspace.mkdir()
|
||||
self.responses.__enter__()
|
||||
self._write_config()
|
||||
return self
|
||||
|
||||
def __exit__(self, _exc_type: object, _exc: object, _tb: object) -> None:
|
||||
self.responses.__exit__(_exc_type, _exc, _tb)
|
||||
shutil.rmtree(self.codex_home, ignore_errors=True)
|
||||
shutil.rmtree(self.workspace, ignore_errors=True)
|
||||
|
||||
def app_server_config(self) -> CodexConfig:
|
||||
"""Prefer the CI binary, then a local debug build, then the installed runtime."""
|
||||
binary_name = "codex.exe" if os.name == "nt" else "codex"
|
||||
debug_binary = Path(__file__).resolve().parents[3] / "codex-rs/target/debug" / binary_name
|
||||
codex_bin = os.environ.get("CODEX_EXEC_PATH")
|
||||
if codex_bin is None and debug_binary.is_file():
|
||||
codex_bin = str(debug_binary)
|
||||
return CodexConfig(
|
||||
codex_bin=codex_bin,
|
||||
cwd=str(self.workspace),
|
||||
env={
|
||||
"CODEX_HOME": str(self.codex_home),
|
||||
"CODEX_APP_SERVER_DISABLE_MANAGED_CONFIG": "1",
|
||||
"RUST_LOG": "warn",
|
||||
},
|
||||
)
|
||||
|
||||
def _write_config(self) -> None:
|
||||
"""Write config.toml that routes model calls to the mock server."""
|
||||
config_toml = self.codex_home / "config.toml"
|
||||
requires_openai_auth = "requires_openai_auth = true\n" if self.requires_openai_auth else ""
|
||||
config_toml.write_text(
|
||||
f"""
|
||||
model = "mock-model"
|
||||
approval_policy = "never"
|
||||
sandbox_mode = "read-only"
|
||||
|
||||
model_provider = "mock_provider"
|
||||
|
||||
[model_providers.mock_provider]
|
||||
name = "Mock provider for Python SDK tests"
|
||||
base_url = "{self.responses.url}/v1"
|
||||
wire_api = "responses"
|
||||
request_max_retries = 0
|
||||
stream_max_retries = 0
|
||||
{requires_openai_auth}
|
||||
""".lstrip()
|
||||
)
|
||||
|
||||
|
||||
class _ResponsesHttpServer(ThreadingHTTPServer):
|
||||
"""ThreadingHTTPServer carrying a reference to the owning mock."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
server_address: tuple[str, int],
|
||||
handler_class: type[BaseHTTPRequestHandler],
|
||||
mock: MockResponsesServer,
|
||||
) -> None:
|
||||
super().__init__(server_address, handler_class)
|
||||
self.mock = mock
|
||||
|
||||
|
||||
class _ResponsesHandler(BaseHTTPRequestHandler):
|
||||
"""HTTP handler for the subset of the Responses API used by SDK tests."""
|
||||
|
||||
server: _ResponsesHttpServer
|
||||
|
||||
def log_message(self, _format: str, *_args: object) -> None:
|
||||
"""Silence default stderr logging; pytest failures print captured requests."""
|
||||
return None
|
||||
|
||||
def do_GET(self) -> None:
|
||||
"""Serve a minimal `/v1/models` response if app-server asks for models."""
|
||||
if self.path.endswith("/v1/models") or self.path.endswith("/models"):
|
||||
self._send_json(
|
||||
{
|
||||
"object": "list",
|
||||
"data": [
|
||||
{
|
||||
"id": "mock-model",
|
||||
"object": "model",
|
||||
"created": 0,
|
||||
"owned_by": "openai",
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
return
|
||||
self.send_error(404, f"unexpected GET {self.path}")
|
||||
|
||||
def do_POST(self) -> None:
|
||||
"""Serve queued SSE responses for `/v1/responses` requests."""
|
||||
length = int(self.headers.get("content-length", "0"))
|
||||
body = self.rfile.read(length)
|
||||
if self.path.endswith("/analytics/codex/turn-costs"):
|
||||
# Optional cost probes are not model requests.
|
||||
self.send_error(404, "turn costs are unavailable for the mock provider")
|
||||
return
|
||||
self.server.mock._record_request(self, body)
|
||||
|
||||
if not (self.path.endswith("/v1/responses") or self.path.endswith("/responses")):
|
||||
self.send_error(404, f"unexpected POST {self.path}")
|
||||
return
|
||||
|
||||
try:
|
||||
response = self.server.mock._next_response()
|
||||
except queue.Empty:
|
||||
self.send_error(500, "no queued SSE response")
|
||||
return
|
||||
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "text/event-stream")
|
||||
self.end_headers()
|
||||
for chunk in response.chunks():
|
||||
self.wfile.write(chunk)
|
||||
self.wfile.flush()
|
||||
if response.delay_between_events_s:
|
||||
time.sleep(response.delay_between_events_s)
|
||||
|
||||
def _send_json(self, payload: Json) -> None:
|
||||
"""Write one JSON response."""
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "application/json")
|
||||
self.send_header("content-length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
def sse(events: list[Json]) -> str:
|
||||
"""Build an SSE body from Responses API event JSON objects."""
|
||||
chunks: list[str] = []
|
||||
for event in events:
|
||||
event_type = event["type"]
|
||||
chunks.append(f"event: {event_type}\ndata: {json.dumps(event)}\n")
|
||||
return "\n".join(chunks) + "\n"
|
||||
|
||||
|
||||
def ev_response_created(response_id: str) -> Json:
|
||||
"""Return a minimal `response.created` event."""
|
||||
return {"type": "response.created", "response": {"id": response_id}}
|
||||
|
||||
|
||||
def ev_completed(response_id: str) -> Json:
|
||||
"""Return a minimal `response.completed` event with usage."""
|
||||
return {
|
||||
"type": "response.completed",
|
||||
"response": {
|
||||
"id": response_id,
|
||||
"usage": {
|
||||
"input_tokens": 1,
|
||||
"input_tokens_details": None,
|
||||
"output_tokens": 1,
|
||||
"output_tokens_details": None,
|
||||
"total_tokens": 2,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def ev_completed_with_usage(
|
||||
response_id: str,
|
||||
*,
|
||||
input_tokens: int,
|
||||
cached_input_tokens: int,
|
||||
output_tokens: int,
|
||||
reasoning_output_tokens: int,
|
||||
total_tokens: int,
|
||||
) -> Json:
|
||||
"""Return `response.completed` with explicit token accounting."""
|
||||
return {
|
||||
"type": "response.completed",
|
||||
"response": {
|
||||
"id": response_id,
|
||||
"usage": {
|
||||
"input_tokens": input_tokens,
|
||||
"input_tokens_details": {"cached_tokens": cached_input_tokens},
|
||||
"output_tokens": output_tokens,
|
||||
"output_tokens_details": {
|
||||
"reasoning_tokens": reasoning_output_tokens,
|
||||
},
|
||||
"total_tokens": total_tokens,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def ev_assistant_message(item_id: str, text: str) -> Json:
|
||||
"""Return a completed assistant message output item."""
|
||||
return {
|
||||
"type": "response.output_item.done",
|
||||
"item": {
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"id": item_id,
|
||||
"content": [{"type": "output_text", "text": text}],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def ev_message_item_added(item_id: str, text: str = "") -> Json:
|
||||
"""Return an assistant message added event before streaming deltas."""
|
||||
return {
|
||||
"type": "response.output_item.added",
|
||||
"item": {
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"id": item_id,
|
||||
"content": [{"type": "output_text", "text": text}],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def ev_output_text_delta(delta: str) -> Json:
|
||||
"""Return an output-text delta event."""
|
||||
return {
|
||||
"type": "response.output_text.delta",
|
||||
"delta": delta,
|
||||
}
|
||||
|
||||
|
||||
def ev_function_call(call_id: str, name: str, arguments: str) -> Json:
|
||||
"""Return a completed function-call output item."""
|
||||
return {
|
||||
"type": "response.output_item.done",
|
||||
"item": {
|
||||
"type": "function_call",
|
||||
"call_id": call_id,
|
||||
"name": name,
|
||||
"arguments": arguments,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def ev_failed(response_id: str, message: str) -> Json:
|
||||
"""Return a failed model response event."""
|
||||
return {
|
||||
"type": "response.failed",
|
||||
"response": {
|
||||
"id": response_id,
|
||||
"error": {"code": "server_error", "message": message},
|
||||
},
|
||||
}
|
||||
167
sdk/python/tests/app_server_helpers.py
Normal file
167
sdk/python/tests/app_server_helpers.py
Normal file
@@ -0,0 +1,167 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncIterator, Iterable, Iterator
|
||||
from typing import Any
|
||||
|
||||
from app_server_harness import (
|
||||
ev_assistant_message,
|
||||
ev_completed,
|
||||
ev_message_item_added,
|
||||
ev_output_text_delta,
|
||||
ev_response_created,
|
||||
sse,
|
||||
)
|
||||
|
||||
from openai_codex.generated.v2_all import (
|
||||
AgentMessageDeltaNotification,
|
||||
ItemCompletedNotification,
|
||||
MessagePhase,
|
||||
)
|
||||
from openai_codex.models import Notification
|
||||
|
||||
TINY_PNG_BYTES = bytes(
|
||||
[
|
||||
137,
|
||||
80,
|
||||
78,
|
||||
71,
|
||||
13,
|
||||
10,
|
||||
26,
|
||||
10,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
13,
|
||||
73,
|
||||
72,
|
||||
68,
|
||||
82,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
8,
|
||||
6,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
31,
|
||||
21,
|
||||
196,
|
||||
137,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
11,
|
||||
73,
|
||||
68,
|
||||
65,
|
||||
84,
|
||||
120,
|
||||
156,
|
||||
99,
|
||||
96,
|
||||
0,
|
||||
2,
|
||||
0,
|
||||
0,
|
||||
5,
|
||||
0,
|
||||
1,
|
||||
122,
|
||||
94,
|
||||
171,
|
||||
63,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
73,
|
||||
69,
|
||||
78,
|
||||
68,
|
||||
174,
|
||||
66,
|
||||
96,
|
||||
130,
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def response_approval_policy(response: Any) -> str:
|
||||
"""Return serialized approvalPolicy from a generated thread response."""
|
||||
return response.model_dump(by_alias=True, mode="json")["approvalPolicy"]
|
||||
|
||||
|
||||
def agent_message_texts(events: list[Notification]) -> list[str]:
|
||||
"""Extract completed agent-message text from SDK notifications."""
|
||||
texts: list[str] = []
|
||||
for event in events:
|
||||
if not isinstance(event.payload, ItemCompletedNotification):
|
||||
continue
|
||||
item = event.payload.item.root
|
||||
if item.type == "agentMessage":
|
||||
texts.append(item.text)
|
||||
return texts
|
||||
|
||||
|
||||
def agent_message_texts_from_items(items: Iterable[Any]) -> list[str]:
|
||||
"""Extract agent-message text from completed turn result items."""
|
||||
texts: list[str] = []
|
||||
for item in items:
|
||||
root = item.root
|
||||
if root.type == "agentMessage":
|
||||
texts.append(root.text)
|
||||
return texts
|
||||
|
||||
|
||||
def next_sync_delta(stream: Iterator[Notification]) -> str:
|
||||
"""Advance a sync turn stream until the next agent-message text delta."""
|
||||
for event in stream:
|
||||
if isinstance(event.payload, AgentMessageDeltaNotification):
|
||||
return event.payload.delta
|
||||
raise AssertionError("stream completed before an agent-message delta")
|
||||
|
||||
|
||||
async def next_async_delta(stream: AsyncIterator[Notification]) -> str:
|
||||
"""Advance an async turn stream until the next agent-message text delta."""
|
||||
async for event in stream:
|
||||
if isinstance(event.payload, AgentMessageDeltaNotification):
|
||||
return event.payload.delta
|
||||
raise AssertionError("stream completed before an agent-message delta")
|
||||
|
||||
|
||||
def streaming_response(response_id: str, item_id: str, parts: list[str]) -> str:
|
||||
"""Build an SSE stream with text deltas and a final assistant message."""
|
||||
return sse(
|
||||
[
|
||||
ev_response_created(response_id),
|
||||
ev_message_item_added(item_id),
|
||||
*[ev_output_text_delta(part) for part in parts],
|
||||
ev_assistant_message(item_id, "".join(parts)),
|
||||
ev_completed(response_id),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def assistant_message_with_phase(
|
||||
item_id: str,
|
||||
text: str,
|
||||
phase: MessagePhase,
|
||||
) -> dict[str, Any]:
|
||||
"""Build an assistant message event carrying app-server phase metadata."""
|
||||
event = ev_assistant_message(item_id, text)
|
||||
event["item"] = {**event["item"], "phase": phase.value}
|
||||
return event
|
||||
|
||||
|
||||
def request_kind(request_path: str) -> str:
|
||||
"""Classify captured mock-server request paths for compact assertions."""
|
||||
if request_path.endswith("/responses"):
|
||||
return "responses"
|
||||
return request_path
|
||||
16
sdk/python/tests/conftest.py
Normal file
16
sdk/python/tests/conftest.py
Normal file
@@ -0,0 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SRC = ROOT / "src"
|
||||
|
||||
src_str = str(SRC)
|
||||
if src_str in sys.path:
|
||||
sys.path.remove(src_str)
|
||||
sys.path.insert(0, src_str)
|
||||
|
||||
for module_name in list(sys.modules):
|
||||
if module_name == "openai_codex" or module_name.startswith("openai_codex."):
|
||||
sys.modules.pop(module_name)
|
||||
39
sdk/python/tests/installed_sdk_smoke.py
Normal file
39
sdk/python/tests/installed_sdk_smoke.py
Normal file
@@ -0,0 +1,39 @@
|
||||
"""Exercise a built SDK's default runtime in an otherwise isolated environment."""
|
||||
|
||||
from dataclasses import replace
|
||||
from importlib.metadata import distribution, version
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from app_server_harness import AppServerHarness
|
||||
|
||||
import openai_codex
|
||||
from openai_codex import Codex
|
||||
|
||||
|
||||
def main() -> None:
|
||||
installed_root = Path(distribution("openai-codex").locate_file("")).resolve()
|
||||
assert Path(openai_codex.__file__).resolve().is_relative_to(installed_root), (
|
||||
"The smoke test must import the installed SDK, not the source checkout"
|
||||
)
|
||||
|
||||
with TemporaryDirectory() as directory, AppServerHarness(Path(directory)) as harness:
|
||||
harness.responses.enqueue_assistant_message("Installed SDK works")
|
||||
config = replace(harness.app_server_config(), codex_bin=None)
|
||||
with Codex(config=config) as codex:
|
||||
thread = codex.thread_start()
|
||||
result = thread.run(
|
||||
"Check the installed SDK", turn_service_tier="default", source="automation"
|
||||
)
|
||||
codex.thread_resume(thread.id, include_turns=False)
|
||||
codex.thread_fork(thread.id, include_turns=True)
|
||||
assert result.final_response == "Installed SDK works"
|
||||
assert harness.responses.single_request().message_input_texts("user")[-1:] == [
|
||||
"Check the installed SDK"
|
||||
]
|
||||
|
||||
print(f"Installed SDK passed with CLI runtime {version('openai-codex-cli-bin')}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
3
sdk/python/tests/requirements-uv.txt
Normal file
3
sdk/python/tests/requirements-uv.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
# Verify the Linux x86-64 wheel even if the test image's pip trusts a stale CA.
|
||||
uv==0.13.5 \
|
||||
--hash=sha256:fa8d26e08e34c29c0c4e820cf3181757086d547240b4f4d31ff1d8bd810ca946
|
||||
208
sdk/python/tests/test_app_server_approvals.py
Normal file
208
sdk/python/tests/test_app_server_approvals.py
Normal file
@@ -0,0 +1,208 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from app_server_harness import AppServerHarness
|
||||
from app_server_helpers import response_approval_policy
|
||||
|
||||
from openai_codex import ApprovalMode, AsyncCodex, Codex
|
||||
from openai_codex.generated.v2_all import AskForApprovalValue, ThreadResumeParams
|
||||
|
||||
|
||||
def test_thread_resume_inherits_deny_all_approval_mode(tmp_path) -> None:
|
||||
"""Resuming a thread should preserve its stored approval mode."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message("source seeded", response_id="resume-mode")
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
source = codex.thread_start(approval_mode=ApprovalMode.deny_all)
|
||||
result = source.run("seed the source rollout")
|
||||
resumed = codex.thread_resume(source.id)
|
||||
resumed_state = codex._client.thread_resume( # noqa: SLF001
|
||||
resumed.id,
|
||||
ThreadResumeParams(thread_id=resumed.id),
|
||||
)
|
||||
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"resumed_policy": response_approval_policy(resumed_state),
|
||||
} == {
|
||||
"final_response": "source seeded",
|
||||
"resumed_policy": AskForApprovalValue.never.value,
|
||||
}
|
||||
|
||||
|
||||
def test_thread_fork_inherits_deny_all_approval_mode(tmp_path) -> None:
|
||||
"""Forking without an override should preserve the source approval mode."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message("source seeded", response_id="fork-mode")
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
source = codex.thread_start(approval_mode=ApprovalMode.deny_all)
|
||||
result = source.run("seed the source rollout")
|
||||
forked = codex.thread_fork(source.id)
|
||||
forked_state = codex._client.thread_resume( # noqa: SLF001
|
||||
forked.id,
|
||||
ThreadResumeParams(thread_id=forked.id),
|
||||
)
|
||||
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"forked_is_distinct": forked.id != source.id,
|
||||
"forked_policy": response_approval_policy(forked_state),
|
||||
} == {
|
||||
"final_response": "source seeded",
|
||||
"forked_is_distinct": True,
|
||||
"forked_policy": AskForApprovalValue.never.value,
|
||||
}
|
||||
|
||||
|
||||
def test_thread_fork_can_override_approval_mode(tmp_path) -> None:
|
||||
"""Forking with an explicit approval mode should send an override."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"source seeded",
|
||||
response_id="fork-override-mode",
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
source = codex.thread_start(approval_mode=ApprovalMode.deny_all)
|
||||
result = source.run("seed the source rollout")
|
||||
forked = codex.thread_fork(
|
||||
source.id,
|
||||
approval_mode=ApprovalMode.auto_review,
|
||||
)
|
||||
forked_state = codex._client.thread_resume( # noqa: SLF001
|
||||
forked.id,
|
||||
ThreadResumeParams(thread_id=forked.id),
|
||||
)
|
||||
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"forked_policy": response_approval_policy(forked_state),
|
||||
} == {
|
||||
"final_response": "source seeded",
|
||||
"forked_policy": AskForApprovalValue.on_request.value,
|
||||
}
|
||||
|
||||
|
||||
def test_turn_approval_mode_persists_until_next_turn(tmp_path) -> None:
|
||||
"""A turn-level approval override should apply to later omitted-arg turns."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message("turn override", response_id="turn-mode-1")
|
||||
harness.responses.enqueue_assistant_message("turn inherited", response_id="turn-mode-2")
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
first_result = thread.run(
|
||||
"deny this and later turns",
|
||||
approval_mode=ApprovalMode.deny_all,
|
||||
)
|
||||
after_turn_override = codex._client.thread_resume( # noqa: SLF001
|
||||
thread.id,
|
||||
ThreadResumeParams(thread_id=thread.id),
|
||||
)
|
||||
second_result = thread.run("inherit previous approval mode")
|
||||
after_omitted_turn = codex._client.thread_resume( # noqa: SLF001
|
||||
thread.id,
|
||||
ThreadResumeParams(thread_id=thread.id),
|
||||
)
|
||||
|
||||
assert {
|
||||
"after_turn_override": response_approval_policy(after_turn_override),
|
||||
"after_omitted_turn": response_approval_policy(after_omitted_turn),
|
||||
"final_responses": [
|
||||
first_result.final_response,
|
||||
second_result.final_response,
|
||||
],
|
||||
} == {
|
||||
"after_turn_override": AskForApprovalValue.never.value,
|
||||
"after_omitted_turn": AskForApprovalValue.never.value,
|
||||
"final_responses": ["turn override", "turn inherited"],
|
||||
}
|
||||
|
||||
|
||||
def test_thread_run_approval_mode_persists_until_explicit_override(tmp_path) -> None:
|
||||
"""Omitted run approval mode should not rewrite the thread's stored setting."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message("locked down", response_id="approval-1")
|
||||
harness.responses.enqueue_assistant_message("reviewable", response_id="approval-2")
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start(approval_mode=ApprovalMode.deny_all)
|
||||
|
||||
first_result = thread.run("keep approvals denied")
|
||||
after_default_run = codex._client.thread_resume( # noqa: SLF001
|
||||
thread.id,
|
||||
ThreadResumeParams(thread_id=thread.id),
|
||||
)
|
||||
second_result = thread.run(
|
||||
"allow auto review now",
|
||||
approval_mode=ApprovalMode.auto_review,
|
||||
)
|
||||
after_override_run = codex._client.thread_resume( # noqa: SLF001
|
||||
thread.id,
|
||||
ThreadResumeParams(thread_id=thread.id),
|
||||
)
|
||||
|
||||
assert {
|
||||
"after_default_policy": response_approval_policy(after_default_run),
|
||||
"after_override_policy": response_approval_policy(after_override_run),
|
||||
"final_responses": [
|
||||
first_result.final_response,
|
||||
second_result.final_response,
|
||||
],
|
||||
} == {
|
||||
"after_default_policy": AskForApprovalValue.never.value,
|
||||
"after_override_policy": AskForApprovalValue.on_request.value,
|
||||
"final_responses": ["locked down", "reviewable"],
|
||||
}
|
||||
|
||||
|
||||
def test_async_thread_run_approval_mode_persists_until_explicit_override(
|
||||
tmp_path,
|
||||
) -> None:
|
||||
"""Async omitted run approval mode should leave stored settings alone."""
|
||||
|
||||
async def scenario() -> None:
|
||||
"""Use the async client to verify persisted app-server approval state."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"async locked down",
|
||||
response_id="async-approval-1",
|
||||
)
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"async reviewable",
|
||||
response_id="async-approval-2",
|
||||
)
|
||||
|
||||
async with AsyncCodex(config=harness.app_server_config()) as codex:
|
||||
thread = await codex.thread_start(approval_mode=ApprovalMode.deny_all)
|
||||
first_result = await thread.run("keep async approvals denied")
|
||||
after_default_run = await codex._client.thread_resume( # noqa: SLF001
|
||||
thread.id,
|
||||
ThreadResumeParams(thread_id=thread.id),
|
||||
)
|
||||
second_result = await thread.run(
|
||||
"allow async auto review now",
|
||||
approval_mode=ApprovalMode.auto_review,
|
||||
)
|
||||
after_override_run = await codex._client.thread_resume( # noqa: SLF001
|
||||
thread.id,
|
||||
ThreadResumeParams(thread_id=thread.id),
|
||||
)
|
||||
|
||||
assert {
|
||||
"after_default_policy": response_approval_policy(after_default_run),
|
||||
"after_override_policy": response_approval_policy(after_override_run),
|
||||
"final_responses": [
|
||||
first_result.final_response,
|
||||
second_result.final_response,
|
||||
],
|
||||
} == {
|
||||
"after_default_policy": AskForApprovalValue.never.value,
|
||||
"after_override_policy": AskForApprovalValue.on_request.value,
|
||||
"final_responses": ["async locked down", "async reviewable"],
|
||||
}
|
||||
|
||||
asyncio.run(scenario())
|
||||
95
sdk/python/tests/test_app_server_goal_operations.py
Normal file
95
sdk/python/tests/test_app_server_goal_operations.py
Normal file
@@ -0,0 +1,95 @@
|
||||
from app_server_harness import (
|
||||
AppServerHarness,
|
||||
ev_assistant_message,
|
||||
ev_completed,
|
||||
ev_function_call,
|
||||
ev_response_created,
|
||||
sse,
|
||||
)
|
||||
from app_server_helpers import agent_message_texts
|
||||
|
||||
from openai_codex import Codex
|
||||
from openai_codex._goal import _GoalNotificationStream
|
||||
from openai_codex._run import _collect_turn_result
|
||||
from openai_codex.generated.notification_registry import notification_turn_id
|
||||
from openai_codex.generated.v2_all import TurnStatus
|
||||
|
||||
|
||||
def test_private_goal_operation_coalesces_runtime_continuations(tmp_path) -> None:
|
||||
"""The private engine should expose automatic continuations as one turn."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"Initial pass complete.",
|
||||
response_id="goal-initial",
|
||||
)
|
||||
harness.responses.enqueue_sse(
|
||||
sse(
|
||||
[
|
||||
ev_response_created("goal-complete-tool"),
|
||||
ev_function_call(
|
||||
"call-goal-complete",
|
||||
"update_goal",
|
||||
'{"status":"complete"}',
|
||||
),
|
||||
ev_completed("goal-complete-tool"),
|
||||
]
|
||||
)
|
||||
)
|
||||
harness.responses.enqueue_sse(
|
||||
sse(
|
||||
[
|
||||
ev_response_created("goal-final"),
|
||||
ev_assistant_message("msg-goal-final", "Goal complete."),
|
||||
ev_completed("goal-final"),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
state, turn_id = codex._client.start_goal_operation( # noqa: SLF001
|
||||
thread.id,
|
||||
"Improve benchmark coverage",
|
||||
)
|
||||
stream = _GoalNotificationStream(
|
||||
state,
|
||||
state.next_notification,
|
||||
lambda: codex._client.unregister_goal_operation(state), # noqa: SLF001
|
||||
lambda: codex._client.cancel_goal_operation(state), # noqa: SLF001
|
||||
)
|
||||
events = list(stream)
|
||||
result = _collect_turn_result(iter(events), turn_id=turn_id)
|
||||
routes = codex._client._router._goal_operations.copy() # noqa: SLF001
|
||||
requests = harness.responses.wait_for_requests(3)
|
||||
|
||||
lifecycle = [event.method for event in events if event.method.startswith("turn/")]
|
||||
routed_ids = [
|
||||
routed_id
|
||||
for event in events
|
||||
if (routed_id := notification_turn_id(event.payload)) is not None
|
||||
]
|
||||
assert {
|
||||
"lifecycle": lifecycle,
|
||||
"routed_ids": routed_ids,
|
||||
"result": (result.id, result.status, result.final_response),
|
||||
"messages": agent_message_texts(events),
|
||||
"request_count": len(requests),
|
||||
"objective_reached_model": (
|
||||
"<external_goal_objective>Improve benchmark coverage</external_goal_objective>"
|
||||
in requests[0].message_input_texts("user")
|
||||
),
|
||||
"steering_reached_model": any(
|
||||
"Continue working toward the active thread goal." in text
|
||||
for text in requests[0].message_input_texts("user")
|
||||
),
|
||||
"routes_after_completion": routes,
|
||||
} == {
|
||||
"lifecycle": ["turn/started", "turn/completed"],
|
||||
"routed_ids": [turn_id] * len(routed_ids),
|
||||
"result": (turn_id, TurnStatus.completed, "Goal complete."),
|
||||
"messages": ["Initial pass complete.", "Goal complete."],
|
||||
"request_count": 3,
|
||||
"objective_reached_model": True,
|
||||
"steering_reached_model": True,
|
||||
"routes_after_completion": {},
|
||||
}
|
||||
308
sdk/python/tests/test_app_server_inputs.py
Normal file
308
sdk/python/tests/test_app_server_inputs.py
Normal file
@@ -0,0 +1,308 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from app_server_harness import AppServerHarness
|
||||
from app_server_helpers import TINY_PNG_BYTES, streaming_response
|
||||
|
||||
from openai_codex import (
|
||||
AsyncCodex,
|
||||
Codex,
|
||||
ExternalMessage,
|
||||
ImageInput,
|
||||
LocalImageInput,
|
||||
SkillInput,
|
||||
TextInput,
|
||||
)
|
||||
from openai_codex.generated.v2_all import FunctionCallOutputThreadItem
|
||||
from openai_codex.types import ThreadItem
|
||||
|
||||
|
||||
def _external_items(request) -> list[dict]:
|
||||
"""Select model-visible external content without generated item identifiers."""
|
||||
return [
|
||||
{key: value for key, value in item.items() if key != "id"}
|
||||
for item in request.input()
|
||||
if item.get("type") == "function_call_output"
|
||||
]
|
||||
|
||||
|
||||
def test_external_message_preserves_tool_authority_through_resume(tmp_path) -> None:
|
||||
content = "External update: deployment completed."
|
||||
expected = {
|
||||
"type": "function_call_output",
|
||||
"name": "notifications",
|
||||
"namespace": "slack",
|
||||
"output": content,
|
||||
}
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message("Update received", response_id="external")
|
||||
harness.responses.enqueue_assistant_message("Still available", response_id="resumed")
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
result = thread.run(
|
||||
ExternalMessage(tool_name="notifications", namespace="slack", content=content)
|
||||
)
|
||||
external_item = next(
|
||||
item for item in result.items if item.root.type == "functionCallOutput"
|
||||
)
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
resumed = codex.thread_resume(thread.id, include_turns=False)
|
||||
history = resumed.read(include_turns=True)
|
||||
persisted = next(
|
||||
item
|
||||
for item in history.thread.turns[0].items
|
||||
if item.root.id == external_item.root.id
|
||||
)
|
||||
assert isinstance(persisted, ThreadItem)
|
||||
assert isinstance(persisted.root, FunctionCallOutputThreadItem)
|
||||
assert persisted.root.started_at_ms is not None
|
||||
assert persisted.root.completed_at_ms is not None
|
||||
assert persisted == external_item
|
||||
resumed.run("Summarize the external update.")
|
||||
requests = harness.responses.requests()
|
||||
|
||||
assert result.final_response == "Update received"
|
||||
assert [_external_items(request) for request in requests] == [[expected], [expected]]
|
||||
assert [
|
||||
text
|
||||
for request in requests
|
||||
for role in ("user", "developer")
|
||||
for text in request.message_input_texts(role)
|
||||
if content in text
|
||||
] == []
|
||||
|
||||
|
||||
def test_external_message_joins_active_turn_with_tool_authority(tmp_path) -> None:
|
||||
content = "External update while the agent is running."
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
streaming_response("external-first", "msg-first", ["Working"]),
|
||||
delay_between_events_s=0.2,
|
||||
)
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"Update processed", response_id="external-second"
|
||||
)
|
||||
with ThreadPoolExecutor(max_workers=2) as consumers:
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
original = thread.turn("Monitor deployment updates.")
|
||||
original_result = consumers.submit(original.run)
|
||||
harness.responses.wait_for_requests(1)
|
||||
joined = thread.turn(ExternalMessage(tool_name="notifications", content=content))
|
||||
result = consumers.submit(joined.run).result(timeout=15)
|
||||
first = original_result.result(timeout=15)
|
||||
assert first.final_response == result.final_response
|
||||
assert first.items[0].root.type == "userMessage"
|
||||
assert all(item.root.type != "userMessage" for item in result.items)
|
||||
assert codex._client._router._turn_states == {}
|
||||
requests = harness.responses.requests()
|
||||
|
||||
assert result.usage is not None
|
||||
assert (joined.id, result.final_response) == (original.id, "Update processed")
|
||||
assert [_external_items(request) for request in requests] == [
|
||||
[],
|
||||
[
|
||||
{
|
||||
"type": "function_call_output",
|
||||
"name": "notifications",
|
||||
"output": content,
|
||||
}
|
||||
],
|
||||
]
|
||||
assert [request.message_input_texts("user")[-1] for request in requests] == [
|
||||
"Monitor deployment updates.",
|
||||
"Monitor deployment updates.",
|
||||
]
|
||||
|
||||
|
||||
def test_async_external_message_reaches_model_with_tool_authority(tmp_path) -> None:
|
||||
async def scenario() -> None:
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"Async update received", response_id="external-async"
|
||||
)
|
||||
async with AsyncCodex(config=harness.app_server_config()) as codex:
|
||||
thread = await codex.thread_start()
|
||||
result = await thread.run(
|
||||
ExternalMessage(tool_name="notifications", content="External async update")
|
||||
)
|
||||
request = harness.responses.single_request()
|
||||
|
||||
assert result.final_response == "Async update received"
|
||||
assert _external_items(request) == [
|
||||
{
|
||||
"type": "function_call_output",
|
||||
"name": "notifications",
|
||||
"output": "External async update",
|
||||
}
|
||||
]
|
||||
assert "External async update" not in request.message_input_texts("user")
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_async_external_message_allows_both_handles_to_consume(tmp_path) -> None:
|
||||
async def scenario() -> None:
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
streaming_response("async-first", "msg-first", ["Working"]),
|
||||
delay_between_events_s=0.2,
|
||||
)
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"Update processed", response_id="async-second"
|
||||
)
|
||||
async with AsyncCodex(config=harness.app_server_config()) as codex:
|
||||
thread = await codex.thread_start()
|
||||
original = await thread.turn("Monitor deployment updates.")
|
||||
original_result = asyncio.create_task(original.run())
|
||||
await asyncio.to_thread(harness.responses.wait_for_requests, 1)
|
||||
joined = await thread.turn(
|
||||
ExternalMessage(tool_name="notifications", content="Update")
|
||||
)
|
||||
first, second = await asyncio.wait_for(
|
||||
asyncio.gather(original_result, joined.run()), timeout=15
|
||||
)
|
||||
assert (first.final_response, first.usage) == (second.final_response, second.usage)
|
||||
assert first.final_response == "Update processed"
|
||||
assert first.usage is not None
|
||||
assert codex._client._sync._router._turn_states == {}
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_external_message_uses_core_tool_output_truncation(tmp_path) -> None:
|
||||
content = "External observation. " * 500
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"Context received", response_id="truncated-external"
|
||||
)
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start(config={"tool_output_token_limit": 32})
|
||||
thread.run(ExternalMessage(tool_name="notifications", content=content))
|
||||
request = harness.responses.single_request()
|
||||
|
||||
[item] = _external_items(request)
|
||||
assert (item["name"], item["type"]) == ("notifications", "function_call_output")
|
||||
assert len(item["output"]) < len(content)
|
||||
assert "truncated" in item["output"].lower()
|
||||
|
||||
|
||||
def test_data_url_image_input_reaches_responses_api(
|
||||
tmp_path,
|
||||
) -> None:
|
||||
"""Data URL image inputs should survive the SDK and app-server boundary."""
|
||||
image_data_url = "data:image/png;base64," + base64.b64encode(TINY_PNG_BYTES).decode("ascii")
|
||||
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"data URL image received",
|
||||
response_id="data-url-image",
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
result = codex.thread_start().run(
|
||||
[
|
||||
TextInput("Describe the data URL image."),
|
||||
ImageInput(image_data_url),
|
||||
]
|
||||
)
|
||||
request = harness.responses.single_request()
|
||||
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"contains_user_prompt": "Describe the data URL image."
|
||||
in request.message_input_texts("user"),
|
||||
"image_url_is_png_data_url": request.message_image_urls("user")[-1].startswith(
|
||||
"data:image/png;base64,"
|
||||
),
|
||||
} == {
|
||||
"final_response": "data URL image received",
|
||||
"contains_user_prompt": True,
|
||||
"image_url_is_png_data_url": True,
|
||||
}
|
||||
|
||||
|
||||
def test_local_image_input_reaches_responses_api(
|
||||
tmp_path,
|
||||
) -> None:
|
||||
"""Local image inputs should become data URLs after crossing the app-server."""
|
||||
local_image = tmp_path / "local.png"
|
||||
local_image.write_bytes(TINY_PNG_BYTES)
|
||||
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"local image received",
|
||||
response_id="local-image",
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
result = codex.thread_start().run(
|
||||
[
|
||||
TextInput("Describe the local image."),
|
||||
LocalImageInput(str(local_image)),
|
||||
]
|
||||
)
|
||||
request = harness.responses.single_request()
|
||||
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"contains_user_prompt": "Describe the local image." in request.message_input_texts("user"),
|
||||
"image_url_is_png_data_url": request.message_image_urls("user")[-1].startswith(
|
||||
"data:image/png;base64,"
|
||||
),
|
||||
} == {
|
||||
"final_response": "local image received",
|
||||
"contains_user_prompt": True,
|
||||
"image_url_is_png_data_url": True,
|
||||
}
|
||||
|
||||
|
||||
def test_skill_input_injects_loaded_skill_body(tmp_path) -> None:
|
||||
"""SkillInput should inject the selected loaded skill into model input."""
|
||||
skill_body = "Use the word cobalt."
|
||||
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
skill_file = harness.workspace / ".agents" / "skills" / "demo" / "SKILL.md"
|
||||
skill_file.parent.mkdir(parents=True)
|
||||
skill_file.write_text(f"---\nname: demo\ndescription: demo skill\n---\n\n{skill_body}\n")
|
||||
skill_path = skill_file.resolve()
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"skill received",
|
||||
response_id="skill-input",
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
result = codex.thread_start().run(
|
||||
[
|
||||
TextInput("Use the selected skill."),
|
||||
SkillInput("demo", str(skill_path)),
|
||||
]
|
||||
)
|
||||
request = harness.responses.single_request()
|
||||
|
||||
skill_blocks = [
|
||||
text for text in request.message_input_texts("user") if text.startswith("<skill>")
|
||||
]
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"skill_blocks": [
|
||||
{
|
||||
"has_name": "<name>demo</name>" in text,
|
||||
"has_path": f"<path>{skill_path}</path>" in text,
|
||||
"has_body": skill_body in text,
|
||||
}
|
||||
for text in skill_blocks
|
||||
],
|
||||
} == {
|
||||
"final_response": "skill received",
|
||||
"skill_blocks": [
|
||||
{
|
||||
"has_name": True,
|
||||
"has_path": True,
|
||||
"has_body": True,
|
||||
}
|
||||
],
|
||||
}
|
||||
271
sdk/python/tests/test_app_server_lifecycle.py
Normal file
271
sdk/python/tests/test_app_server_lifecycle.py
Normal file
@@ -0,0 +1,271 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from app_server_harness import AppServerHarness
|
||||
from app_server_helpers import request_kind
|
||||
|
||||
from openai_codex import AsyncCodex, Codex
|
||||
|
||||
|
||||
def _thread_message_summary(read_response) -> list[tuple[str, str]]:
|
||||
"""Return persisted user/agent messages from a thread read response."""
|
||||
messages: list[tuple[str, str]] = []
|
||||
for turn in read_response.thread.turns:
|
||||
for item in turn.items:
|
||||
root = item.root
|
||||
if root.type == "userMessage":
|
||||
text = "\n".join(
|
||||
input_item.root.text
|
||||
for input_item in root.content
|
||||
if input_item.root.type == "text"
|
||||
)
|
||||
messages.append(("user", text))
|
||||
if root.type == "agentMessage":
|
||||
messages.append(("agent", root.text))
|
||||
return messages
|
||||
|
||||
|
||||
def test_thread_set_name_and_read(tmp_path) -> None:
|
||||
"""Thread naming should round-trip through app-server JSON-RPC."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
thread.set_name("sdk integration thread")
|
||||
named = thread.read(include_turns=True)
|
||||
|
||||
assert {"thread_name": named.thread.name} == {
|
||||
"thread_name": "sdk integration thread",
|
||||
}
|
||||
|
||||
|
||||
def test_sync_and_async_initialization_round_trip_metadata(tmp_path) -> None:
|
||||
"""Public clients should initialize and start threads through app-server."""
|
||||
|
||||
async def async_scenario(harness: AppServerHarness) -> dict[str, object]:
|
||||
async with AsyncCodex(config=harness.app_server_config()) as codex:
|
||||
thread = await codex.thread_start()
|
||||
server = codex.metadata.serverInfo
|
||||
return {
|
||||
"thread_id": thread.id,
|
||||
"user_agent": codex.metadata.userAgent,
|
||||
"server_name": None if server is None else server.name,
|
||||
"server_version": None if server is None else server.version,
|
||||
}
|
||||
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
server = codex.metadata.serverInfo
|
||||
sync_summary = {
|
||||
"thread_id": thread.id,
|
||||
"user_agent": codex.metadata.userAgent,
|
||||
"server_name": None if server is None else server.name,
|
||||
"server_version": None if server is None else server.version,
|
||||
}
|
||||
async_summary = asyncio.run(async_scenario(harness))
|
||||
|
||||
assert {
|
||||
"sync": {
|
||||
"thread_id_present": bool(sync_summary["thread_id"]),
|
||||
"user_agent_present": bool(sync_summary["user_agent"]),
|
||||
"server_name_present": bool(sync_summary["server_name"]),
|
||||
"server_version_present": bool(sync_summary["server_version"]),
|
||||
},
|
||||
"async": {
|
||||
"thread_id_present": bool(async_summary["thread_id"]),
|
||||
"user_agent_present": bool(async_summary["user_agent"]),
|
||||
"server_name_present": bool(async_summary["server_name"]),
|
||||
"server_version_present": bool(async_summary["server_version"]),
|
||||
},
|
||||
} == {
|
||||
"sync": {
|
||||
"thread_id_present": True,
|
||||
"user_agent_present": True,
|
||||
"server_name_present": True,
|
||||
"server_version_present": True,
|
||||
},
|
||||
"async": {
|
||||
"thread_id_present": True,
|
||||
"user_agent_present": True,
|
||||
"server_name_present": True,
|
||||
"server_version_present": True,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_thread_list_filters_archived_threads(tmp_path) -> None:
|
||||
"""Thread listing should reflect archive state through app-server."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message("active", response_id="list-active")
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"archived",
|
||||
response_id="list-archived",
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
active_thread = codex.thread_start()
|
||||
archived_thread = codex.thread_start()
|
||||
active_thread.run("keep this listed")
|
||||
archived_thread.run("archive this")
|
||||
codex.thread_archive(archived_thread.id)
|
||||
active_list = codex.thread_list(archived=False)
|
||||
archived_list = codex.thread_list(archived=True)
|
||||
|
||||
expected_ids = {active_thread.id, archived_thread.id}
|
||||
assert {
|
||||
"active_ids": sorted(thread.id for thread in active_list.data if thread.id in expected_ids),
|
||||
"archived_ids": sorted(
|
||||
thread.id for thread in archived_list.data if thread.id in expected_ids
|
||||
),
|
||||
} == {
|
||||
"active_ids": [active_thread.id],
|
||||
"archived_ids": [archived_thread.id],
|
||||
}
|
||||
|
||||
|
||||
def test_read_include_turns_returns_persisted_history(tmp_path) -> None:
|
||||
"""Thread.read(include_turns=True) should load real persisted turn items."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message("first answer", response_id="read-1")
|
||||
harness.responses.enqueue_assistant_message("second answer", response_id="read-2")
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
thread.run("first question")
|
||||
thread.run("second question")
|
||||
read = thread.read(include_turns=True)
|
||||
|
||||
assert _thread_message_summary(read) == [
|
||||
("user", "first question"),
|
||||
("agent", "first answer"),
|
||||
("user", "second question"),
|
||||
("agent", "second answer"),
|
||||
]
|
||||
|
||||
|
||||
def test_async_lifecycle_methods_round_trip(tmp_path) -> None:
|
||||
"""Async lifecycle helpers should preserve the same app-server thread state."""
|
||||
|
||||
async def scenario() -> None:
|
||||
"""Exercise async wrappers over one materialized thread."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"async materialized",
|
||||
response_id="async-lifecycle",
|
||||
)
|
||||
|
||||
async with AsyncCodex(config=harness.app_server_config()) as codex:
|
||||
thread = await codex.thread_start()
|
||||
turn_result = await thread.run("materialize async thread")
|
||||
await thread.set_name("async lifecycle")
|
||||
named = await thread.read()
|
||||
resumed = await codex.thread_resume(thread.id)
|
||||
forked = await codex.thread_fork(thread.id)
|
||||
archive_response = await codex.thread_archive(thread.id)
|
||||
unarchived = await codex.thread_unarchive(thread.id)
|
||||
|
||||
assert {
|
||||
"turn_final_response": turn_result.final_response,
|
||||
"named_thread": named.thread.name,
|
||||
"resumed_id": resumed.id,
|
||||
"forked_is_distinct": forked.id != thread.id,
|
||||
"archive_response": archive_response.model_dump(by_alias=True, mode="json"),
|
||||
"unarchived_id": unarchived.id,
|
||||
} == {
|
||||
"turn_final_response": "async materialized",
|
||||
"named_thread": "async lifecycle",
|
||||
"resumed_id": thread.id,
|
||||
"forked_is_distinct": True,
|
||||
"archive_response": {},
|
||||
"unarchived_id": thread.id,
|
||||
}
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_thread_fork_returns_distinct_thread(tmp_path) -> None:
|
||||
"""Thread fork should return a distinct thread for a persisted rollout."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message("materialized", response_id="fork-seed")
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
seeded = thread.run("materialize this thread before fork")
|
||||
forked = codex.thread_fork(thread.id)
|
||||
|
||||
assert {
|
||||
"seeded_response": seeded.final_response,
|
||||
"forked_is_distinct": forked.id != thread.id,
|
||||
} == {
|
||||
"seeded_response": "materialized",
|
||||
"forked_is_distinct": True,
|
||||
}
|
||||
|
||||
|
||||
def test_archive_unarchive_round_trip_uses_materialized_rollout(tmp_path) -> None:
|
||||
"""Archive helpers should work once the app-server has persisted a rollout."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message("materialized", response_id="archive-seed")
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
seeded = thread.run("materialize this thread before archive")
|
||||
archived = codex.thread_archive(thread.id)
|
||||
unarchived = codex.thread_unarchive(thread.id)
|
||||
read = unarchived.read()
|
||||
|
||||
assert {
|
||||
"seeded_response": seeded.final_response,
|
||||
"archive_response": archived.model_dump(by_alias=True, mode="json"),
|
||||
"unarchived_id": unarchived.id,
|
||||
"read_id": read.thread.id,
|
||||
} == {
|
||||
"seeded_response": "materialized",
|
||||
"archive_response": {},
|
||||
"unarchived_id": thread.id,
|
||||
"read_id": thread.id,
|
||||
}
|
||||
|
||||
|
||||
def test_models_rpc(tmp_path) -> None:
|
||||
"""Model listing should go through the pinned app-server method."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
models = codex.models(include_hidden=True)
|
||||
|
||||
assert {
|
||||
"models_payload_has_data": isinstance(
|
||||
models.model_dump(by_alias=True, mode="json").get("data"),
|
||||
list,
|
||||
),
|
||||
} == {"models_payload_has_data": True}
|
||||
|
||||
|
||||
def test_compact_rpc_hits_mock_responses(tmp_path) -> None:
|
||||
"""Compaction should run through app-server and hit the mock Responses boundary."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message("history", response_id="compact-history")
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"compact summary",
|
||||
response_id="compact-summary",
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
turn_result = thread.run("create history")
|
||||
compact_response = thread.compact()
|
||||
requests = harness.responses.wait_for_requests(2)
|
||||
|
||||
assert {
|
||||
"turn_final_response": turn_result.final_response,
|
||||
"compact_response": compact_response.model_dump(
|
||||
by_alias=True,
|
||||
mode="json",
|
||||
),
|
||||
"request_kinds": [request_kind(request.path) for request in requests],
|
||||
} == {
|
||||
"turn_final_response": "history",
|
||||
"compact_response": {},
|
||||
"request_kinds": ["responses", "responses"],
|
||||
}
|
||||
90
sdk/python/tests/test_app_server_login.py
Normal file
90
sdk/python/tests/test_app_server_login.py
Normal file
@@ -0,0 +1,90 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
|
||||
from app_server_harness import AppServerHarness
|
||||
|
||||
from openai_codex import Codex, CodexConfig
|
||||
from openai_codex.generated.v2_all import (
|
||||
ChatgptAuthTokensLoginAccountParams,
|
||||
LoginAccountParams,
|
||||
)
|
||||
|
||||
|
||||
def _app_server_config(harness: AppServerHarness) -> CodexConfig:
|
||||
"""Build an isolated login config without inheriting ambient API-key auth."""
|
||||
config = harness.app_server_config()
|
||||
config.env = {**(config.env or {}), "OPENAI_API_KEY": ""}
|
||||
return config
|
||||
|
||||
|
||||
def test_api_key_login_authenticates_follow_up_model_requests(tmp_path) -> None:
|
||||
"""API-key login should authorize the next Responses request with that key."""
|
||||
with AppServerHarness(tmp_path, requires_openai_auth=True) as harness:
|
||||
harness.responses.enqueue_assistant_message("api key auth", response_id="api-key-auth")
|
||||
|
||||
with Codex(config=_app_server_config(harness)) as codex:
|
||||
codex.login_api_key("sk-sdk-login-test")
|
||||
result = codex.thread_start().run("prove api key auth")
|
||||
request = harness.responses.single_request()
|
||||
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"authorization": request.header("authorization"),
|
||||
} == {
|
||||
"final_response": "api key auth",
|
||||
"authorization": "Bearer sk-sdk-login-test",
|
||||
}
|
||||
|
||||
|
||||
def test_chatgpt_token_login_authenticates_follow_up_model_requests(tmp_path) -> None:
|
||||
"""ChatGPT token handoff should authorize later Responses requests with that token."""
|
||||
account_id = "workspace-sdk-chatgpt"
|
||||
|
||||
def _encode(payload: dict[str, object]) -> str:
|
||||
raw = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
|
||||
|
||||
# App-server parses claims from the access token before persisting external ChatGPT auth.
|
||||
header = _encode({"alg": "none", "typ": "JWT"})
|
||||
claims = _encode(
|
||||
{
|
||||
"email": "sdk-chatgpt@example.com",
|
||||
"https://api.openai.com/auth": {
|
||||
"chatgpt_account_id": account_id,
|
||||
"chatgpt_plan_type": "pro",
|
||||
},
|
||||
}
|
||||
)
|
||||
access_token = f"{header}.{claims}.sig"
|
||||
|
||||
with AppServerHarness(tmp_path, requires_openai_auth=True) as harness:
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"chatgpt token auth",
|
||||
response_id="chatgpt-token-auth",
|
||||
)
|
||||
|
||||
with Codex(config=_app_server_config(harness)) as codex:
|
||||
login = codex._client.account_login_start(
|
||||
LoginAccountParams(
|
||||
root=ChatgptAuthTokensLoginAccountParams(
|
||||
access_token=access_token,
|
||||
chatgpt_account_id=account_id,
|
||||
chatgpt_plan_type="pro",
|
||||
type="chatgptAuthTokens",
|
||||
)
|
||||
)
|
||||
)
|
||||
result = codex.thread_start().run("prove chatgpt token auth")
|
||||
request = harness.responses.single_request()
|
||||
|
||||
assert {
|
||||
"login_type": login.root.type,
|
||||
"final_response": result.final_response,
|
||||
"authorization": request.header("authorization"),
|
||||
} == {
|
||||
"login_type": "chatgptAuthTokens",
|
||||
"final_response": "chatgpt token auth",
|
||||
"authorization": f"Bearer {access_token}",
|
||||
}
|
||||
381
sdk/python/tests/test_app_server_run.py
Normal file
381
sdk/python/tests/test_app_server_run.py
Normal file
@@ -0,0 +1,381 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
from app_server_harness import (
|
||||
AppServerHarness,
|
||||
ev_assistant_message,
|
||||
ev_completed,
|
||||
ev_completed_with_usage,
|
||||
ev_failed,
|
||||
ev_response_created,
|
||||
sse,
|
||||
)
|
||||
from app_server_helpers import (
|
||||
agent_message_texts_from_items,
|
||||
assistant_message_with_phase,
|
||||
)
|
||||
|
||||
from openai_codex import AsyncCodex, Codex
|
||||
from openai_codex.generated.v2_all import MessagePhase
|
||||
|
||||
|
||||
def test_sync_thread_run_uses_mock_responses(
|
||||
tmp_path,
|
||||
) -> None:
|
||||
"""Drive Thread.run through the pinned app-server and inspect the HTTP request."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message("Hello from the mock.", response_id="run-1")
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
result = thread.run("hello")
|
||||
|
||||
request = harness.responses.single_request()
|
||||
|
||||
body = request.body_json()
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"agent_messages": agent_message_texts_from_items(result.items),
|
||||
"has_usage": result.usage is not None,
|
||||
"request_model": body["model"],
|
||||
"request_stream": body["stream"],
|
||||
"request_user_texts": request.message_input_texts("user")[-1:],
|
||||
} == {
|
||||
"final_response": "Hello from the mock.",
|
||||
"agent_messages": ["Hello from the mock."],
|
||||
"has_usage": True,
|
||||
"request_model": "mock-model",
|
||||
"request_stream": True,
|
||||
"request_user_texts": ["hello"],
|
||||
}
|
||||
|
||||
|
||||
def test_checkout_supports_new_options_and_history_selection(tmp_path) -> None:
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message("Options supported")
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
result = thread.run("hello", turn_service_tier="default", source="automation")
|
||||
resumed = codex.thread_resume(thread.id, include_turns=False)
|
||||
forked = codex.thread_fork(thread.id, include_turns=True)
|
||||
assert result.final_response == "Options supported"
|
||||
assert resumed.id == thread.id
|
||||
assert forked.id != thread.id
|
||||
assert harness.responses.single_request().message_input_texts("user")[-1:] == ["hello"]
|
||||
|
||||
|
||||
def test_run_params_and_usage_cross_app_server_boundary(tmp_path) -> None:
|
||||
"""Thread.run should pass overrides and collect app-server token usage."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
sse(
|
||||
[
|
||||
ev_response_created("run-overrides"),
|
||||
ev_assistant_message("msg-run-overrides", "overrides applied"),
|
||||
ev_completed_with_usage(
|
||||
"run-overrides",
|
||||
input_tokens=11,
|
||||
cached_input_tokens=3,
|
||||
output_tokens=7,
|
||||
reasoning_output_tokens=5,
|
||||
total_tokens=18,
|
||||
),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
result = thread.run(
|
||||
"use overrides",
|
||||
model="mock-model-override",
|
||||
)
|
||||
request = harness.responses.single_request()
|
||||
|
||||
usage_payload = None
|
||||
if result.usage is not None:
|
||||
dumped_usage = result.usage.model_dump(by_alias=True, mode="json")
|
||||
usage_payload = {
|
||||
"last": dumped_usage["last"],
|
||||
"total": dumped_usage["total"],
|
||||
}
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"request_model": request.body_json()["model"],
|
||||
"usage": usage_payload,
|
||||
} == {
|
||||
"final_response": "overrides applied",
|
||||
"request_model": "mock-model-override",
|
||||
"usage": {
|
||||
"last": {
|
||||
"cacheWriteInputTokens": 0,
|
||||
"cachedInputTokens": 3,
|
||||
"inputTokens": 11,
|
||||
"outputTokens": 7,
|
||||
"reasoningOutputTokens": 5,
|
||||
"totalTokens": 18,
|
||||
},
|
||||
"total": {
|
||||
"cacheWriteInputTokens": 0,
|
||||
"cachedInputTokens": 3,
|
||||
"inputTokens": 11,
|
||||
"outputTokens": 7,
|
||||
"reasoningOutputTokens": 5,
|
||||
"totalTokens": 18,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_async_thread_run_uses_mock_responses(
|
||||
tmp_path,
|
||||
) -> None:
|
||||
"""Async Thread.run should exercise the same app-server boundary."""
|
||||
|
||||
async def scenario() -> None:
|
||||
"""Run the async client against a real app-server process."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"Hello async.",
|
||||
response_id="async-run-1",
|
||||
)
|
||||
|
||||
async with AsyncCodex(config=harness.app_server_config()) as codex:
|
||||
thread = await codex.thread_start()
|
||||
result = await thread.run("async hello")
|
||||
|
||||
request = harness.responses.single_request()
|
||||
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"agent_messages": agent_message_texts_from_items(result.items),
|
||||
"request_user_texts": request.message_input_texts("user")[-1:],
|
||||
} == {
|
||||
"final_response": "Hello async.",
|
||||
"agent_messages": ["Hello async."],
|
||||
"request_user_texts": ["async hello"],
|
||||
}
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_sync_turn_result_uses_last_unknown_phase_message(tmp_path) -> None:
|
||||
"""TurnResult should use the last unknown-phase agent message as final text."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
sse(
|
||||
[
|
||||
ev_response_created("items-last"),
|
||||
ev_assistant_message("msg-items-first", "First message"),
|
||||
ev_assistant_message("msg-items-second", "Second message"),
|
||||
ev_completed("items-last"),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
result = codex.thread_start().run("case: last unknown phase wins")
|
||||
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"agent_messages": agent_message_texts_from_items(result.items),
|
||||
} == {
|
||||
"final_response": "Second message",
|
||||
"agent_messages": ["First message", "Second message"],
|
||||
}
|
||||
|
||||
|
||||
def test_sync_turn_result_preserves_empty_last_message(tmp_path) -> None:
|
||||
"""TurnResult should preserve an empty final agent message instead of skipping it."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
sse(
|
||||
[
|
||||
ev_response_created("items-empty"),
|
||||
ev_assistant_message("msg-items-nonempty", "First message"),
|
||||
ev_assistant_message("msg-items-empty", ""),
|
||||
ev_completed("items-empty"),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
result = codex.thread_start().run("case: empty last message")
|
||||
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"agent_messages": agent_message_texts_from_items(result.items),
|
||||
} == {
|
||||
"final_response": "",
|
||||
"agent_messages": ["First message", ""],
|
||||
}
|
||||
|
||||
|
||||
def test_sync_turn_result_does_not_promote_commentary_only_to_final(tmp_path) -> None:
|
||||
"""TurnResult final_response should stay unset when app-server marks only commentary."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
sse(
|
||||
[
|
||||
ev_response_created("items-commentary"),
|
||||
assistant_message_with_phase(
|
||||
"msg-items-commentary",
|
||||
"Commentary",
|
||||
MessagePhase.commentary,
|
||||
),
|
||||
ev_completed("items-commentary"),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
result = codex.thread_start().run("case: commentary only")
|
||||
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"agent_messages": agent_message_texts_from_items(result.items),
|
||||
} == {
|
||||
"final_response": None,
|
||||
"agent_messages": ["Commentary"],
|
||||
}
|
||||
|
||||
|
||||
def test_async_turn_result_uses_last_unknown_phase_message(tmp_path) -> None:
|
||||
"""Async TurnResult should use the last unknown-phase agent message."""
|
||||
|
||||
async def scenario() -> None:
|
||||
"""Run one async result-mapping case against a pinned app-server."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
sse(
|
||||
[
|
||||
ev_response_created("async-items-last"),
|
||||
ev_assistant_message(
|
||||
"msg-async-items-first",
|
||||
"First async message",
|
||||
),
|
||||
ev_assistant_message(
|
||||
"msg-async-items-second",
|
||||
"Second async message",
|
||||
),
|
||||
ev_completed("async-items-last"),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
async with AsyncCodex(config=harness.app_server_config()) as codex:
|
||||
result = await (await codex.thread_start()).run("case: async last unknown phase")
|
||||
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"agent_messages": agent_message_texts_from_items(result.items),
|
||||
} == {
|
||||
"final_response": "Second async message",
|
||||
"agent_messages": ["First async message", "Second async message"],
|
||||
}
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_async_turn_result_does_not_promote_commentary_only_to_final(
|
||||
tmp_path,
|
||||
) -> None:
|
||||
"""Async TurnResult final_response should stay unset for commentary-only output."""
|
||||
|
||||
async def scenario() -> None:
|
||||
"""Run one async commentary mapping case against a pinned app-server."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
sse(
|
||||
[
|
||||
ev_response_created("async-items-commentary"),
|
||||
assistant_message_with_phase(
|
||||
"msg-async-items-commentary",
|
||||
"Async commentary",
|
||||
MessagePhase.commentary,
|
||||
),
|
||||
ev_completed("async-items-commentary"),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
async with AsyncCodex(config=harness.app_server_config()) as codex:
|
||||
result = await (await codex.thread_start()).run("case: async commentary only")
|
||||
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"agent_messages": agent_message_texts_from_items(result.items),
|
||||
} == {
|
||||
"final_response": None,
|
||||
"agent_messages": ["Async commentary"],
|
||||
}
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_thread_run_raises_when_real_app_server_reports_failed_turn(tmp_path) -> None:
|
||||
"""Thread.run should surface the failed turn error emitted by app-server."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
sse(
|
||||
[
|
||||
ev_response_created("failed-run"),
|
||||
ev_failed("failed-run", "boom from mock model"),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
with pytest.raises(RuntimeError, match="boom from mock model"):
|
||||
thread.run("trigger failure")
|
||||
|
||||
|
||||
def test_final_answer_phase_survives_real_app_server_mapping(tmp_path) -> None:
|
||||
"""TurnResult should use the final-answer item emitted by app-server."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
sse(
|
||||
[
|
||||
ev_response_created("phase-1"),
|
||||
{
|
||||
**ev_assistant_message("msg-commentary", "Commentary"),
|
||||
"item": {
|
||||
**ev_assistant_message("msg-commentary", "Commentary")["item"],
|
||||
"phase": MessagePhase.commentary.value,
|
||||
},
|
||||
},
|
||||
{
|
||||
**ev_assistant_message("msg-final", "Final answer"),
|
||||
"item": {
|
||||
**ev_assistant_message("msg-final", "Final answer")["item"],
|
||||
"phase": MessagePhase.final_answer.value,
|
||||
},
|
||||
},
|
||||
ev_completed("phase-1"),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
result = codex.thread_start().run("choose final answer")
|
||||
|
||||
assert {
|
||||
"final_response": result.final_response,
|
||||
"items": [
|
||||
{
|
||||
"text": item.root.text,
|
||||
"phase": None if item.root.phase is None else item.root.phase.value,
|
||||
}
|
||||
for item in result.items
|
||||
if item.root.type == "agentMessage"
|
||||
],
|
||||
} == {
|
||||
"final_response": "Final answer",
|
||||
"items": [
|
||||
{"text": "Commentary", "phase": MessagePhase.commentary.value},
|
||||
{"text": "Final answer", "phase": MessagePhase.final_answer.value},
|
||||
],
|
||||
}
|
||||
274
sdk/python/tests/test_app_server_streaming.py
Normal file
274
sdk/python/tests/test_app_server_streaming.py
Normal file
@@ -0,0 +1,274 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from app_server_harness import AppServerHarness
|
||||
from app_server_helpers import (
|
||||
agent_message_texts,
|
||||
agent_message_texts_from_items,
|
||||
next_async_delta,
|
||||
next_sync_delta,
|
||||
streaming_response,
|
||||
)
|
||||
|
||||
from openai_codex import AsyncCodex, Codex
|
||||
from openai_codex.generated.v2_all import (
|
||||
AgentMessageDeltaNotification,
|
||||
TurnCompletedNotification,
|
||||
TurnStatus,
|
||||
)
|
||||
|
||||
|
||||
def test_sync_stream_routes_text_deltas_and_completion(tmp_path) -> None:
|
||||
"""A sync turn stream should expose deltas, completed items, and completion."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(streaming_response("stream-1", "msg-stream-1", ["he", "llo"]))
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
stream = thread.turn("stream please").stream()
|
||||
events = list(stream)
|
||||
request = harness.responses.single_request()
|
||||
|
||||
assert {
|
||||
"deltas": [
|
||||
event.payload.delta
|
||||
for event in events
|
||||
if isinstance(event.payload, AgentMessageDeltaNotification)
|
||||
],
|
||||
"agent_messages": agent_message_texts(events),
|
||||
"request_user_texts": request.message_input_texts("user")[-1:],
|
||||
"completed_statuses": [
|
||||
event.payload.turn.status
|
||||
for event in events
|
||||
if isinstance(event.payload, TurnCompletedNotification)
|
||||
],
|
||||
} == {
|
||||
"deltas": ["he", "llo"],
|
||||
"agent_messages": ["hello"],
|
||||
"request_user_texts": ["stream please"],
|
||||
"completed_statuses": [TurnStatus.completed],
|
||||
}
|
||||
|
||||
|
||||
def test_turn_run_returns_completed_turn(tmp_path) -> None:
|
||||
"""TurnHandle.run should collect output and completion metadata."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_assistant_message("turn complete", response_id="turn-run-1")
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
turn = thread.turn("complete this turn")
|
||||
completed = turn.run()
|
||||
|
||||
assert {
|
||||
"turn_id": completed.id,
|
||||
"status": completed.status,
|
||||
"agent_messages": agent_message_texts_from_items(completed.items),
|
||||
"final_response": completed.final_response,
|
||||
} == {
|
||||
"turn_id": turn.id,
|
||||
"status": TurnStatus.completed,
|
||||
"agent_messages": ["turn complete"],
|
||||
"final_response": "turn complete",
|
||||
}
|
||||
|
||||
|
||||
def test_async_stream_routes_text_deltas_and_completion(tmp_path) -> None:
|
||||
"""An async turn stream should expose the same notification sequence."""
|
||||
|
||||
async def scenario() -> None:
|
||||
"""Stream one async turn against the real pinned app-server."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
streaming_response("async-stream-1", "msg-async-stream-1", ["as", "ync"])
|
||||
)
|
||||
|
||||
async with AsyncCodex(config=harness.app_server_config()) as codex:
|
||||
thread = await codex.thread_start()
|
||||
turn = await thread.turn("async stream please")
|
||||
events = [event async for event in turn.stream()]
|
||||
request = harness.responses.single_request()
|
||||
|
||||
assert {
|
||||
"deltas": [
|
||||
event.payload.delta
|
||||
for event in events
|
||||
if isinstance(event.payload, AgentMessageDeltaNotification)
|
||||
],
|
||||
"agent_messages": agent_message_texts(events),
|
||||
"request_user_texts": request.message_input_texts("user")[-1:],
|
||||
"completed_statuses": [
|
||||
event.payload.turn.status
|
||||
for event in events
|
||||
if isinstance(event.payload, TurnCompletedNotification)
|
||||
],
|
||||
} == {
|
||||
"deltas": ["as", "ync"],
|
||||
"agent_messages": ["async"],
|
||||
"request_user_texts": ["async stream please"],
|
||||
"completed_statuses": [TurnStatus.completed],
|
||||
}
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_low_level_sync_stream_text_uses_real_turn_routing(tmp_path) -> None:
|
||||
"""CodexClient.stream_text should stream through a real app-server turn."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
streaming_response("low-sync-stream", "msg-low-sync-stream", ["fir", "st"])
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
chunks = list(codex._client.stream_text(thread.id, "low-level sync")) # noqa: SLF001
|
||||
|
||||
assert [chunk.delta for chunk in chunks] == ["fir", "st"]
|
||||
|
||||
|
||||
def test_low_level_async_stream_text_allows_parallel_model_list(tmp_path) -> None:
|
||||
"""Async stream_text should yield without blocking another app-server request."""
|
||||
|
||||
async def scenario() -> None:
|
||||
"""Leave a stream open while another async request completes."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
streaming_response(
|
||||
"low-async-stream",
|
||||
"msg-low-async-stream",
|
||||
["one", "two", "three"],
|
||||
),
|
||||
delay_between_events_s=0.03,
|
||||
)
|
||||
|
||||
async with AsyncCodex(config=harness.app_server_config()) as codex:
|
||||
thread = await codex.thread_start()
|
||||
stream = codex._client.stream_text( # noqa: SLF001
|
||||
thread.id,
|
||||
"low-level async",
|
||||
)
|
||||
first = await anext(stream)
|
||||
models_task = asyncio.create_task(codex.models())
|
||||
models = await asyncio.wait_for(models_task, timeout=1.0)
|
||||
remaining = [chunk.delta async for chunk in stream]
|
||||
|
||||
assert {
|
||||
"first": first.delta,
|
||||
"remaining": remaining,
|
||||
"models_payload_has_data": isinstance(
|
||||
models.model_dump(by_alias=True, mode="json").get("data"),
|
||||
list,
|
||||
),
|
||||
} == {
|
||||
"first": "one",
|
||||
"remaining": ["two", "three"],
|
||||
"models_payload_has_data": True,
|
||||
}
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_interleaved_sync_turn_streams_route_by_turn_id(tmp_path) -> None:
|
||||
"""Two sync streams on one client should consume only their own notifications."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
streaming_response("first-stream", "msg-first", ["one-", "done"]),
|
||||
delay_between_events_s=0.01,
|
||||
)
|
||||
harness.responses.enqueue_sse(
|
||||
streaming_response("second-stream", "msg-second", ["two-", "done"]),
|
||||
delay_between_events_s=0.01,
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
first_thread = codex.thread_start()
|
||||
second_thread = codex.thread_start()
|
||||
first_turn = first_thread.turn("first")
|
||||
second_turn = second_thread.turn("second")
|
||||
|
||||
first_stream = first_turn.stream()
|
||||
second_stream = second_turn.stream()
|
||||
first_first_delta = next_sync_delta(first_stream)
|
||||
second_first_delta = next_sync_delta(second_stream)
|
||||
first_second_delta = next_sync_delta(first_stream)
|
||||
second_second_delta = next_sync_delta(second_stream)
|
||||
first_tail = list(first_stream)
|
||||
second_tail = list(second_stream)
|
||||
|
||||
assert {
|
||||
"streams": sorted(
|
||||
[
|
||||
(
|
||||
first_first_delta,
|
||||
first_second_delta,
|
||||
agent_message_texts(first_tail),
|
||||
),
|
||||
(
|
||||
second_first_delta,
|
||||
second_second_delta,
|
||||
agent_message_texts(second_tail),
|
||||
),
|
||||
]
|
||||
),
|
||||
} == {
|
||||
"streams": [
|
||||
("one-", "done", ["one-done"]),
|
||||
("two-", "done", ["two-done"]),
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_interleaved_async_turn_streams_route_by_turn_id(tmp_path) -> None:
|
||||
"""Two async streams on one client should consume only their own notifications."""
|
||||
|
||||
async def scenario() -> None:
|
||||
"""Interleave async stream consumers against one app-server process."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
streaming_response("async-first", "msg-async-first", ["a1", "-done"]),
|
||||
delay_between_events_s=0.01,
|
||||
)
|
||||
harness.responses.enqueue_sse(
|
||||
streaming_response("async-second", "msg-async-second", ["a2", "-done"]),
|
||||
delay_between_events_s=0.01,
|
||||
)
|
||||
|
||||
async with AsyncCodex(config=harness.app_server_config()) as codex:
|
||||
first_thread = await codex.thread_start()
|
||||
second_thread = await codex.thread_start()
|
||||
first_turn = await first_thread.turn("async first")
|
||||
second_turn = await second_thread.turn("async second")
|
||||
|
||||
first_stream = first_turn.stream()
|
||||
second_stream = second_turn.stream()
|
||||
first_first_delta = await next_async_delta(first_stream)
|
||||
second_first_delta = await next_async_delta(second_stream)
|
||||
first_second_delta = await next_async_delta(first_stream)
|
||||
second_second_delta = await next_async_delta(second_stream)
|
||||
first_tail = [event async for event in first_stream]
|
||||
second_tail = [event async for event in second_stream]
|
||||
|
||||
assert {
|
||||
"streams": sorted(
|
||||
[
|
||||
(
|
||||
first_first_delta,
|
||||
first_second_delta,
|
||||
agent_message_texts(first_tail),
|
||||
),
|
||||
(
|
||||
second_first_delta,
|
||||
second_second_delta,
|
||||
agent_message_texts(second_tail),
|
||||
),
|
||||
]
|
||||
),
|
||||
} == {
|
||||
"streams": [
|
||||
("a1", "-done", ["a1-done"]),
|
||||
("a2", "-done", ["a2-done"]),
|
||||
],
|
||||
}
|
||||
|
||||
asyncio.run(scenario())
|
||||
81
sdk/python/tests/test_app_server_turn_controls.py
Normal file
81
sdk/python/tests/test_app_server_turn_controls.py
Normal file
@@ -0,0 +1,81 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from app_server_harness import AppServerHarness
|
||||
from app_server_helpers import agent_message_texts, streaming_response
|
||||
|
||||
from openai_codex import Codex
|
||||
from openai_codex.generated.v2_all import TurnStatus
|
||||
|
||||
|
||||
def test_turn_steer_adds_follow_up_input(tmp_path) -> None:
|
||||
"""Steering an active turn should create a follow-up Responses request."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
streaming_response("steer-first", "msg-steer-first", ["before steer"]),
|
||||
delay_between_events_s=0.2,
|
||||
)
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"after steer",
|
||||
response_id="steer-second",
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start(config={"features.instant_interrupt": False})
|
||||
turn = thread.turn("Start a steerable turn.")
|
||||
harness.responses.wait_for_requests(1)
|
||||
steer = turn.steer("Use this steering input.")
|
||||
events = list(turn.stream())
|
||||
requests = harness.responses.wait_for_requests(2)
|
||||
|
||||
assert {
|
||||
"steered_turn_id": steer.turn_id,
|
||||
"turn_id": turn.id,
|
||||
"agent_messages": agent_message_texts(events),
|
||||
"last_user_texts": [request.message_input_texts("user")[-1] for request in requests],
|
||||
} == {
|
||||
"steered_turn_id": turn.id,
|
||||
"turn_id": turn.id,
|
||||
"agent_messages": ["before steer", "after steer"],
|
||||
"last_user_texts": [
|
||||
"Start a steerable turn.",
|
||||
"Use this steering input.",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_turn_interrupt_stops_active_turn_and_follow_up_runs(tmp_path) -> None:
|
||||
"""Interrupting an active turn should complete it and leave the thread usable."""
|
||||
with AppServerHarness(tmp_path) as harness:
|
||||
harness.responses.enqueue_sse(
|
||||
streaming_response(
|
||||
"interrupt-first",
|
||||
"msg-interrupt-first",
|
||||
["still ", "running"],
|
||||
),
|
||||
delay_between_events_s=0.2,
|
||||
)
|
||||
harness.responses.enqueue_assistant_message(
|
||||
"after interrupt",
|
||||
response_id="interrupt-follow-up",
|
||||
)
|
||||
|
||||
with Codex(config=harness.app_server_config()) as codex:
|
||||
thread = codex.thread_start()
|
||||
interrupted_turn = thread.turn("Start a long turn.")
|
||||
harness.responses.wait_for_requests(1)
|
||||
interrupt_response = interrupted_turn.interrupt()
|
||||
completed = interrupted_turn.run()
|
||||
follow_up = thread.run("Continue after the interrupt.")
|
||||
|
||||
assert {
|
||||
"interrupt_response": interrupt_response.model_dump(
|
||||
by_alias=True,
|
||||
mode="json",
|
||||
),
|
||||
"interrupted_status": completed.status,
|
||||
"follow_up": follow_up.final_response,
|
||||
} == {
|
||||
"interrupt_response": {},
|
||||
"interrupted_status": TurnStatus.interrupted,
|
||||
"follow_up": "after interrupt",
|
||||
}
|
||||
1485
sdk/python/tests/test_artifact_workflow_and_binaries.py
Normal file
1485
sdk/python/tests/test_artifact_workflow_and_binaries.py
Normal file
File diff suppressed because it is too large
Load Diff
104
sdk/python/tests/test_async_client_behavior.py
Normal file
104
sdk/python/tests/test_async_client_behavior.py
Normal file
@@ -0,0 +1,104 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
from openai_codex.async_client import AsyncCodexClient
|
||||
from openai_codex.generated.v2_all import (
|
||||
TurnCompletedNotification,
|
||||
)
|
||||
from openai_codex.models import Notification, UnknownNotification
|
||||
|
||||
|
||||
def test_async_client_allows_concurrent_transport_calls() -> None:
|
||||
"""Async wrappers should offload sync calls so concurrent awaits can overlap."""
|
||||
|
||||
async def scenario() -> int:
|
||||
"""Run two blocking sync calls and report peak overlap."""
|
||||
client = AsyncCodexClient()
|
||||
active = 0
|
||||
max_active = 0
|
||||
|
||||
def fake_model_list(include_hidden: bool = False) -> bool:
|
||||
"""Simulate a blocking sync transport call."""
|
||||
nonlocal active, max_active
|
||||
active += 1
|
||||
max_active = max(max_active, active)
|
||||
time.sleep(0.05)
|
||||
active -= 1
|
||||
return include_hidden
|
||||
|
||||
client._sync.model_list = fake_model_list # type: ignore[method-assign]
|
||||
await asyncio.gather(client.model_list(), client.model_list())
|
||||
return max_active
|
||||
|
||||
assert asyncio.run(scenario()) == 2
|
||||
|
||||
|
||||
def test_async_client_turn_notification_methods_delegate_to_sync_client() -> None:
|
||||
"""Async turn routing methods should preserve sync-client registration semantics."""
|
||||
|
||||
async def scenario() -> tuple[list[tuple[str, str]], Notification, str]:
|
||||
"""Record the sync-client calls made by async turn notification wrappers."""
|
||||
client = AsyncCodexClient()
|
||||
event = Notification(
|
||||
method="unknown/direct",
|
||||
payload=UnknownNotification(params={"turnId": "turn-1"}),
|
||||
)
|
||||
completed = TurnCompletedNotification.model_validate(
|
||||
{
|
||||
"threadId": "thread-1",
|
||||
"turn": {"id": "turn-1", "items": [], "status": "completed"},
|
||||
}
|
||||
)
|
||||
calls: list[tuple[str, str]] = []
|
||||
|
||||
def fake_register(turn_id: str) -> None:
|
||||
"""Record turn registration through the wrapped sync client."""
|
||||
calls.append(("register", turn_id))
|
||||
|
||||
def fake_unregister(turn_id: str) -> None:
|
||||
"""Record turn unregistration through the wrapped sync client."""
|
||||
calls.append(("unregister", turn_id))
|
||||
|
||||
def fake_next(turn_id: str) -> Notification:
|
||||
"""Return one routed notification through the wrapped sync client."""
|
||||
calls.append(("next", turn_id))
|
||||
return event
|
||||
|
||||
def fake_wait(turn_id: str) -> TurnCompletedNotification:
|
||||
"""Return one completion through the wrapped sync client."""
|
||||
calls.append(("wait", turn_id))
|
||||
return completed
|
||||
|
||||
client._sync.register_turn_notifications = fake_register # type: ignore[method-assign]
|
||||
client._sync.unregister_turn_notifications = fake_unregister # type: ignore[method-assign]
|
||||
client._sync.next_turn_notification = fake_next # type: ignore[method-assign]
|
||||
client._sync.wait_for_turn_completed = fake_wait # type: ignore[method-assign]
|
||||
|
||||
client.register_turn_notifications("turn-1")
|
||||
next_event = await client.next_turn_notification("turn-1")
|
||||
completed_event = await client.wait_for_turn_completed("turn-1")
|
||||
client.unregister_turn_notifications("turn-1")
|
||||
|
||||
return calls, next_event, completed_event.turn.id
|
||||
|
||||
calls, next_event, completed_turn_id = asyncio.run(scenario())
|
||||
|
||||
assert (
|
||||
calls,
|
||||
next_event,
|
||||
completed_turn_id,
|
||||
) == (
|
||||
[
|
||||
("register", "turn-1"),
|
||||
("next", "turn-1"),
|
||||
("wait", "turn-1"),
|
||||
("unregister", "turn-1"),
|
||||
],
|
||||
Notification(
|
||||
method="unknown/direct",
|
||||
payload=UnknownNotification(params={"turnId": "turn-1"}),
|
||||
),
|
||||
"turn-1",
|
||||
)
|
||||
790
sdk/python/tests/test_client_rpc_methods.py
Normal file
790
sdk/python/tests/test_client_rpc_methods.py
Normal file
@@ -0,0 +1,790 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import get_type_hints
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from openai_codex._runtime_requirements import CheckoutCapabilities
|
||||
from openai_codex.client import CodexClient, _params_dict
|
||||
from openai_codex.errors import CodexError
|
||||
from openai_codex.generated.notification_registry import notification_turn_id
|
||||
from openai_codex.generated.v2_all import (
|
||||
AbsolutePathBuf,
|
||||
AccountRateLimitsUpdatedNotification,
|
||||
AccountUpdatedNotification,
|
||||
AgentMessageDeltaNotification,
|
||||
ApplyPatchGuardianApprovalReviewAction,
|
||||
ApprovalsReviewer,
|
||||
AuthRecoveryNotification,
|
||||
CommandGuardianApprovalReviewAction,
|
||||
GetAccountResponse,
|
||||
ModelProviderConfigWriteParams,
|
||||
ModelProviderConfigWriteResponse,
|
||||
ModelProviderListResponse,
|
||||
PlanType,
|
||||
ReasoningEffort,
|
||||
ReasoningEffortOption,
|
||||
ReviewDelivery,
|
||||
ReviewStartParams,
|
||||
ThreadForkParams,
|
||||
ThreadListParams,
|
||||
ThreadQueueChangedNotification,
|
||||
ThreadResumeResponse,
|
||||
ThreadStartParams,
|
||||
ThreadTokenUsageUpdatedNotification,
|
||||
TurnCompletedNotification,
|
||||
TurnStartParams,
|
||||
WarningNotification,
|
||||
)
|
||||
from openai_codex.models import InitializeResponse, JsonObject, Notification, UnknownNotification
|
||||
from openai_codex.types import ThreadSource
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def test_model_provider_responses_preserve_wire_fields_for_each_auth_mode() -> None:
|
||||
wire = {
|
||||
"data": [
|
||||
{
|
||||
"id": "openai",
|
||||
"name": "OpenAI",
|
||||
"canEdit": False,
|
||||
"baseUrl": None,
|
||||
"settings": {"type": "openai"},
|
||||
},
|
||||
{
|
||||
"id": "amazon-bedrock",
|
||||
"name": "Amazon Bedrock Mantle",
|
||||
"canEdit": True,
|
||||
"baseUrl": None,
|
||||
"settings": {"type": "bedrock", "profile": "work", "region": "us-east-1"},
|
||||
},
|
||||
{
|
||||
"id": "gcp",
|
||||
"name": "Google Cloud Vertex AI",
|
||||
"canEdit": True,
|
||||
"baseUrl": None,
|
||||
"settings": {
|
||||
"type": "gcp",
|
||||
"projectId": "test-project",
|
||||
"location": "global",
|
||||
"credentialFile": "/host/adc.json",
|
||||
},
|
||||
},
|
||||
*[
|
||||
{
|
||||
"id": auth["mode"],
|
||||
"name": "Gateway",
|
||||
"canEdit": True,
|
||||
"baseUrl": "https://gateway.example.test",
|
||||
"settings": {"type": "customGateway", "auth": auth},
|
||||
}
|
||||
for auth in [
|
||||
{"mode": "none"},
|
||||
{"mode": "environmentVariable", "envKey": "GATEWAY_KEY"},
|
||||
{"mode": "externallyConfigured", "envKey": "EXTERNAL_KEY"},
|
||||
]
|
||||
],
|
||||
],
|
||||
"defaultProviderId": "gcp",
|
||||
"canChangeDefault": True,
|
||||
}
|
||||
response = ModelProviderListResponse.model_validate(wire)
|
||||
assert response.model_dump(mode="json", by_alias=True) == wire
|
||||
for provider in wire["data"]:
|
||||
saved = ModelProviderConfigWriteResponse.model_validate({"provider": provider})
|
||||
assert saved.model_dump(mode="json", by_alias=True) == {"provider": provider}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"settings",
|
||||
[
|
||||
{"type": "customGateway", "name": "Gateway", "baseUrl": "https://example.test"},
|
||||
{"type": "customGateway", "providerId": "team", "envKey": None},
|
||||
{"type": "bedrock", "providerId": "amazon-bedrock", "region": None},
|
||||
{"type": "bedrock", "providerId": "amazon-bedrock-runtime", "profile": "work"},
|
||||
{"type": "gcp", "providerId": "gcp", "credentialFile": None, "location": "global"},
|
||||
],
|
||||
)
|
||||
def test_provider_patch_preserves_explicit_null_and_omitted_fields(settings: dict) -> None:
|
||||
wire = {"settings": settings}
|
||||
params = ModelProviderConfigWriteParams.model_validate(wire)
|
||||
assert params.model_dump(mode="json", by_alias=True, exclude_unset=True) == wire
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"settings",
|
||||
[
|
||||
{"type": "bedrock", "providerId": "gcp", "region": "us-east-1"},
|
||||
{"type": "gcp", "providerId": "gcp", "region": "us-east-1"},
|
||||
],
|
||||
)
|
||||
def test_provider_patch_rejects_mismatched_id_or_fields(settings: dict) -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
ModelProviderConfigWriteParams.model_validate({"settings": settings})
|
||||
|
||||
|
||||
def test_inline_review_delivery_round_trips_as_an_enum() -> None:
|
||||
wire = {"threadId": "thread-1", "target": {"type": "uncommittedChanges"}, "delivery": "inline"}
|
||||
params = ReviewStartParams.model_validate(wire)
|
||||
|
||||
assert params.delivery is ReviewDelivery.inline
|
||||
assert params.model_dump(mode="json", by_alias=True) == wire
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("model", "fields"),
|
||||
[
|
||||
(
|
||||
CommandGuardianApprovalReviewAction,
|
||||
{"type": "command", "command": "pwd", "source": "shell"},
|
||||
),
|
||||
(
|
||||
ApplyPatchGuardianApprovalReviewAction,
|
||||
{"type": "applyPatch", "files": [AbsolutePathBuf("/workspace/file")]},
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_approval_review_paths_preserve_existing_wrappers(model, fields) -> None:
|
||||
action = model(cwd=AbsolutePathBuf("/workspace"), **fields)
|
||||
expected = {
|
||||
**fields,
|
||||
"cwd": "/workspace",
|
||||
}
|
||||
if "files" in expected:
|
||||
expected["files"] = ["/workspace/file"]
|
||||
assert action.model_dump(mode="json") == expected
|
||||
assert isinstance(action.cwd, AbsolutePathBuf)
|
||||
|
||||
|
||||
def _initialized_client(
|
||||
monkeypatch: pytest.MonkeyPatch, metadata: JsonObject
|
||||
) -> tuple[CodexClient, list[tuple[str, JsonObject | None]]]:
|
||||
client = CodexClient()
|
||||
requests: list[tuple[str, JsonObject | None]] = []
|
||||
|
||||
def request_raw(method: str, params: JsonObject | None) -> JsonObject:
|
||||
requests.append((method, params))
|
||||
return metadata if method == "initialize" else {}
|
||||
|
||||
monkeypatch.setattr(client, "_request_raw", request_raw)
|
||||
monkeypatch.setattr(client, "notify", lambda *_args: None)
|
||||
client.initialize()
|
||||
requests.clear()
|
||||
return client, requests
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "params"),
|
||||
[
|
||||
("turn/start", {"input": [], "toolOutput": {"name": "delegate", "output": "Investigate"}}),
|
||||
("turn/start", {"input": [], "turnTrigger": "automation"}),
|
||||
("turn/start", {"input": [], "serviceTierForTurn": "default"}),
|
||||
("thread/resume", {"threadId": "thread-1", "excludeTurns": False}),
|
||||
("thread/fork", {"threadId": "thread-1", "excludeTurns": True}),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("version", ["0.147.0", "0.149.0", "0.151.0-alpha.6", "unknown", ""])
|
||||
def test_new_options_reject_unsupported_runtime_before_sending(
|
||||
monkeypatch: pytest.MonkeyPatch, method: str, params: JsonObject, version: str
|
||||
) -> None:
|
||||
client, requests = _initialized_client(monkeypatch, {"userAgent": f"codex-cli/{version}"})
|
||||
|
||||
with pytest.raises(CodexError, match=r"Codex CLI 0\.151\.0 or newer"):
|
||||
client.request(method, params, response_model=InitializeResponse)
|
||||
|
||||
assert requests == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"metadata",
|
||||
[
|
||||
{"userAgent": "codex-cli/0.151.0 (Linux)"},
|
||||
{"userAgent": "codex-cli 0.153.0"},
|
||||
{"userAgent": "codex-cli/0.154.0-alpha.1"},
|
||||
{"userAgent": "codex-cli/0.154.0-alpha.1.2"},
|
||||
{"userAgent": "codex-cli/0.151.0.post1"},
|
||||
{"userAgent": "unknown", "serverInfo": {"name": "codex", "version": "0.153.0"}},
|
||||
],
|
||||
)
|
||||
def test_new_options_accept_supported_runtime_metadata(
|
||||
monkeypatch: pytest.MonkeyPatch, metadata: JsonObject
|
||||
) -> None:
|
||||
client, requests = _initialized_client(monkeypatch, metadata)
|
||||
params = {"input": [], "toolOutput": {"name": "delegate", "output": "Investigate"}}
|
||||
|
||||
client.request("turn/start", params, response_model=InitializeResponse)
|
||||
|
||||
assert requests == [("turn/start", params)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("supports_options", [True, False])
|
||||
def test_unversioned_checkout_probes_and_caches_its_own_schema(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, supports_options: bool
|
||||
) -> None:
|
||||
client, requests = _initialized_client(monkeypatch, {"userAgent": "codex-cli/0.0.0"})
|
||||
command = ("checkout-codex", "--config", "key=value", "app-server")
|
||||
client._checkout_capabilities = CheckoutCapabilities(
|
||||
command, str(tmp_path), {"CUSTOM": "value"}
|
||||
)
|
||||
probes = []
|
||||
|
||||
def generate_schema(args, **kwargs):
|
||||
probes.append((args[:-1], kwargs))
|
||||
output = Path(args[-1]) / "v2"
|
||||
output.mkdir()
|
||||
for name, fields in (
|
||||
("TurnStartParams", ["turnTrigger", "serviceTierForTurn"]),
|
||||
("ThreadResumeParams", ["excludeTurns"]),
|
||||
("ThreadForkParams", ["excludeTurns"]),
|
||||
):
|
||||
(output / f"{name}.json").write_text(
|
||||
json.dumps(
|
||||
{"properties": {field: {} for field in fields} if supports_options else {}}
|
||||
)
|
||||
)
|
||||
|
||||
monkeypatch.setattr("openai_codex._runtime_requirements.subprocess.run", generate_schema)
|
||||
for method, params in (
|
||||
("turn/start", {"input": [], "turnTrigger": "automation"}),
|
||||
("thread/resume", {"threadId": "thread-1", "excludeTurns": False}),
|
||||
):
|
||||
if supports_options:
|
||||
client.request(method, params, response_model=InitializeResponse)
|
||||
else:
|
||||
with pytest.raises(CodexError, match="checkout does not support"):
|
||||
client.request(method, params, response_model=InitializeResponse)
|
||||
assert len(requests) == (2 if supports_options else 0)
|
||||
assert probes == [
|
||||
(
|
||||
[*command, "generate-json-schema", "--experimental", "--out"],
|
||||
{
|
||||
"cwd": str(tmp_path),
|
||||
"env": {"CUSTOM": "value"},
|
||||
"capture_output": True,
|
||||
"check": True,
|
||||
"timeout": 30,
|
||||
},
|
||||
)
|
||||
]
|
||||
client.close()
|
||||
assert client._checkout_capabilities is None
|
||||
|
||||
|
||||
def test_unversioned_custom_launch_requires_verifiable_capabilities(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
client, requests = _initialized_client(monkeypatch, {"userAgent": "codex-cli/0.0.0"})
|
||||
with pytest.raises(CodexError, match="Cannot verify an unversioned CLI"):
|
||||
client.request(
|
||||
"turn/start", {"turnTrigger": "automation"}, response_model=InitializeResponse
|
||||
)
|
||||
assert requests == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("metadata", [{}, {"userAgent": "codex-cli/0.147.0"}])
|
||||
def test_ordinary_requests_keep_working_on_old_or_unknown_runtime(
|
||||
monkeypatch: pytest.MonkeyPatch, metadata: JsonObject
|
||||
) -> None:
|
||||
client, requests = _initialized_client(monkeypatch, metadata)
|
||||
params = {"input": [{"type": "text", "text": "Hello"}], "serviceTier": "default"}
|
||||
|
||||
client.request("turn/start", params, response_model=InitializeResponse)
|
||||
client.request("thread/resume", {"threadId": "thread-1"}, response_model=InitializeResponse)
|
||||
client.request("thread/fork", {"threadId": "thread-1"}, response_model=InitializeResponse)
|
||||
|
||||
assert requests == [
|
||||
("turn/start", params),
|
||||
("thread/resume", {"threadId": "thread-1"}),
|
||||
("thread/fork", {"threadId": "thread-1"}),
|
||||
]
|
||||
|
||||
|
||||
def test_new_options_require_fresh_initialize_metadata_after_close(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
client, requests = _initialized_client(monkeypatch, {"userAgent": "codex-cli/0.153.0"})
|
||||
client.close()
|
||||
|
||||
with pytest.raises(CodexError, match="reported version is 'unknown'"):
|
||||
client.request("thread/resume", {"excludeTurns": True}, response_model=InitializeResponse)
|
||||
|
||||
assert requests == []
|
||||
|
||||
|
||||
def test_generated_params_models_are_snake_case_and_dump_by_alias() -> None:
|
||||
params = ThreadListParams(search_term="needle", limit=5)
|
||||
|
||||
assert "search_term" in ThreadListParams.model_fields
|
||||
dumped = _params_dict(params)
|
||||
assert dumped == {"searchTerm": "needle", "limit": 5}
|
||||
|
||||
|
||||
def test_generated_v2_bundle_has_single_shared_plan_type_definition() -> None:
|
||||
source = (ROOT / "src" / "openai_codex" / "generated" / "v2_all.py").read_text()
|
||||
assert source.count("class PlanType(") == 1
|
||||
|
||||
|
||||
def test_plan_type_accepts_business_prolite_from_newer_runtime() -> None:
|
||||
"""New runtime plan values should remain typed when using a codex_bin override."""
|
||||
plan_type = "self_serve_business_prolite"
|
||||
response = GetAccountResponse.model_validate(
|
||||
{
|
||||
"account": {
|
||||
"type": "chatgpt",
|
||||
"email": "user@example.com",
|
||||
"planType": plan_type,
|
||||
},
|
||||
"requiresOpenaiAuth": True,
|
||||
}
|
||||
)
|
||||
assert response.account is not None
|
||||
assert response.account.root.plan_type.value == plan_type
|
||||
|
||||
client = CodexClient()
|
||||
account_updated = client._coerce_notification(
|
||||
"account/updated",
|
||||
{"authMode": "chatgpt", "planType": plan_type},
|
||||
)
|
||||
assert isinstance(account_updated.payload, AccountUpdatedNotification)
|
||||
assert account_updated.payload.plan_type == PlanType(plan_type)
|
||||
|
||||
rate_limits_updated = client._coerce_notification(
|
||||
"account/rateLimits/updated",
|
||||
{"rateLimits": {"planType": plan_type}},
|
||||
)
|
||||
assert isinstance(rate_limits_updated.payload, AccountRateLimitsUpdatedNotification)
|
||||
assert rate_limits_updated.payload.rate_limits.plan_type == PlanType(plan_type)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("effort", "wire_value"),
|
||||
[(ReasoningEffort.max, "max"), (ReasoningEffort.ultra, "ultra")],
|
||||
)
|
||||
def test_reasoning_effort_preserves_enum_constants_and_accepts_future_values(
|
||||
effort: ReasoningEffort, wire_value: str
|
||||
) -> None:
|
||||
"""Known effort members and new runtime values should share the enum-style API."""
|
||||
known_option = ReasoningEffortOption.model_validate(
|
||||
{"description": "Balanced", "reasoningEffort": "medium"}
|
||||
)
|
||||
future_option = ReasoningEffortOption.model_validate(
|
||||
{"description": "Future", "reasoningEffort": "future"}
|
||||
)
|
||||
turn_params = TurnStartParams(
|
||||
thread_id="thread-1",
|
||||
input=[],
|
||||
effort=effort,
|
||||
)
|
||||
|
||||
assert {
|
||||
"known_member": ReasoningEffort.medium.value,
|
||||
"known_option": known_option.reasoning_effort.value,
|
||||
"future_option": future_option.reasoning_effort.value,
|
||||
"turn_effort": _params_dict(turn_params)["effort"],
|
||||
} == {
|
||||
"known_member": "medium",
|
||||
"known_option": "medium",
|
||||
"future_option": "future",
|
||||
"turn_effort": wire_value,
|
||||
}
|
||||
|
||||
|
||||
def test_thread_source_preserves_enum_constants_and_accepts_future_values() -> None:
|
||||
"""Known thread sources and new runtime values should share the enum-style API."""
|
||||
start_params = ThreadStartParams(thread_source=ThreadSource.user)
|
||||
fork_params = ThreadForkParams(
|
||||
thread_id="thread-1",
|
||||
thread_source=ThreadSource("future_source"),
|
||||
)
|
||||
|
||||
assert {
|
||||
"known_member": ThreadSource.user.value,
|
||||
"subagent_member": ThreadSource.subagent.value,
|
||||
"memory_member": ThreadSource.memory_consolidation.value,
|
||||
"start_source": _params_dict(start_params)["threadSource"],
|
||||
"fork_source": _params_dict(fork_params)["threadSource"],
|
||||
} == {
|
||||
"known_member": "user",
|
||||
"subagent_member": "subagent",
|
||||
"memory_member": "memory_consolidation",
|
||||
"start_source": "user",
|
||||
"fork_source": "future_source",
|
||||
}
|
||||
|
||||
|
||||
def test_thread_resume_response_accepts_auto_review_reviewer() -> None:
|
||||
"""Generated response models should keep accepting the auto review enum value."""
|
||||
response = ThreadResumeResponse.model_validate(
|
||||
{
|
||||
"approvalPolicy": "on-request",
|
||||
"approvalsReviewer": "auto_review",
|
||||
"cwd": "/tmp",
|
||||
"model": "gpt-5",
|
||||
"modelProvider": "openai",
|
||||
"sandbox": {"type": "dangerFullAccess"},
|
||||
"thread": {
|
||||
"cliVersion": "1.0.0",
|
||||
"createdAt": 1,
|
||||
"cwd": "/tmp",
|
||||
"ephemeral": False,
|
||||
"id": "thread-1",
|
||||
"modelProvider": "openai",
|
||||
"preview": "",
|
||||
# The pinned runtime schema requires the session id on threads.
|
||||
"sessionId": "session-1",
|
||||
"source": "cli",
|
||||
"status": {"type": "idle"},
|
||||
"turns": [],
|
||||
"updatedAt": 1,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
assert response.approvals_reviewer is ApprovalsReviewer.auto_review
|
||||
|
||||
|
||||
def test_notifications_are_typed_with_canonical_v2_methods() -> None:
|
||||
client = CodexClient()
|
||||
event = client._coerce_notification(
|
||||
"thread/tokenUsage/updated",
|
||||
{
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-1",
|
||||
"tokenUsage": {
|
||||
"last": {
|
||||
"cachedInputTokens": 0,
|
||||
"inputTokens": 1,
|
||||
"outputTokens": 2,
|
||||
"reasoningOutputTokens": 0,
|
||||
"totalTokens": 3,
|
||||
},
|
||||
"total": {
|
||||
"cachedInputTokens": 0,
|
||||
"inputTokens": 1,
|
||||
"outputTokens": 2,
|
||||
"reasoningOutputTokens": 0,
|
||||
"totalTokens": 3,
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert event.method == "thread/tokenUsage/updated"
|
||||
assert isinstance(event.payload, ThreadTokenUsageUpdatedNotification)
|
||||
assert event.payload.turn_id == "turn-1"
|
||||
|
||||
|
||||
def test_unknown_notifications_fall_back_to_unknown_payloads() -> None:
|
||||
client = CodexClient()
|
||||
event = client._coerce_notification(
|
||||
"unknown/notification",
|
||||
{
|
||||
"id": "evt-1",
|
||||
"conversationId": "thread-1",
|
||||
"msg": {"type": "turn_aborted"},
|
||||
},
|
||||
)
|
||||
|
||||
assert event.method == "unknown/notification"
|
||||
assert isinstance(event.payload, UnknownNotification)
|
||||
assert event.payload.params["msg"] == {"type": "turn_aborted"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "params", "expected"),
|
||||
[
|
||||
(
|
||||
"modelProvider/authRecoveryCompleted",
|
||||
{
|
||||
"provider": "openai",
|
||||
"message": "Authentication recovered",
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-1",
|
||||
},
|
||||
AuthRecoveryNotification(
|
||||
provider="openai",
|
||||
message="Authentication recovered",
|
||||
thread_id="thread-1",
|
||||
turn_id="turn-1",
|
||||
),
|
||||
),
|
||||
(
|
||||
"thread/queue/changed",
|
||||
{"threadId": "thread-1"},
|
||||
ThreadQueueChangedNotification(thread_id="thread-1"),
|
||||
),
|
||||
("warning", {"message": "heads up"}, WarningNotification(message="heads up")),
|
||||
(
|
||||
"future/notification",
|
||||
{"newField": "value"},
|
||||
UnknownNotification(params={"newField": "value"}),
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_decoded_notifications_match_the_declared_payload_type(method, params, expected) -> None:
|
||||
event = CodexClient()._coerce_notification(method, params)
|
||||
|
||||
assert event == Notification(method=method, payload=expected)
|
||||
assert isinstance(event.payload, get_type_hints(Notification)["payload"])
|
||||
|
||||
|
||||
def test_invalid_notification_payload_falls_back_to_unknown() -> None:
|
||||
client = CodexClient()
|
||||
event = client._coerce_notification("thread/tokenUsage/updated", {"threadId": "missing"})
|
||||
|
||||
assert event.method == "thread/tokenUsage/updated"
|
||||
assert isinstance(event.payload, UnknownNotification)
|
||||
|
||||
|
||||
def test_generated_notification_turn_id_handles_known_payload_shapes() -> None:
|
||||
"""Generated routing metadata should cover direct, nested, and unscoped payloads."""
|
||||
direct = AgentMessageDeltaNotification.model_validate(
|
||||
{
|
||||
"delta": "hello",
|
||||
"itemId": "item-1",
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-1",
|
||||
}
|
||||
)
|
||||
nested = TurnCompletedNotification.model_validate(
|
||||
{
|
||||
"threadId": "thread-1",
|
||||
"turn": {"id": "turn-2", "items": [], "status": "completed"},
|
||||
}
|
||||
)
|
||||
unscoped = WarningNotification(message="heads up")
|
||||
|
||||
assert [
|
||||
notification_turn_id(direct),
|
||||
notification_turn_id(nested),
|
||||
notification_turn_id(unscoped),
|
||||
] == ["turn-1", "turn-2", None]
|
||||
|
||||
|
||||
def test_turn_notification_router_demuxes_registered_turns() -> None:
|
||||
"""The router should deliver out-of-order turn events to the matching queues."""
|
||||
client = CodexClient()
|
||||
client.register_turn_notifications("turn-1")
|
||||
client.register_turn_notifications("turn-2")
|
||||
|
||||
client._router.route_notification(
|
||||
client._coerce_notification(
|
||||
"item/agentMessage/delta",
|
||||
{
|
||||
"delta": "two",
|
||||
"itemId": "item-2",
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-2",
|
||||
},
|
||||
)
|
||||
)
|
||||
client._router.route_notification(
|
||||
client._coerce_notification(
|
||||
"item/agentMessage/delta",
|
||||
{
|
||||
"delta": "one",
|
||||
"itemId": "item-1",
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-1",
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
first = client.next_turn_notification("turn-1")
|
||||
second = client.next_turn_notification("turn-2")
|
||||
|
||||
assert isinstance(first.payload, AgentMessageDeltaNotification)
|
||||
assert isinstance(second.payload, AgentMessageDeltaNotification)
|
||||
assert [
|
||||
(first.method, first.payload.delta),
|
||||
(second.method, second.payload.delta),
|
||||
] == [
|
||||
("item/agentMessage/delta", "one"),
|
||||
("item/agentMessage/delta", "two"),
|
||||
]
|
||||
|
||||
|
||||
def test_goal_notification_router_routes_by_thread_id() -> None:
|
||||
"""A goal operation should receive turn notifications across physical turn ids."""
|
||||
client = CodexClient()
|
||||
state = client.register_goal_operation("thread-1")
|
||||
|
||||
client._router.route_notification(
|
||||
client._coerce_notification(
|
||||
"item/agentMessage/delta",
|
||||
{
|
||||
"delta": "continued",
|
||||
"itemId": "item-1",
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-2",
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
event = client.next_goal_notification(state)
|
||||
|
||||
assert isinstance(event.payload, AgentMessageDeltaNotification)
|
||||
assert (event.method, event.payload.delta) == (
|
||||
"item/agentMessage/delta",
|
||||
"continued",
|
||||
)
|
||||
|
||||
|
||||
def test_client_reader_routes_interleaved_turn_notifications_by_turn_id() -> None:
|
||||
"""Reader-loop routing should preserve order within each interleaved turn stream."""
|
||||
client = CodexClient()
|
||||
client.register_turn_notifications("turn-1")
|
||||
client.register_turn_notifications("turn-2")
|
||||
|
||||
messages: list[dict[str, object]] = [
|
||||
{
|
||||
"method": "item/agentMessage/delta",
|
||||
"params": {
|
||||
"delta": "one-a",
|
||||
"itemId": "item-1",
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-1",
|
||||
},
|
||||
},
|
||||
{
|
||||
"method": "item/agentMessage/delta",
|
||||
"params": {
|
||||
"delta": "two-a",
|
||||
"itemId": "item-2",
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-2",
|
||||
},
|
||||
},
|
||||
{
|
||||
"method": "item/agentMessage/delta",
|
||||
"params": {
|
||||
"delta": "one-b",
|
||||
"itemId": "item-3",
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-1",
|
||||
},
|
||||
},
|
||||
{
|
||||
"method": "item/agentMessage/delta",
|
||||
"params": {
|
||||
"delta": "two-b",
|
||||
"itemId": "item-4",
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-2",
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
def fake_read_message() -> dict[str, object]:
|
||||
"""Feed the reader loop a realistic interleaved stdout sequence."""
|
||||
if messages:
|
||||
return messages.pop(0)
|
||||
raise EOFError
|
||||
|
||||
client._read_message = fake_read_message # type: ignore[method-assign]
|
||||
client._reader_loop()
|
||||
|
||||
first_turn_events = [
|
||||
client.next_turn_notification("turn-1"),
|
||||
client.next_turn_notification("turn-1"),
|
||||
]
|
||||
second_turn_events = [
|
||||
client.next_turn_notification("turn-2"),
|
||||
client.next_turn_notification("turn-2"),
|
||||
]
|
||||
|
||||
first_turn_deltas = [
|
||||
event.payload.delta
|
||||
for event in first_turn_events
|
||||
if isinstance(event.payload, AgentMessageDeltaNotification)
|
||||
]
|
||||
second_turn_deltas = [
|
||||
event.payload.delta
|
||||
for event in second_turn_events
|
||||
if isinstance(event.payload, AgentMessageDeltaNotification)
|
||||
]
|
||||
assert (first_turn_deltas, second_turn_deltas) == (
|
||||
["one-a", "one-b"],
|
||||
["two-a", "two-b"],
|
||||
)
|
||||
|
||||
|
||||
def test_turn_notification_router_starts_at_explicit_registration() -> None:
|
||||
"""Explicit registration receives events from when the caller attaches."""
|
||||
client = CodexClient()
|
||||
client.register_turn_notifications("turn-1")
|
||||
client._router.route_notification(
|
||||
client._coerce_notification(
|
||||
"item/agentMessage/delta",
|
||||
{
|
||||
"delta": "early",
|
||||
"itemId": "item-1",
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-1",
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
event = client.next_turn_notification("turn-1")
|
||||
|
||||
assert isinstance(event.payload, AgentMessageDeltaNotification)
|
||||
assert (event.method, event.payload.delta) == (
|
||||
"item/agentMessage/delta",
|
||||
"early",
|
||||
)
|
||||
|
||||
|
||||
def test_turn_notification_router_clears_unregistered_turn_when_completed() -> None:
|
||||
"""A completed unregistered turn should not leave a pending queue behind."""
|
||||
client = CodexClient()
|
||||
client._router.route_notification(
|
||||
client._coerce_notification(
|
||||
"item/agentMessage/delta",
|
||||
{
|
||||
"delta": "early",
|
||||
"itemId": "item-1",
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-1",
|
||||
},
|
||||
)
|
||||
)
|
||||
client._router.route_notification(
|
||||
client._coerce_notification(
|
||||
"turn/completed",
|
||||
{
|
||||
"threadId": "thread-1",
|
||||
"turn": {"id": "turn-1", "items": [], "status": "completed"},
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
assert client._router._turn_states == {}
|
||||
|
||||
|
||||
def test_turn_notification_router_routes_unknown_turn_notifications() -> None:
|
||||
"""Unknown notifications should still route when their raw params carry a turn id."""
|
||||
client = CodexClient()
|
||||
client.register_turn_notifications("turn-1")
|
||||
client.register_turn_notifications("turn-2")
|
||||
|
||||
client._router.route_notification(
|
||||
Notification(
|
||||
method="unknown/direct",
|
||||
payload=UnknownNotification(params={"turnId": "turn-1"}),
|
||||
)
|
||||
)
|
||||
client._router.route_notification(
|
||||
Notification(
|
||||
method="unknown/nested",
|
||||
payload=UnknownNotification(params={"turn": {"id": "turn-2"}}),
|
||||
)
|
||||
)
|
||||
|
||||
first = client.next_turn_notification("turn-1")
|
||||
second = client.next_turn_notification("turn-2")
|
||||
|
||||
assert [first.method, second.method] == ["unknown/direct", "unknown/nested"]
|
||||
144
sdk/python/tests/test_contract_generation.py
Normal file
144
sdk/python/tests/test_contract_generation.py
Normal file
@@ -0,0 +1,144 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import os
|
||||
import runpy
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
GENERATED_TARGETS = [
|
||||
Path("src/openai_codex/generated/notification_registry.py"),
|
||||
Path("src/openai_codex/generated/v2_all.py"),
|
||||
Path("src/openai_codex/api.py"),
|
||||
]
|
||||
|
||||
|
||||
def _snapshot_target(root: Path, rel_path: Path) -> dict[str, bytes] | bytes | None:
|
||||
"""Capture one generated artifact so regeneration drift is easy to compare."""
|
||||
target = root / rel_path
|
||||
if not target.exists():
|
||||
return None
|
||||
if target.is_file():
|
||||
return target.read_bytes()
|
||||
|
||||
snapshot: dict[str, bytes] = {}
|
||||
for path in sorted(target.rglob("*")):
|
||||
if path.is_file() and "__pycache__" not in path.parts:
|
||||
snapshot[str(path.relative_to(target))] = path.read_bytes()
|
||||
return snapshot
|
||||
|
||||
|
||||
def _snapshot_targets(root: Path) -> dict[str, dict[str, bytes] | bytes | None]:
|
||||
"""Capture all checked-in generated artifacts before and after regeneration."""
|
||||
return {str(rel_path): _snapshot_target(root, rel_path) for rel_path in GENERATED_TARGETS}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("format_output", [True, False])
|
||||
def test_generated_files_are_up_to_date(tmp_path, format_output):
|
||||
"""Both generation modes preserve the reviewed API, with optional formatting."""
|
||||
before = _snapshot_targets(ROOT)
|
||||
sdk = tmp_path / "sdk" / "python"
|
||||
sdk.mkdir(parents=True)
|
||||
for directory in ("src", "scripts"):
|
||||
shutil.copytree(
|
||||
ROOT / directory, sdk / directory, ignore=shutil.ignore_patterns("__pycache__")
|
||||
)
|
||||
for name in ("pyproject.toml", "release_version.py"):
|
||||
shutil.copyfile(ROOT / name, sdk / name)
|
||||
|
||||
env = os.environ.copy()
|
||||
python_bin = str(Path(sys.executable).parent)
|
||||
env["PATH"] = f"{python_bin}{os.pathsep}{env.get('PATH', '')}"
|
||||
|
||||
command = [
|
||||
sys.executable,
|
||||
"scripts/update_sdk_artifacts.py",
|
||||
"generate-types",
|
||||
"--schema-dir",
|
||||
str(ROOT.parents[1] / "codex-rs/app-server-protocol/schema/json"),
|
||||
]
|
||||
if not format_output:
|
||||
command.append("--no-format")
|
||||
subprocess.run(
|
||||
command,
|
||||
cwd=sdk,
|
||||
check=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
after = _snapshot_targets(sdk)
|
||||
if format_output:
|
||||
assert before == after, "Generated files drifted after regeneration"
|
||||
else:
|
||||
assert [ast.dump(ast.parse((ROOT / path).read_bytes())) for path in GENERATED_TARGETS] == [
|
||||
ast.dump(ast.parse((sdk / path).read_bytes())) for path in GENERATED_TARGETS
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["repository", "scratch", "experimental"])
|
||||
def test_schema_refresh_only_updates_python_for_repository_schemas(monkeypatch, tmp_path, mode):
|
||||
script = ROOT.parents[1] / "codex-rs/app-server-protocol/scripts/write_schema_fixtures.py"
|
||||
arguments = {
|
||||
"repository": [],
|
||||
"scratch": ["--schema-root", str(tmp_path / "schema")],
|
||||
"experimental": ["--experimental"],
|
||||
}[mode]
|
||||
calls = []
|
||||
monkeypatch.setattr(sys, "argv", [str(script), *arguments])
|
||||
monkeypatch.setattr(subprocess, "run", lambda args, **kwargs: calls.append((args, kwargs)))
|
||||
|
||||
runpy.run_path(str(script), run_name="__main__")
|
||||
|
||||
assert [args[0] for args, _kwargs in calls] == (
|
||||
["cargo", "uv"] if mode == "repository" else ["cargo"]
|
||||
)
|
||||
assert all(kwargs["check"] for _args, kwargs in calls)
|
||||
if mode == "repository":
|
||||
assert calls[1][0][-3:] == [
|
||||
"generate-types",
|
||||
"--schema-dir",
|
||||
str(ROOT.parents[1] / "codex-rs/app-server-protocol/schema/json"),
|
||||
]
|
||||
|
||||
|
||||
def test_schema_generation_failure_does_not_update_python(monkeypatch):
|
||||
script = ROOT.parents[1] / "codex-rs/app-server-protocol/scripts/write_schema_fixtures.py"
|
||||
calls = []
|
||||
|
||||
def fail(args, **_kwargs):
|
||||
calls.append(args[0])
|
||||
raise subprocess.CalledProcessError(1, args)
|
||||
|
||||
monkeypatch.setattr(sys, "argv", [str(script)])
|
||||
monkeypatch.setattr(subprocess, "run", fail)
|
||||
with pytest.raises(subprocess.CalledProcessError):
|
||||
runpy.run_path(str(script), run_name="__main__")
|
||||
assert calls == ["cargo"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
[
|
||||
{"type": "modelProviderNotConfigured", "modelProvider": "old-provider"},
|
||||
{
|
||||
"type": "modelProviderMismatch",
|
||||
"modelProvider": "old-provider",
|
||||
"currentModelProvider": "current-provider",
|
||||
},
|
||||
{
|
||||
"type": "modelProviderPolicyConflict",
|
||||
"modelProvider": "old-provider",
|
||||
"requiredModelProvider": "required-provider",
|
||||
},
|
||||
],
|
||||
)
|
||||
def test_model_provider_errors_round_trip_wire_names(payload):
|
||||
from openai_codex.generated.v2_all import ModelProviderError
|
||||
|
||||
error = ModelProviderError.model_validate(payload)
|
||||
assert error.model_dump(by_alias=True) == payload
|
||||
37
sdk/python/tests/test_mcp_conformance_fixtures.py
Normal file
37
sdk/python/tests/test_mcp_conformance_fixtures.py
Normal file
@@ -0,0 +1,37 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_mcp_conformance_fixture_self_tests() -> None:
|
||||
repository_root = Path(__file__).resolve().parents[3]
|
||||
candidates = (
|
||||
repository_root / "public" / "scripts" / "mcp_conformance",
|
||||
repository_root / "scripts" / "mcp_conformance",
|
||||
)
|
||||
fixture_directory = next((candidate for candidate in candidates if candidate.is_dir()), None)
|
||||
assert fixture_directory is not None, (
|
||||
"MCP conformance fixtures are missing; checked "
|
||||
+ " and ".join(str(candidate) for candidate in candidates)
|
||||
)
|
||||
|
||||
env = os.environ.copy()
|
||||
env["PYTEST_DISABLE_PLUGIN_AUTOLOAD"] = "1"
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "pytest", "-q", str(fixture_directory)],
|
||||
cwd=repository_root,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == 0, (
|
||||
f"MCP conformance fixture self-tests failed with exit "
|
||||
f"{result.returncode}.\n"
|
||||
f"Fixture directory: {fixture_directory}\n"
|
||||
f"STDOUT:\n{result.stdout}\n"
|
||||
f"STDERR:\n{result.stderr}"
|
||||
)
|
||||
358
sdk/python/tests/test_public_api_runtime_behavior.py
Normal file
358
sdk/python/tests/test_public_api_runtime_behavior.py
Normal file
@@ -0,0 +1,358 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
|
||||
import openai_codex.api as public_api_module
|
||||
from openai_codex.api import (
|
||||
ApprovalMode,
|
||||
AsyncCodex,
|
||||
Codex,
|
||||
ExternalMessage,
|
||||
Sandbox,
|
||||
TextInput,
|
||||
)
|
||||
from openai_codex.client import _params_dict
|
||||
from openai_codex.generated.v2_all import TurnCompletedNotification, TurnStartParams
|
||||
from openai_codex.models import InitializeResponse, Notification
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _approval_settings(params: list[Any]) -> list[dict[str, object]]:
|
||||
"""Return serialized approval settings from captured Pydantic params."""
|
||||
return [
|
||||
{
|
||||
key: value
|
||||
for key, value in param.model_dump(
|
||||
by_alias=True,
|
||||
exclude_none=True,
|
||||
mode="json",
|
||||
).items()
|
||||
if key in {"approvalPolicy", "approvalsReviewer"}
|
||||
}
|
||||
for param in params
|
||||
]
|
||||
|
||||
|
||||
def test_codex_init_failure_closes_client(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
closed: list[bool] = []
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, config=None) -> None: # noqa: ANN001,ARG002
|
||||
self._closed = False
|
||||
|
||||
def start(self) -> None:
|
||||
return None
|
||||
|
||||
def initialize(self) -> InitializeResponse:
|
||||
return InitializeResponse.model_validate({})
|
||||
|
||||
def close(self) -> None:
|
||||
self._closed = True
|
||||
closed.append(True)
|
||||
|
||||
monkeypatch.setattr(public_api_module, "CodexClient", FakeClient)
|
||||
|
||||
with pytest.raises(RuntimeError, match="missing required metadata"):
|
||||
Codex()
|
||||
|
||||
assert closed == [True]
|
||||
|
||||
|
||||
def test_async_codex_init_failure_closes_client() -> None:
|
||||
async def scenario() -> None:
|
||||
codex = AsyncCodex()
|
||||
close_calls = 0
|
||||
|
||||
async def fake_start() -> None:
|
||||
return None
|
||||
|
||||
async def fake_initialize() -> InitializeResponse:
|
||||
return InitializeResponse.model_validate({})
|
||||
|
||||
async def fake_close() -> None:
|
||||
nonlocal close_calls
|
||||
close_calls += 1
|
||||
|
||||
codex._client.start = fake_start # type: ignore[method-assign]
|
||||
codex._client.initialize = fake_initialize # type: ignore[method-assign]
|
||||
codex._client.close = fake_close # type: ignore[method-assign]
|
||||
|
||||
with pytest.raises(RuntimeError, match="missing required metadata"):
|
||||
await codex.models()
|
||||
|
||||
assert close_calls == 1
|
||||
assert codex._initialized is False
|
||||
assert codex._init is None
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_async_codex_initializes_only_once_under_concurrency() -> None:
|
||||
async def scenario() -> None:
|
||||
codex = AsyncCodex()
|
||||
start_calls = 0
|
||||
initialize_calls = 0
|
||||
ready = asyncio.Event()
|
||||
|
||||
async def fake_start() -> None:
|
||||
nonlocal start_calls
|
||||
start_calls += 1
|
||||
|
||||
async def fake_initialize() -> InitializeResponse:
|
||||
nonlocal initialize_calls
|
||||
initialize_calls += 1
|
||||
ready.set()
|
||||
await asyncio.sleep(0.02)
|
||||
return InitializeResponse.model_validate(
|
||||
{
|
||||
"userAgent": "codex-cli/1.2.3",
|
||||
"serverInfo": {"name": "codex-cli", "version": "1.2.3"},
|
||||
}
|
||||
)
|
||||
|
||||
async def fake_model_list(include_hidden: bool = False): # noqa: ANN202,ARG001
|
||||
await ready.wait()
|
||||
return object()
|
||||
|
||||
codex._client.start = fake_start # type: ignore[method-assign]
|
||||
codex._client.initialize = fake_initialize # type: ignore[method-assign]
|
||||
codex._client.model_list = fake_model_list # type: ignore[method-assign]
|
||||
|
||||
await asyncio.gather(codex.models(), codex.models())
|
||||
|
||||
assert start_calls == 1
|
||||
assert initialize_calls == 1
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api_type", [Codex, AsyncCodex])
|
||||
@pytest.mark.parametrize(
|
||||
("options", "expected"),
|
||||
[
|
||||
({}, {}),
|
||||
({"include_turns": None}, {}),
|
||||
({"include_turns": True}, {"excludeTurns": False}),
|
||||
({"include_turns": False}, {"excludeTurns": True}),
|
||||
],
|
||||
)
|
||||
def test_include_turns_preserves_omission_and_inverts_explicit_values(
|
||||
api_type, options, expected
|
||||
) -> None:
|
||||
async def scenario() -> None:
|
||||
async_api = api_type is AsyncCodex
|
||||
rpc = AsyncMock if async_api else Mock
|
||||
thread_response = SimpleNamespace(thread=SimpleNamespace(id="thread-2"))
|
||||
client = SimpleNamespace(
|
||||
thread_resume=rpc(return_value=thread_response),
|
||||
thread_fork=rpc(return_value=thread_response),
|
||||
)
|
||||
codex = api_type.__new__(api_type)
|
||||
codex._client = client
|
||||
codex._initialized = True
|
||||
|
||||
for method in ("thread_resume", "thread_fork"):
|
||||
thread = getattr(codex, method)("thread-1", **options)
|
||||
if async_api:
|
||||
thread = await thread
|
||||
assert thread.id == "thread-2"
|
||||
assert _params_dict(getattr(client, method).call_args.args[1]) == {
|
||||
"threadId": "thread-1",
|
||||
**expected,
|
||||
}
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api_type", [Codex, AsyncCodex])
|
||||
@pytest.mark.parametrize("method", ["run", "turn"])
|
||||
@pytest.mark.parametrize(
|
||||
"content", [None, "External update", [{"type": "input_text", "text": "External update"}]]
|
||||
)
|
||||
def test_turn_inputs_and_options_reach_the_client(api_type, method, content) -> None:
|
||||
"""User and external inputs preserve distinct wire representations for every entry point."""
|
||||
|
||||
async def scenario() -> None:
|
||||
async_api = api_type is AsyncCodex
|
||||
rpc = AsyncMock if async_api else Mock
|
||||
completed = Notification(
|
||||
method="turn/completed",
|
||||
payload=TurnCompletedNotification.model_validate(
|
||||
{
|
||||
"threadId": "thread-1",
|
||||
"turn": {"id": "turn-1", "items": [], "status": "completed"},
|
||||
}
|
||||
),
|
||||
)
|
||||
subscription = SimpleNamespace(next=Mock(return_value=completed), close=Mock())
|
||||
client = SimpleNamespace(
|
||||
_start_turn=rpc(
|
||||
return_value=(SimpleNamespace(turn=SimpleNamespace(id="turn-1")), subscription)
|
||||
),
|
||||
)
|
||||
codex = api_type.__new__(api_type)
|
||||
codex._client = client
|
||||
codex._initialized = True
|
||||
thread = (
|
||||
public_api_module.AsyncThread(codex, "thread-1")
|
||||
if async_api
|
||||
else public_api_module.Thread(client, "thread-1")
|
||||
)
|
||||
input = (
|
||||
"Continue."
|
||||
if content is None
|
||||
else ExternalMessage(tool_name="notifications", namespace="slack", content=content)
|
||||
)
|
||||
turn = getattr(thread, method)(
|
||||
input,
|
||||
service_tier="priority",
|
||||
turn_service_tier="default",
|
||||
source="automation",
|
||||
)
|
||||
if async_api:
|
||||
turn = await turn
|
||||
assert turn.id == "turn-1"
|
||||
expected_input = (
|
||||
[{"type": "text", "text": "Continue.", "text_elements": []}] if content is None else []
|
||||
)
|
||||
expected_tool_output = (
|
||||
{}
|
||||
if content is None
|
||||
else {
|
||||
"toolOutput": {"name": "notifications", "namespace": "slack", "output": content},
|
||||
}
|
||||
)
|
||||
assert _params_dict(client._start_turn.call_args.kwargs["params"]) == {
|
||||
"threadId": "thread-1",
|
||||
"input": expected_input,
|
||||
"serviceTier": "priority",
|
||||
"serviceTierForTurn": "default",
|
||||
"turnTrigger": "automation",
|
||||
**expected_tool_output,
|
||||
}
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api_type", [Codex, AsyncCodex])
|
||||
def test_external_messages_cannot_be_mixed_with_user_input_or_sent_as_user_steering(
|
||||
api_type,
|
||||
) -> None:
|
||||
async def scenario() -> None:
|
||||
async_api = api_type is AsyncCodex
|
||||
rpc = AsyncMock if async_api else Mock
|
||||
client = SimpleNamespace(
|
||||
_start_turn=rpc(), turn_steer=rpc(), _subscribe_turn_notifications=Mock()
|
||||
)
|
||||
codex = api_type.__new__(api_type)
|
||||
codex._client = client
|
||||
codex._initialized = True
|
||||
thread = (
|
||||
public_api_module.AsyncThread(codex, "thread-1")
|
||||
if async_api
|
||||
else public_api_module.Thread(client, "thread-1")
|
||||
)
|
||||
handle = (
|
||||
public_api_module.AsyncTurnHandle(codex, "thread-1", "turn-1")
|
||||
if async_api
|
||||
else public_api_module.TurnHandle(client, "thread-1", "turn-1")
|
||||
)
|
||||
external = ExternalMessage(tool_name="notifications", content="Untrusted update")
|
||||
for operation, input in (
|
||||
(thread.turn, [TextInput("User request"), external]),
|
||||
(handle.steer, external),
|
||||
):
|
||||
with pytest.raises(TypeError):
|
||||
result = operation(input)
|
||||
if async_api:
|
||||
await result
|
||||
with pytest.raises(ValueError, match="tool_name"):
|
||||
result = thread.turn(ExternalMessage(tool_name=" ", content="Untrusted update"))
|
||||
if async_api:
|
||||
await result
|
||||
client._start_turn.assert_not_called()
|
||||
client.turn_steer.assert_not_called()
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def _approval_mode_turn_params(approval_mode: ApprovalMode) -> TurnStartParams:
|
||||
"""Build real generated turn params from one public approval mode."""
|
||||
approval_policy, approvals_reviewer = public_api_module._approval_mode_settings(approval_mode)
|
||||
return TurnStartParams(
|
||||
thread_id="thread-1",
|
||||
input=[],
|
||||
approval_policy=approval_policy,
|
||||
approvals_reviewer=approvals_reviewer,
|
||||
)
|
||||
|
||||
|
||||
def test_approval_modes_serialize_to_expected_start_params() -> None:
|
||||
"""ApprovalMode should map to the app-server params sent for new work."""
|
||||
assert {
|
||||
mode.value: _approval_settings([_approval_mode_turn_params(mode)])[0]
|
||||
for mode in ApprovalMode
|
||||
} == {
|
||||
"deny_all": {"approvalPolicy": "never"},
|
||||
"auto_review": {
|
||||
"approvalPolicy": "on-request",
|
||||
"approvalsReviewer": "auto_review",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_unknown_approval_mode_is_rejected() -> None:
|
||||
"""Invalid approval modes should fail before params are constructed."""
|
||||
with pytest.raises(ValueError, match="deny_all, auto_review"):
|
||||
public_api_module._approval_mode_settings("allow_all") # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_sandbox_presets_serialize_for_threads_and_turns() -> None:
|
||||
"""One public sandbox enum should map to both stable wire representations."""
|
||||
assert {
|
||||
sandbox.name: public_api_module._sandbox_mode(sandbox).value for sandbox in Sandbox
|
||||
} == {
|
||||
"read_only": "read-only",
|
||||
"workspace_write": "workspace-write",
|
||||
"full_access": "danger-full-access",
|
||||
}
|
||||
assert {
|
||||
sandbox.name: public_api_module._sandbox_policy(sandbox).model_dump(
|
||||
by_alias=True,
|
||||
mode="json",
|
||||
)
|
||||
for sandbox in Sandbox
|
||||
} == {
|
||||
"read_only": {"networkAccess": False, "type": "readOnly"},
|
||||
"workspace_write": {
|
||||
"excludeSlashTmp": False,
|
||||
"excludeTmpdirEnvVar": False,
|
||||
"networkAccess": False,
|
||||
"type": "workspaceWrite",
|
||||
"writableRoots": [],
|
||||
},
|
||||
"full_access": {"type": "dangerFullAccess"},
|
||||
}
|
||||
|
||||
|
||||
def test_raw_sandbox_strings_are_rejected() -> None:
|
||||
"""Callers should use the discoverable enum rather than memorizing values."""
|
||||
with pytest.raises(ValueError, match="Sandbox\\.workspace_write"):
|
||||
public_api_module._sandbox_mode("workspace") # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_retry_examples_compare_status_with_enum() -> None:
|
||||
for path in (
|
||||
ROOT / "examples" / "10_error_handling_and_retry" / "sync.py",
|
||||
ROOT / "examples" / "10_error_handling_and_retry" / "async.py",
|
||||
):
|
||||
source = path.read_text()
|
||||
assert '== "failed"' not in source
|
||||
assert "TurnStatus.failed" in source
|
||||
579
sdk/python/tests/test_public_api_signatures.py
Normal file
579
sdk/python/tests/test_public_api_signatures.py
Normal file
@@ -0,0 +1,579 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.resources as resources
|
||||
import inspect
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import openai_codex
|
||||
import openai_codex.types as public_types
|
||||
from openai_codex import (
|
||||
ApprovalMode,
|
||||
AsyncCodex,
|
||||
AsyncThread,
|
||||
AsyncTurnHandle,
|
||||
Codex,
|
||||
CodexConfig,
|
||||
ExternalMessage,
|
||||
Sandbox,
|
||||
Thread,
|
||||
TurnHandle,
|
||||
TurnResult,
|
||||
)
|
||||
from openai_codex._initialize_metadata import validate_initialize_metadata
|
||||
from openai_codex.types import InitializeResponse
|
||||
|
||||
try:
|
||||
import tomllib
|
||||
except ModuleNotFoundError:
|
||||
import tomli as tomllib
|
||||
|
||||
EXPECTED_ROOT_EXPORTS = [
|
||||
"__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",
|
||||
]
|
||||
|
||||
EXPECTED_TYPES_EXPORTS = [
|
||||
"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",
|
||||
]
|
||||
|
||||
|
||||
def _keyword_only_names(fn: object) -> list[str]:
|
||||
"""Return only user-facing keyword-only parameter names for a public method."""
|
||||
signature = inspect.signature(fn)
|
||||
return [
|
||||
param.name
|
||||
for param in signature.parameters.values()
|
||||
if param.kind == inspect.Parameter.KEYWORD_ONLY
|
||||
]
|
||||
|
||||
|
||||
def _keyword_default(fn: object, name: str) -> object:
|
||||
"""Return the default value for one keyword parameter on a public method."""
|
||||
return inspect.signature(fn).parameters[name].default
|
||||
|
||||
|
||||
def _assert_no_any_annotations(fn: object) -> None:
|
||||
"""Reject loose annotations on public wrapper methods."""
|
||||
signature = inspect.signature(fn)
|
||||
for param in signature.parameters.values():
|
||||
if param.annotation is Any:
|
||||
raise AssertionError(f"{fn} has public parameter typed as Any: {param.name}")
|
||||
if signature.return_annotation is Any:
|
||||
raise AssertionError(f"{fn} has public return annotation typed as Any")
|
||||
|
||||
|
||||
def test_root_exports_codex_config() -> None:
|
||||
"""The root package should expose the process configuration object."""
|
||||
assert CodexConfig.__name__ == "CodexConfig"
|
||||
|
||||
|
||||
def test_root_exports_turn_result() -> None:
|
||||
"""The root package should expose the collected turn result wrapper."""
|
||||
assert {
|
||||
"name": TurnResult.__name__,
|
||||
"fields": list(TurnResult.__dataclass_fields__),
|
||||
} == {
|
||||
"name": "TurnResult",
|
||||
"fields": [
|
||||
"id",
|
||||
"status",
|
||||
"error",
|
||||
"started_at",
|
||||
"completed_at",
|
||||
"duration_ms",
|
||||
"final_response",
|
||||
"items",
|
||||
"usage",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_turn_run_methods_return_turn_result() -> None:
|
||||
"""Both convenience and handle-based run APIs return the same result shape."""
|
||||
funcs = [
|
||||
Thread.run,
|
||||
TurnHandle.run,
|
||||
AsyncThread.run,
|
||||
AsyncTurnHandle.run,
|
||||
]
|
||||
|
||||
assert {fn: inspect.signature(fn).return_annotation for fn in funcs} == dict.fromkeys(
|
||||
funcs, "TurnResult"
|
||||
)
|
||||
|
||||
|
||||
def test_turn_input_methods_accept_string_shortcut() -> None:
|
||||
"""Every public turn-input method should accept strings and typed inputs."""
|
||||
funcs = [
|
||||
Thread.run,
|
||||
Thread.turn,
|
||||
AsyncThread.run,
|
||||
AsyncThread.turn,
|
||||
]
|
||||
|
||||
assert {fn: inspect.signature(fn).parameters["input"].annotation for fn in funcs} == (
|
||||
dict.fromkeys(funcs, "RunInput")
|
||||
)
|
||||
assert {
|
||||
fn: inspect.signature(fn).parameters["input"].annotation
|
||||
for fn in (TurnHandle.steer, AsyncTurnHandle.steer)
|
||||
} == dict.fromkeys((TurnHandle.steer, AsyncTurnHandle.steer), "Input | str")
|
||||
|
||||
|
||||
def test_root_exports_approval_mode() -> None:
|
||||
"""The root package should expose the high-level approval mode enum."""
|
||||
assert [(mode.name, mode.value) for mode in ApprovalMode] == [
|
||||
("deny_all", "deny_all"),
|
||||
("auto_review", "auto_review"),
|
||||
]
|
||||
|
||||
|
||||
def test_root_exports_sandbox_presets() -> None:
|
||||
"""The friendly sandbox API should expose only obvious named presets."""
|
||||
assert [(sandbox.name, sandbox.value) for sandbox in Sandbox] == [
|
||||
("read_only", "read-only"),
|
||||
("workspace_write", "workspace-write"),
|
||||
("full_access", "full-access"),
|
||||
]
|
||||
|
||||
|
||||
def test_package_and_default_client_versions_follow_project_version() -> None:
|
||||
"""The importable package version should stay aligned with pyproject metadata."""
|
||||
pyproject_path = Path(__file__).resolve().parents[1] / "pyproject.toml"
|
||||
pyproject = tomllib.loads(pyproject_path.read_text())
|
||||
|
||||
assert openai_codex.__version__ == pyproject["project"]["version"]
|
||||
assert CodexConfig().client_version == openai_codex.__version__
|
||||
|
||||
|
||||
def test_curated_public_api_has_builtin_help_documentation() -> None:
|
||||
"""The package's normal ``help()`` surface should explain common first-use APIs."""
|
||||
documented = {
|
||||
"module": openai_codex,
|
||||
"Codex": Codex,
|
||||
"AsyncCodex": AsyncCodex,
|
||||
"CodexConfig": CodexConfig,
|
||||
"Thread": Thread,
|
||||
"AsyncThread": AsyncThread,
|
||||
"TurnHandle": TurnHandle,
|
||||
"AsyncTurnHandle": AsyncTurnHandle,
|
||||
"TurnResult": TurnResult,
|
||||
"ExternalMessage": ExternalMessage,
|
||||
"Sandbox": Sandbox,
|
||||
"thread_start": Codex.thread_start,
|
||||
"thread_resume": Codex.thread_resume,
|
||||
"thread_run": Thread.run,
|
||||
"thread_turn": Thread.turn,
|
||||
}
|
||||
|
||||
assert {name: inspect.getdoc(value) is not None for name, value in documented.items()} == (
|
||||
dict.fromkeys(documented, True)
|
||||
)
|
||||
|
||||
|
||||
def test_package_includes_py_typed_marker() -> None:
|
||||
"""The wheel should advertise that inline type information is available."""
|
||||
marker = resources.files("openai_codex").joinpath("py.typed")
|
||||
assert marker.is_file()
|
||||
|
||||
|
||||
def test_package_root_exports_only_public_api() -> None:
|
||||
"""The package root should expose the supported SDK surface, not internals."""
|
||||
assert openai_codex.__all__ == EXPECTED_ROOT_EXPORTS
|
||||
assert {name: hasattr(openai_codex, name) for name in EXPECTED_ROOT_EXPORTS} == dict.fromkeys(
|
||||
EXPECTED_ROOT_EXPORTS, True
|
||||
)
|
||||
assert {
|
||||
"CodexClient": hasattr(openai_codex, "CodexClient"),
|
||||
"AsyncCodexClient": hasattr(openai_codex, "AsyncCodexClient"),
|
||||
"InitializeResponse": hasattr(openai_codex, "InitializeResponse"),
|
||||
"ThreadStartParams": hasattr(openai_codex, "ThreadStartParams"),
|
||||
"TurnStartParams": hasattr(openai_codex, "TurnStartParams"),
|
||||
"TurnCompletedNotification": hasattr(openai_codex, "TurnCompletedNotification"),
|
||||
"TurnStatus": hasattr(openai_codex, "TurnStatus"),
|
||||
} == {
|
||||
"CodexClient": False,
|
||||
"AsyncCodexClient": False,
|
||||
"InitializeResponse": False,
|
||||
"ThreadStartParams": False,
|
||||
"TurnStartParams": False,
|
||||
"TurnCompletedNotification": False,
|
||||
"TurnStatus": False,
|
||||
}
|
||||
|
||||
|
||||
def test_package_star_import_matches_public_api() -> None:
|
||||
"""Star imports should follow the same explicit public API list."""
|
||||
namespace: dict[str, object] = {}
|
||||
exec("from openai_codex import *", namespace)
|
||||
|
||||
exported = set(namespace) - {"__builtins__"}
|
||||
assert exported == set(EXPECTED_ROOT_EXPORTS)
|
||||
|
||||
|
||||
def test_types_module_exports_curated_public_types() -> None:
|
||||
"""The public type module should expose Codex protocol models."""
|
||||
assert public_types.__all__ == EXPECTED_TYPES_EXPORTS
|
||||
assert {name: hasattr(public_types, name) for name in EXPECTED_TYPES_EXPORTS} == dict.fromkeys(
|
||||
EXPECTED_TYPES_EXPORTS, True
|
||||
)
|
||||
|
||||
|
||||
def test_types_star_import_matches_public_types() -> None:
|
||||
"""Star imports from the type module should match its explicit export list."""
|
||||
namespace: dict[str, object] = {}
|
||||
exec("from openai_codex.types import *", namespace)
|
||||
|
||||
exported = set(namespace) - {"__builtins__"}
|
||||
assert exported == set(EXPECTED_TYPES_EXPORTS)
|
||||
|
||||
|
||||
def test_examples_use_public_import_surfaces() -> None:
|
||||
"""Examples should teach users the public root and type-module imports only."""
|
||||
examples_root = Path(__file__).resolve().parents[1] / "examples"
|
||||
private_import_markers = [
|
||||
"openai_codex.api",
|
||||
"openai_codex.client",
|
||||
"openai_codex.generated",
|
||||
"openai_codex.models",
|
||||
"openai_codex.retry",
|
||||
]
|
||||
|
||||
offenders = {
|
||||
str(path.relative_to(examples_root)): marker
|
||||
for path in examples_root.rglob("*.py")
|
||||
for marker in private_import_markers
|
||||
if marker in path.read_text()
|
||||
}
|
||||
|
||||
assert offenders == {}
|
||||
|
||||
|
||||
def test_generated_public_signatures_are_snake_case_and_typed() -> None:
|
||||
"""Generated convenience methods should expose typed Pythonic keyword names."""
|
||||
expected = {
|
||||
Codex.thread_start: [
|
||||
"approval_mode",
|
||||
"base_instructions",
|
||||
"config",
|
||||
"cwd",
|
||||
"developer_instructions",
|
||||
"ephemeral",
|
||||
"model",
|
||||
"model_provider",
|
||||
"personality",
|
||||
"sandbox",
|
||||
"service_name",
|
||||
"service_tier",
|
||||
"session_start_source",
|
||||
"thread_source",
|
||||
],
|
||||
Codex.thread_list: [
|
||||
"archived",
|
||||
"cursor",
|
||||
"cwd",
|
||||
"limit",
|
||||
"model_providers",
|
||||
"search_term",
|
||||
"section_id",
|
||||
"sort_direction",
|
||||
"sort_key",
|
||||
"source_kinds",
|
||||
"use_state_db_only",
|
||||
],
|
||||
Codex.thread_resume: [
|
||||
"approval_mode",
|
||||
"base_instructions",
|
||||
"config",
|
||||
"cwd",
|
||||
"developer_instructions",
|
||||
"include_turns",
|
||||
"model",
|
||||
"model_provider",
|
||||
"personality",
|
||||
"sandbox",
|
||||
"service_tier",
|
||||
],
|
||||
Codex.thread_fork: [
|
||||
"approval_mode",
|
||||
"base_instructions",
|
||||
"config",
|
||||
"cwd",
|
||||
"developer_instructions",
|
||||
"ephemeral",
|
||||
"include_turns",
|
||||
"model",
|
||||
"model_provider",
|
||||
"sandbox",
|
||||
"service_tier",
|
||||
"thread_source",
|
||||
],
|
||||
Thread.turn: [
|
||||
"approval_mode",
|
||||
"cwd",
|
||||
"effort",
|
||||
"model",
|
||||
"output_schema",
|
||||
"personality",
|
||||
"sandbox",
|
||||
"service_tier",
|
||||
"source",
|
||||
"summary",
|
||||
"turn_service_tier",
|
||||
],
|
||||
Thread.run: [
|
||||
"approval_mode",
|
||||
"cwd",
|
||||
"effort",
|
||||
"model",
|
||||
"output_schema",
|
||||
"personality",
|
||||
"sandbox",
|
||||
"service_tier",
|
||||
"source",
|
||||
"summary",
|
||||
"turn_service_tier",
|
||||
],
|
||||
AsyncCodex.thread_start: [
|
||||
"approval_mode",
|
||||
"base_instructions",
|
||||
"config",
|
||||
"cwd",
|
||||
"developer_instructions",
|
||||
"ephemeral",
|
||||
"model",
|
||||
"model_provider",
|
||||
"personality",
|
||||
"sandbox",
|
||||
"service_name",
|
||||
"service_tier",
|
||||
"session_start_source",
|
||||
"thread_source",
|
||||
],
|
||||
AsyncCodex.thread_list: [
|
||||
"archived",
|
||||
"cursor",
|
||||
"cwd",
|
||||
"limit",
|
||||
"model_providers",
|
||||
"search_term",
|
||||
"section_id",
|
||||
"sort_direction",
|
||||
"sort_key",
|
||||
"source_kinds",
|
||||
"use_state_db_only",
|
||||
],
|
||||
AsyncCodex.thread_resume: [
|
||||
"approval_mode",
|
||||
"base_instructions",
|
||||
"config",
|
||||
"cwd",
|
||||
"developer_instructions",
|
||||
"include_turns",
|
||||
"model",
|
||||
"model_provider",
|
||||
"personality",
|
||||
"sandbox",
|
||||
"service_tier",
|
||||
],
|
||||
AsyncCodex.thread_fork: [
|
||||
"approval_mode",
|
||||
"base_instructions",
|
||||
"config",
|
||||
"cwd",
|
||||
"developer_instructions",
|
||||
"ephemeral",
|
||||
"include_turns",
|
||||
"model",
|
||||
"model_provider",
|
||||
"sandbox",
|
||||
"service_tier",
|
||||
"thread_source",
|
||||
],
|
||||
AsyncThread.turn: [
|
||||
"approval_mode",
|
||||
"cwd",
|
||||
"effort",
|
||||
"model",
|
||||
"output_schema",
|
||||
"personality",
|
||||
"sandbox",
|
||||
"service_tier",
|
||||
"source",
|
||||
"summary",
|
||||
"turn_service_tier",
|
||||
],
|
||||
AsyncThread.run: [
|
||||
"approval_mode",
|
||||
"cwd",
|
||||
"effort",
|
||||
"model",
|
||||
"output_schema",
|
||||
"personality",
|
||||
"sandbox",
|
||||
"service_tier",
|
||||
"source",
|
||||
"summary",
|
||||
"turn_service_tier",
|
||||
],
|
||||
}
|
||||
|
||||
for fn, expected_kwargs in expected.items():
|
||||
actual = _keyword_only_names(fn)
|
||||
assert actual == expected_kwargs, f"unexpected kwargs for {fn}: {actual}"
|
||||
assert all(name == name.lower() for name in actual), (
|
||||
f"non snake_case kwargs in {fn}: {actual}"
|
||||
)
|
||||
_assert_no_any_annotations(fn)
|
||||
|
||||
|
||||
def test_new_thread_methods_default_to_auto_review() -> None:
|
||||
"""New threads should start with auto-review unless callers opt out."""
|
||||
funcs = [
|
||||
Codex.thread_start,
|
||||
AsyncCodex.thread_start,
|
||||
]
|
||||
|
||||
assert {fn: _keyword_default(fn, "approval_mode") for fn in funcs} == dict.fromkeys(
|
||||
funcs, ApprovalMode.auto_review
|
||||
)
|
||||
|
||||
|
||||
def test_existing_thread_methods_default_to_preserving_approval_settings() -> None:
|
||||
"""Existing thread operations should not serialize approval overrides by default."""
|
||||
funcs = [
|
||||
Codex.thread_resume,
|
||||
Codex.thread_fork,
|
||||
Thread.turn,
|
||||
Thread.run,
|
||||
AsyncCodex.thread_resume,
|
||||
AsyncCodex.thread_fork,
|
||||
AsyncThread.turn,
|
||||
AsyncThread.run,
|
||||
]
|
||||
|
||||
assert {fn: _keyword_default(fn, "approval_mode") for fn in funcs} == dict.fromkeys(funcs)
|
||||
|
||||
|
||||
def test_lifecycle_methods_are_codex_scoped() -> None:
|
||||
"""Lifecycle operations should hang off the client rather than thread objects."""
|
||||
assert hasattr(Codex, "thread_resume")
|
||||
assert hasattr(Codex, "thread_fork")
|
||||
assert hasattr(Codex, "thread_archive")
|
||||
assert hasattr(Codex, "thread_unarchive")
|
||||
assert hasattr(AsyncCodex, "thread_resume")
|
||||
assert hasattr(AsyncCodex, "thread_fork")
|
||||
assert hasattr(AsyncCodex, "thread_archive")
|
||||
assert hasattr(AsyncCodex, "thread_unarchive")
|
||||
assert not hasattr(Codex, "thread")
|
||||
assert not hasattr(AsyncCodex, "thread")
|
||||
|
||||
assert not hasattr(Thread, "resume")
|
||||
assert not hasattr(Thread, "fork")
|
||||
assert not hasattr(Thread, "archive")
|
||||
assert not hasattr(Thread, "unarchive")
|
||||
assert not hasattr(AsyncThread, "resume")
|
||||
assert not hasattr(AsyncThread, "fork")
|
||||
assert not hasattr(AsyncThread, "archive")
|
||||
assert not hasattr(AsyncThread, "unarchive")
|
||||
|
||||
for fn in (
|
||||
Codex.thread_archive,
|
||||
Codex.thread_unarchive,
|
||||
AsyncCodex.thread_archive,
|
||||
AsyncCodex.thread_unarchive,
|
||||
):
|
||||
_assert_no_any_annotations(fn)
|
||||
|
||||
|
||||
def test_initialize_metadata_parses_user_agent_shape() -> None:
|
||||
"""Initialize metadata should accept the legacy user-agent-only payload shape."""
|
||||
payload = InitializeResponse.model_validate({"userAgent": "codex-cli/1.2.3"})
|
||||
parsed = validate_initialize_metadata(payload)
|
||||
assert parsed is payload
|
||||
assert parsed.userAgent == "codex-cli/1.2.3"
|
||||
assert parsed.serverInfo is not None
|
||||
assert parsed.serverInfo.name == "codex-cli"
|
||||
assert parsed.serverInfo.version == "1.2.3"
|
||||
|
||||
|
||||
def test_initialize_metadata_requires_non_empty_information() -> None:
|
||||
"""Initialize metadata should fail when the runtime gives no identity signal."""
|
||||
try:
|
||||
validate_initialize_metadata(InitializeResponse.model_validate({}))
|
||||
except RuntimeError as exc:
|
||||
assert "missing required metadata" in str(exc)
|
||||
else:
|
||||
raise AssertionError("expected RuntimeError when initialize metadata is missing")
|
||||
569
sdk/python/tests/test_real_app_server_integration.py
Normal file
569
sdk/python/tests/test_real_app_server_integration.py
Normal file
@@ -0,0 +1,569 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EXAMPLES_DIR = ROOT / "examples"
|
||||
NOTEBOOK_PATH = ROOT / "notebooks" / "sdk_walkthrough.ipynb"
|
||||
|
||||
root_str = str(ROOT)
|
||||
if root_str not in sys.path:
|
||||
sys.path.insert(0, root_str)
|
||||
|
||||
from _runtime_setup import ensure_runtime_package_installed, pinned_runtime_version
|
||||
|
||||
RUN_REAL_CODEX_TESTS = os.environ.get("RUN_REAL_CODEX_TESTS") == "1"
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not RUN_REAL_CODEX_TESTS,
|
||||
reason="set RUN_REAL_CODEX_TESTS=1 to run real Codex integration coverage",
|
||||
)
|
||||
|
||||
# 11_cli_mini_app is interactive; we still run it by feeding one prompt, then '/exit'.
|
||||
EXAMPLE_CASES: list[tuple[str, str]] = [
|
||||
("01_quickstart_constructor", "sync.py"),
|
||||
("01_quickstart_constructor", "async.py"),
|
||||
("02_turn_run", "sync.py"),
|
||||
("02_turn_run", "async.py"),
|
||||
("03_turn_stream_events", "sync.py"),
|
||||
("03_turn_stream_events", "async.py"),
|
||||
("04_models_and_metadata", "sync.py"),
|
||||
("04_models_and_metadata", "async.py"),
|
||||
("05_existing_thread", "sync.py"),
|
||||
("05_existing_thread", "async.py"),
|
||||
("06_thread_lifecycle_and_controls", "sync.py"),
|
||||
("06_thread_lifecycle_and_controls", "async.py"),
|
||||
("07_image_and_text", "sync.py"),
|
||||
("07_image_and_text", "async.py"),
|
||||
("08_local_image_and_text", "sync.py"),
|
||||
("08_local_image_and_text", "async.py"),
|
||||
("09_async_parity", "sync.py"),
|
||||
# 09_async_parity async path is represented by 01 async + dedicated async-based cases above.
|
||||
("10_error_handling_and_retry", "sync.py"),
|
||||
("10_error_handling_and_retry", "async.py"),
|
||||
("11_cli_mini_app", "sync.py"),
|
||||
("11_cli_mini_app", "async.py"),
|
||||
("12_turn_params_kitchen_sink", "sync.py"),
|
||||
("12_turn_params_kitchen_sink", "async.py"),
|
||||
("13_model_select_and_turn_params", "sync.py"),
|
||||
("13_model_select_and_turn_params", "async.py"),
|
||||
("14_turn_controls", "sync.py"),
|
||||
("14_turn_controls", "async.py"),
|
||||
]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PreparedRuntimeEnv:
|
||||
python: str
|
||||
env: dict[str, str]
|
||||
runtime_version: str
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def runtime_env(tmp_path_factory: pytest.TempPathFactory) -> PreparedRuntimeEnv:
|
||||
runtime_version = pinned_runtime_version()
|
||||
temp_root = tmp_path_factory.mktemp("python-runtime-env")
|
||||
isolated_site = temp_root / "site-packages"
|
||||
python = sys.executable
|
||||
|
||||
_run_command(
|
||||
[
|
||||
python,
|
||||
"-m",
|
||||
"pip",
|
||||
"install",
|
||||
"--target",
|
||||
str(isolated_site),
|
||||
"pydantic>=2.12",
|
||||
],
|
||||
cwd=ROOT,
|
||||
env=os.environ.copy(),
|
||||
timeout_s=240,
|
||||
)
|
||||
ensure_runtime_package_installed(
|
||||
python,
|
||||
ROOT,
|
||||
install_target=isolated_site,
|
||||
)
|
||||
|
||||
env = os.environ.copy()
|
||||
env["PYTHONPATH"] = os.pathsep.join([str(isolated_site), str(ROOT / "src")])
|
||||
env["CODEX_PYTHON_SDK_DIR"] = str(ROOT)
|
||||
return PreparedRuntimeEnv(python=python, env=env, runtime_version=runtime_version)
|
||||
|
||||
|
||||
def _run_command(
|
||||
args: list[str],
|
||||
*,
|
||||
cwd: Path,
|
||||
env: dict[str, str],
|
||||
timeout_s: int,
|
||||
stdin: str | None = None,
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run(
|
||||
args,
|
||||
cwd=str(cwd),
|
||||
env=env,
|
||||
input=stdin,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=timeout_s,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
def _run_python(
|
||||
runtime_env: PreparedRuntimeEnv,
|
||||
source: str,
|
||||
*,
|
||||
cwd: Path | None = None,
|
||||
timeout_s: int = 180,
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
return _run_command(
|
||||
[str(runtime_env.python), "-c", source],
|
||||
cwd=cwd or ROOT,
|
||||
env=runtime_env.env,
|
||||
timeout_s=timeout_s,
|
||||
)
|
||||
|
||||
|
||||
def _runtime_schema_hint(
|
||||
runtime_env: PreparedRuntimeEnv,
|
||||
*,
|
||||
stdout: str,
|
||||
stderr: str,
|
||||
) -> str:
|
||||
combined = f"{stdout}\n{stderr}"
|
||||
if "ThreadStartResponse" in combined and "approvalsReviewer" in combined:
|
||||
return (
|
||||
"\nSchema hint:\n"
|
||||
f"Pinned runtime {runtime_env.runtime_version} returned a thread/start payload "
|
||||
"that is older than the current SDK schema and is missing "
|
||||
"`approvalsReviewer`. Bump `sdk/python/_runtime_setup.py` to a matching "
|
||||
"released runtime version.\n"
|
||||
)
|
||||
return ""
|
||||
|
||||
|
||||
def _run_json_python(
|
||||
runtime_env: PreparedRuntimeEnv,
|
||||
source: str,
|
||||
*,
|
||||
cwd: Path | None = None,
|
||||
timeout_s: int = 180,
|
||||
) -> dict[str, object]:
|
||||
result = _run_python(runtime_env, source, cwd=cwd, timeout_s=timeout_s)
|
||||
assert result.returncode == 0, (
|
||||
"Python snippet failed.\n"
|
||||
f"STDOUT:\n{result.stdout}\n"
|
||||
f"STDERR:\n{result.stderr}"
|
||||
f"{_runtime_schema_hint(runtime_env, stdout=result.stdout, stderr=result.stderr)}"
|
||||
)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def _run_example(
|
||||
runtime_env: PreparedRuntimeEnv,
|
||||
folder: str,
|
||||
script: str,
|
||||
*,
|
||||
timeout_s: int = 180,
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
path = EXAMPLES_DIR / folder / script
|
||||
assert path.exists(), f"Missing example script: {path}"
|
||||
|
||||
stdin = (
|
||||
"Give 3 short bullets on SIMD.\nNow rewrite that as 1 short sentence.\n/exit\n"
|
||||
if folder == "11_cli_mini_app"
|
||||
else None
|
||||
)
|
||||
return _run_command(
|
||||
[str(runtime_env.python), str(path)],
|
||||
cwd=ROOT,
|
||||
env=runtime_env.env,
|
||||
timeout_s=timeout_s,
|
||||
stdin=stdin,
|
||||
)
|
||||
|
||||
|
||||
def _notebook_cell_source(cell_index: int) -> str:
|
||||
notebook = json.loads(NOTEBOOK_PATH.read_text())
|
||||
return "".join(notebook["cells"][cell_index]["source"])
|
||||
|
||||
|
||||
def test_real_initialize_and_model_list(runtime_env: PreparedRuntimeEnv) -> None:
|
||||
data = _run_json_python(
|
||||
runtime_env,
|
||||
textwrap.dedent(
|
||||
"""
|
||||
import json
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex() as codex:
|
||||
models = codex.models(include_hidden=True)
|
||||
server = codex.metadata.serverInfo
|
||||
print(json.dumps({
|
||||
"user_agent": codex.metadata.userAgent,
|
||||
"server_name": None if server is None else server.name,
|
||||
"server_version": None if server is None else server.version,
|
||||
"model_count": len(models.data),
|
||||
}))
|
||||
"""
|
||||
),
|
||||
)
|
||||
|
||||
assert isinstance(data["user_agent"], str) and data["user_agent"].strip()
|
||||
if data["server_name"] is not None:
|
||||
assert isinstance(data["server_name"], str) and data["server_name"].strip()
|
||||
if data["server_version"] is not None:
|
||||
assert isinstance(data["server_version"], str) and data["server_version"].strip()
|
||||
assert isinstance(data["model_count"], int)
|
||||
|
||||
|
||||
def test_real_thread_and_turn_start_smoke(runtime_env: PreparedRuntimeEnv) -> None:
|
||||
data = _run_json_python(
|
||||
runtime_env,
|
||||
textwrap.dedent(
|
||||
"""
|
||||
import json
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex() as codex:
|
||||
thread = codex.thread_start(
|
||||
model="gpt-5.4",
|
||||
config={"model_reasoning_effort": "high"},
|
||||
)
|
||||
result = thread.turn("hello").run()
|
||||
print(json.dumps({
|
||||
"thread_id": thread.id,
|
||||
"turn_id": result.id,
|
||||
"status": result.status.value,
|
||||
"items_count": len(result.items),
|
||||
"final_response_is_text": isinstance(result.final_response, str) and bool(result.final_response.strip()),
|
||||
}))
|
||||
"""
|
||||
),
|
||||
)
|
||||
|
||||
assert isinstance(data["thread_id"], str) and data["thread_id"].strip()
|
||||
assert isinstance(data["turn_id"], str) and data["turn_id"].strip()
|
||||
assert data["status"] == "completed"
|
||||
assert data["items_count"] > 0
|
||||
assert data["final_response_is_text"] is True
|
||||
|
||||
|
||||
def test_real_thread_run_convenience_smoke(runtime_env: PreparedRuntimeEnv) -> None:
|
||||
data = _run_json_python(
|
||||
runtime_env,
|
||||
textwrap.dedent(
|
||||
"""
|
||||
import json
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex() as codex:
|
||||
thread = codex.thread_start(
|
||||
model="gpt-5.4",
|
||||
config={"model_reasoning_effort": "high"},
|
||||
)
|
||||
result = thread.run("say ok")
|
||||
print(json.dumps({
|
||||
"thread_id": thread.id,
|
||||
"final_response": result.final_response,
|
||||
"items_count": len(result.items),
|
||||
"has_usage": result.usage is not None,
|
||||
}))
|
||||
"""
|
||||
),
|
||||
)
|
||||
|
||||
assert isinstance(data["thread_id"], str) and data["thread_id"].strip()
|
||||
assert isinstance(data["final_response"], str) and data["final_response"].strip()
|
||||
assert isinstance(data["items_count"], int)
|
||||
assert isinstance(data["has_usage"], bool)
|
||||
|
||||
|
||||
def test_real_quickstart_style_flow_smoke(runtime_env: PreparedRuntimeEnv) -> None:
|
||||
data = _run_json_python(
|
||||
runtime_env,
|
||||
textwrap.dedent(
|
||||
"""
|
||||
import json
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex() as codex:
|
||||
thread = codex.thread_start()
|
||||
result = thread.run("Say hello in one sentence.")
|
||||
print(json.dumps({
|
||||
"thread_id": thread.id,
|
||||
"final_response": result.final_response,
|
||||
"items_count": len(result.items),
|
||||
}))
|
||||
"""
|
||||
),
|
||||
)
|
||||
|
||||
assert {
|
||||
"thread_id_is_text": isinstance(data["thread_id"], str) and bool(data["thread_id"].strip()),
|
||||
"final_response_is_text": isinstance(data["final_response"], str)
|
||||
and bool(data["final_response"].strip()),
|
||||
"items_count_is_int": isinstance(data["items_count"], int),
|
||||
} == {
|
||||
"thread_id_is_text": True,
|
||||
"final_response_is_text": True,
|
||||
"items_count_is_int": True,
|
||||
}
|
||||
|
||||
|
||||
def test_real_async_thread_turn_usage_and_ids_smoke(
|
||||
runtime_env: PreparedRuntimeEnv,
|
||||
) -> None:
|
||||
data = _run_json_python(
|
||||
runtime_env,
|
||||
textwrap.dedent(
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
from openai_codex import AsyncCodex
|
||||
|
||||
async def main():
|
||||
async with AsyncCodex() as codex:
|
||||
thread = await codex.thread_start(
|
||||
model="gpt-5.4",
|
||||
config={"model_reasoning_effort": "high"},
|
||||
)
|
||||
result = await (await thread.turn("say ok")).run()
|
||||
print(json.dumps({
|
||||
"thread_id": thread.id,
|
||||
"turn_id": result.id,
|
||||
"status": result.status.value,
|
||||
"items_count": len(result.items),
|
||||
"final_response_is_text": isinstance(result.final_response, str) and bool(result.final_response.strip()),
|
||||
}))
|
||||
|
||||
asyncio.run(main())
|
||||
"""
|
||||
),
|
||||
)
|
||||
|
||||
assert isinstance(data["thread_id"], str) and data["thread_id"].strip()
|
||||
assert isinstance(data["turn_id"], str) and data["turn_id"].strip()
|
||||
assert data["status"] == "completed"
|
||||
assert data["items_count"] > 0
|
||||
assert data["final_response_is_text"] is True
|
||||
|
||||
|
||||
def test_real_async_thread_run_convenience_smoke(
|
||||
runtime_env: PreparedRuntimeEnv,
|
||||
) -> None:
|
||||
data = _run_json_python(
|
||||
runtime_env,
|
||||
textwrap.dedent(
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
from openai_codex import AsyncCodex
|
||||
|
||||
async def main():
|
||||
async with AsyncCodex() as codex:
|
||||
thread = await codex.thread_start(
|
||||
model="gpt-5.4",
|
||||
config={"model_reasoning_effort": "high"},
|
||||
)
|
||||
result = await thread.run("say ok")
|
||||
print(json.dumps({
|
||||
"thread_id": thread.id,
|
||||
"final_response": result.final_response,
|
||||
"items_count": len(result.items),
|
||||
"has_usage": result.usage is not None,
|
||||
}))
|
||||
|
||||
asyncio.run(main())
|
||||
"""
|
||||
),
|
||||
)
|
||||
|
||||
assert isinstance(data["thread_id"], str) and data["thread_id"].strip()
|
||||
assert isinstance(data["final_response"], str) and data["final_response"].strip()
|
||||
assert isinstance(data["items_count"], int)
|
||||
assert isinstance(data["has_usage"], bool)
|
||||
|
||||
|
||||
def test_notebook_bootstrap_resolves_sdk_and_runtime_from_unrelated_cwd(
|
||||
runtime_env: PreparedRuntimeEnv,
|
||||
) -> None:
|
||||
cell_1_source = _notebook_cell_source(1)
|
||||
env = runtime_env.env.copy()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_cwd:
|
||||
result = _run_command(
|
||||
[str(runtime_env.python), "-c", cell_1_source],
|
||||
cwd=Path(temp_cwd),
|
||||
env=env,
|
||||
timeout_s=180,
|
||||
)
|
||||
|
||||
assert result.returncode == 0, (
|
||||
f"Notebook bootstrap failed from unrelated cwd.\n"
|
||||
f"STDOUT:\n{result.stdout}\n"
|
||||
f"STDERR:\n{result.stderr}"
|
||||
)
|
||||
assert "SDK source:" in result.stdout
|
||||
assert f"Runtime package: {runtime_env.runtime_version}" in result.stdout
|
||||
|
||||
|
||||
def test_notebook_sync_cell_smoke(runtime_env: PreparedRuntimeEnv) -> None:
|
||||
source = "\n\n".join(
|
||||
[
|
||||
_notebook_cell_source(1),
|
||||
_notebook_cell_source(2),
|
||||
_notebook_cell_source(4),
|
||||
]
|
||||
)
|
||||
result = _run_python(runtime_env, source, timeout_s=240)
|
||||
assert result.returncode == 0, (
|
||||
f"Notebook sync smoke failed.\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}"
|
||||
)
|
||||
assert "status:" in result.stdout
|
||||
assert "server:" in result.stdout
|
||||
|
||||
|
||||
def test_notebook_advanced_cell_smoke(runtime_env: PreparedRuntimeEnv) -> None:
|
||||
source = "\n\n".join(
|
||||
[
|
||||
_notebook_cell_source(1),
|
||||
_notebook_cell_source(2),
|
||||
_notebook_cell_source(8),
|
||||
]
|
||||
)
|
||||
result = _run_python(runtime_env, source, timeout_s=360)
|
||||
assert result.returncode == 0, (
|
||||
f"Notebook advanced smoke failed.\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}"
|
||||
)
|
||||
assert "selected.model:" in result.stdout
|
||||
assert "agent.message.params:" in result.stdout
|
||||
assert "items.params:" in result.stdout
|
||||
|
||||
|
||||
def test_real_streaming_smoke_turn_completed(runtime_env: PreparedRuntimeEnv) -> None:
|
||||
data = _run_json_python(
|
||||
runtime_env,
|
||||
textwrap.dedent(
|
||||
"""
|
||||
import json
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex() as codex:
|
||||
thread = codex.thread_start(
|
||||
model="gpt-5.4",
|
||||
config={"model_reasoning_effort": "high"},
|
||||
)
|
||||
turn = thread.turn("Reply with one short sentence.")
|
||||
saw_delta = False
|
||||
saw_completed = False
|
||||
for event in turn.stream():
|
||||
if event.method == "item/agentMessage/delta":
|
||||
saw_delta = True
|
||||
if event.method == "turn/completed":
|
||||
saw_completed = True
|
||||
print(json.dumps({
|
||||
"saw_delta": saw_delta,
|
||||
"saw_completed": saw_completed,
|
||||
}))
|
||||
"""
|
||||
),
|
||||
)
|
||||
|
||||
assert data["saw_completed"] is True
|
||||
assert isinstance(data["saw_delta"], bool)
|
||||
|
||||
|
||||
def test_real_turn_interrupt_smoke(runtime_env: PreparedRuntimeEnv) -> None:
|
||||
data = _run_json_python(
|
||||
runtime_env,
|
||||
textwrap.dedent(
|
||||
"""
|
||||
import json
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex() as codex:
|
||||
thread = codex.thread_start(
|
||||
model="gpt-5.4",
|
||||
config={"model_reasoning_effort": "high"},
|
||||
)
|
||||
turn = thread.turn("Count from 1 to 200 with commas.")
|
||||
turn.interrupt()
|
||||
follow_up = thread.turn("Say 'ok' only.").run()
|
||||
print(json.dumps({"status": follow_up.status.value}))
|
||||
"""
|
||||
),
|
||||
)
|
||||
|
||||
assert data["status"] in {"completed", "failed"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("folder", "script"), EXAMPLE_CASES)
|
||||
def test_real_examples_run_and_assert(
|
||||
runtime_env: PreparedRuntimeEnv,
|
||||
folder: str,
|
||||
script: str,
|
||||
) -> None:
|
||||
result = _run_example(runtime_env, folder, script)
|
||||
|
||||
assert result.returncode == 0, (
|
||||
f"Example failed: {folder}/{script}\n"
|
||||
f"STDOUT:\n{result.stdout}\n"
|
||||
f"STDERR:\n{result.stderr}"
|
||||
f"{_runtime_schema_hint(runtime_env, stdout=result.stdout, stderr=result.stderr)}"
|
||||
)
|
||||
|
||||
out = result.stdout
|
||||
|
||||
if folder == "01_quickstart_constructor":
|
||||
assert "Server:" in out and "Items:" in out and "Text:" in out
|
||||
assert "Server: unknown" not in out
|
||||
elif folder == "02_turn_run":
|
||||
assert "thread_id:" in out and "turn_id:" in out and "status:" in out
|
||||
assert "items.count:" in out
|
||||
elif folder == "03_turn_stream_events":
|
||||
assert "stream.completed:" in out
|
||||
assert "assistant>" in out
|
||||
elif folder == "04_models_and_metadata":
|
||||
assert "server:" in out
|
||||
assert "models.count:" in out
|
||||
assert "models:" in out
|
||||
assert "metadata:" not in out
|
||||
elif folder == "05_existing_thread":
|
||||
assert "Created thread:" in out
|
||||
elif folder == "06_thread_lifecycle_and_controls":
|
||||
assert "Lifecycle OK:" in out
|
||||
elif folder in {"07_image_and_text", "08_local_image_and_text"}:
|
||||
assert "completed" in out.lower() or "Status:" in out
|
||||
elif folder == "09_async_parity":
|
||||
assert "Thread:" in out and "Turn:" in out
|
||||
elif folder == "10_error_handling_and_retry":
|
||||
assert "Text:" in out
|
||||
elif folder == "11_cli_mini_app":
|
||||
assert "Thread:" in out
|
||||
assert out.count("assistant>") >= 2
|
||||
assert out.count("assistant.status>") >= 2
|
||||
assert out.count("usage>") >= 2
|
||||
elif folder == "12_turn_params_kitchen_sink":
|
||||
assert "Status:" in out
|
||||
assert "summary:" in out
|
||||
assert "actions:" in out
|
||||
assert "Items:" in out
|
||||
elif folder == "13_model_select_and_turn_params":
|
||||
assert (
|
||||
"selected.model:" in out and "agent.message.params:" in out and "items.params:" in out
|
||||
)
|
||||
elif folder == "14_turn_controls":
|
||||
assert "steer.result:" in out and "steer.final.status:" in out
|
||||
assert "interrupt.result:" in out and "interrupt.final.status:" in out
|
||||
345
sdk/python/tests/test_turn_subscriptions.py
Normal file
345
sdk/python/tests/test_turn_subscriptions.py
Normal file
@@ -0,0 +1,345 @@
|
||||
import asyncio
|
||||
import gc
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from itertools import chain
|
||||
|
||||
import pytest
|
||||
|
||||
from openai_codex import AsyncCodex
|
||||
from openai_codex._run import _collect_turn_result
|
||||
from openai_codex.api import AsyncThread, AsyncTurnHandle, Thread, TurnHandle
|
||||
from openai_codex.async_client import AsyncCodexClient
|
||||
from openai_codex.client import CodexClient
|
||||
from openai_codex.errors import TransportClosedError
|
||||
|
||||
|
||||
def turn_events(client, *, status="completed"):
|
||||
scope = {"threadId": "thread-1", "turnId": "turn-1"}
|
||||
usage = {
|
||||
"inputTokens": 2,
|
||||
"cachedInputTokens": 0,
|
||||
"outputTokens": 3,
|
||||
"reasoningOutputTokens": 0,
|
||||
"totalTokens": 5,
|
||||
}
|
||||
return [
|
||||
client._coerce_notification(
|
||||
"item/completed",
|
||||
{
|
||||
**scope,
|
||||
"completedAtMs": 1,
|
||||
"item": {
|
||||
"id": "message",
|
||||
"type": "agentMessage",
|
||||
"text": "done",
|
||||
"phase": "final_answer",
|
||||
},
|
||||
},
|
||||
),
|
||||
client._coerce_notification(
|
||||
"thread/tokenUsage/updated", {**scope, "tokenUsage": {"last": usage, "total": usage}}
|
||||
),
|
||||
client._coerce_notification(
|
||||
"turn/completed",
|
||||
{
|
||||
"threadId": "thread-1",
|
||||
"turn": {
|
||||
"id": "turn-1",
|
||||
"items": [],
|
||||
"status": status,
|
||||
"error": {"message": "model failed"} if status == "failed" else None,
|
||||
},
|
||||
},
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("consumed", [False, True])
|
||||
def test_late_join_starts_with_future_events(consumed):
|
||||
client = CodexClient()
|
||||
original = TurnHandle(client, "thread-1", "turn-1")
|
||||
events = turn_events(client)
|
||||
client._router.route_notification(events[0])
|
||||
stream = original.stream()
|
||||
previous = [next(stream)] if consumed else []
|
||||
joined = TurnHandle(client, "thread-1", "turn-1")
|
||||
client._router.route_notification(events[1])
|
||||
for event in events[2:]:
|
||||
client._router.route_notification(event)
|
||||
|
||||
first_result = _collect_turn_result(chain(previous, stream), turn_id="turn-1")
|
||||
joined_result = joined.run()
|
||||
assert first_result.final_response == "done"
|
||||
assert joined_result.final_response is None
|
||||
assert joined_result.usage == first_result.usage
|
||||
assert client._router._turn_states == {}
|
||||
|
||||
|
||||
def test_consumed_deltas_are_released_while_turn_is_active():
|
||||
client = CodexClient()
|
||||
subscription = client._subscribe_turn_notifications("turn-1")
|
||||
state = client._router._turn_states["turn-1"]
|
||||
for index in range(1000):
|
||||
event = client._coerce_notification(
|
||||
"item/agentMessage/delta",
|
||||
{
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-1",
|
||||
"itemId": "message",
|
||||
"delta": str(index),
|
||||
},
|
||||
)
|
||||
client._router.route_notification(event)
|
||||
assert subscription.next() == event
|
||||
assert state.events == {}
|
||||
assert not state.completed
|
||||
subscription.close()
|
||||
|
||||
|
||||
def test_slow_subscriber_keeps_unread_deltas_until_it_consumes_them():
|
||||
client = CodexClient()
|
||||
fast = client._subscribe_turn_notifications("turn-1")
|
||||
slow = client._subscribe_turn_notifications("turn-1")
|
||||
event = client._coerce_notification(
|
||||
"item/agentMessage/delta",
|
||||
{"threadId": "thread-1", "turnId": "turn-1", "itemId": "message", "delta": "hello"},
|
||||
)
|
||||
client._router.route_notification(event)
|
||||
assert fast.next() == event
|
||||
assert slow.next() == event
|
||||
assert client._router._turn_states["turn-1"].events == {}
|
||||
fast.close()
|
||||
slow.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("async_api", [False, True])
|
||||
@pytest.mark.parametrize("low_level", [False, True])
|
||||
@pytest.mark.parametrize("completed", [False, True])
|
||||
def test_events_or_failure_before_turn_start_returns(monkeypatch, async_api, low_level, completed):
|
||||
codex = AsyncCodex()
|
||||
codex._initialized = True
|
||||
client = codex._client._sync if async_api else CodexClient()
|
||||
|
||||
def request_raw(method, params):
|
||||
assert method == "turn/start"
|
||||
for event in turn_events(client) if completed else []:
|
||||
client._router.route_notification(event)
|
||||
client._router.fail_all(TransportClosedError("transport failed"))
|
||||
return {"turn": {"id": "turn-1", "status": "inProgress", "items": []}}
|
||||
|
||||
monkeypatch.setattr(client, "_request_raw", request_raw)
|
||||
public = codex._client if async_api else client
|
||||
thread = AsyncThread(codex, "thread-1") if async_api else Thread(client, "thread-1")
|
||||
|
||||
async def value(call):
|
||||
return await call if async_api else call
|
||||
|
||||
async def scenario():
|
||||
if low_level:
|
||||
started = await value(public.turn_start("thread-1", "hello"))
|
||||
assert (
|
||||
await value(public.wait_for_turn_completed(started.turn.id))
|
||||
).turn.id == "turn-1"
|
||||
else:
|
||||
handle = await value(thread.turn("hello"))
|
||||
assert (await value(handle.run())).final_response == "done"
|
||||
|
||||
if completed:
|
||||
asyncio.run(scenario())
|
||||
else:
|
||||
with pytest.raises(TransportClosedError, match="transport failed"):
|
||||
asyncio.run(scenario())
|
||||
assert client._router._turn_states == {}
|
||||
|
||||
|
||||
def test_pending_join_starts_at_request_while_original_handle_finishes():
|
||||
client = CodexClient()
|
||||
original = TurnHandle(client, "thread-1", "turn-1")
|
||||
events = turn_events(client)
|
||||
unknown = [client._coerce_notification(name, {"turnId": "turn-1"}) for name in ("old", "live")]
|
||||
client._router.route_notification(unknown[0])
|
||||
assert original._subscription.next() is unknown[0]
|
||||
|
||||
with client._router.pending_turn("thread-1") as cursors:
|
||||
client._router.route_notification(unknown[1])
|
||||
assert original._subscription.next() is unknown[1]
|
||||
client._router.route_notification(events[0])
|
||||
client._router.route_notification(events[1])
|
||||
manual = TurnHandle(client, "thread-1", "turn-1")
|
||||
client._router.route_notification(events[2])
|
||||
result = original.run()
|
||||
assert manual.run().usage is None
|
||||
subscription = client._router.prepare_turn("turn-1", "thread-1", cursors, for_handle=True)
|
||||
joined_handle = TurnHandle(client, "thread-1", "turn-1", _subscription=subscription)
|
||||
assert joined_handle._subscription.next() is unknown[1]
|
||||
joined = joined_handle.run()
|
||||
assert result.final_response == joined.final_response == "done"
|
||||
assert joined.usage.last.total_tokens == 5
|
||||
assert client._router._turn_states == {}
|
||||
|
||||
|
||||
def test_failed_start_releases_early_completed_state():
|
||||
client = CodexClient()
|
||||
with pytest.raises(ValueError, match="request failed"):
|
||||
with client._router.pending_turn("thread-1"):
|
||||
for event in turn_events(client):
|
||||
client._router.route_notification(event)
|
||||
raise ValueError("request failed")
|
||||
assert client._router._turn_states == {}
|
||||
assert client._router._pending_turn_requests == {}
|
||||
|
||||
|
||||
def test_closing_one_stream_leaves_other_subscriber_intact():
|
||||
client = CodexClient()
|
||||
original = TurnHandle(client, "thread-1", "turn-1")
|
||||
joined = TurnHandle(client, "thread-1", "turn-1")
|
||||
events = turn_events(client)
|
||||
client._router.route_notification(events[0])
|
||||
stream = original.stream()
|
||||
next(stream)
|
||||
stream.close()
|
||||
for event in events[1:]:
|
||||
client._router.route_notification(event)
|
||||
assert joined.run().final_response == "done"
|
||||
assert client._router._turn_states == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", ["transport", "model"])
|
||||
def test_both_handles_observe_failure_and_release_state(failure):
|
||||
client = CodexClient()
|
||||
handles = [TurnHandle(client, "thread-1", "turn-1") for _ in range(2)]
|
||||
if failure == "transport":
|
||||
client._router.fail_all(TransportClosedError("transport failed"))
|
||||
else:
|
||||
for event in turn_events(client, status="failed"):
|
||||
client._router.route_notification(event)
|
||||
for handle in handles:
|
||||
with pytest.raises((TransportClosedError, RuntimeError), match=f"{failure} failed"):
|
||||
handle.run()
|
||||
assert client._router._turn_states == {}
|
||||
|
||||
|
||||
def test_abandoned_handle_releases_completed_history():
|
||||
client = CodexClient()
|
||||
handle = TurnHandle(client, "thread-1", "turn-1")
|
||||
for event in turn_events(client):
|
||||
client._router.route_notification(event)
|
||||
with client._router._lock:
|
||||
del handle
|
||||
gc.collect()
|
||||
assert client._router._turn_states == {}
|
||||
|
||||
|
||||
def test_cancelled_async_consumer_leaves_other_handle_intact():
|
||||
async def scenario():
|
||||
codex = AsyncCodex()
|
||||
codex._initialized = True
|
||||
client = codex._client._sync
|
||||
original = AsyncTurnHandle(codex, "thread-1", "turn-1")
|
||||
joined = AsyncTurnHandle(codex, "thread-1", "turn-1")
|
||||
task = asyncio.create_task(original.run())
|
||||
await asyncio.sleep(0) # Let the stream enter its wait before cancelling it.
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
for event in turn_events(client):
|
||||
client._router.route_notification(event)
|
||||
assert (await asyncio.wait_for(joined.run(), timeout=2)).final_response == "done"
|
||||
assert client._router._turn_states == {}
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_cancelled_turn_start_releases_result_after_response(monkeypatch):
|
||||
async def scenario():
|
||||
client = AsyncCodexClient()
|
||||
entered = threading.Event()
|
||||
respond = threading.Event()
|
||||
released = threading.Event()
|
||||
subscribe = client._sync._router.prepare_turn
|
||||
|
||||
def request_raw(method, params):
|
||||
entered.set()
|
||||
assert respond.wait(timeout=2)
|
||||
for event in turn_events(client._sync):
|
||||
client._sync._router.route_notification(event)
|
||||
return {"turn": {"id": "turn-1", "items": [], "status": "completed"}}
|
||||
|
||||
def observe_release(*args, **kwargs):
|
||||
subscription = subscribe(*args, **kwargs)
|
||||
close = subscription.close
|
||||
|
||||
def close_and_signal():
|
||||
close()
|
||||
released.set()
|
||||
|
||||
subscription.close = close_and_signal
|
||||
return subscription
|
||||
|
||||
monkeypatch.setattr(client._sync, "_request_raw", request_raw)
|
||||
monkeypatch.setattr(client._sync._router, "prepare_turn", observe_release)
|
||||
task = asyncio.create_task(client.turn_start("thread-1", "hello"))
|
||||
try:
|
||||
assert await asyncio.to_thread(entered.wait, 2)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
finally:
|
||||
respond.set()
|
||||
assert await asyncio.to_thread(released.wait, 2)
|
||||
assert client._sync._router._turn_states == {}
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_cancelled_queued_start_does_not_send_a_request(monkeypatch):
|
||||
with ThreadPoolExecutor(max_workers=1) as executor:
|
||||
monkeypatch.setattr("openai_codex.async_client._TURN_START_EXECUTOR", executor)
|
||||
release_worker = threading.Event()
|
||||
worker_started = threading.Event()
|
||||
request_sent = threading.Event()
|
||||
|
||||
def occupy_worker():
|
||||
worker_started.set()
|
||||
assert release_worker.wait(timeout=5)
|
||||
|
||||
occupied = executor.submit(occupy_worker)
|
||||
assert worker_started.wait(timeout=5)
|
||||
client = AsyncCodexClient()
|
||||
monkeypatch.setattr(client._sync, "_start_turn", lambda *args, **kwargs: request_sent.set())
|
||||
|
||||
async def scenario():
|
||||
task = asyncio.create_task(client.turn_start("thread-1", "hello"))
|
||||
await asyncio.sleep(0)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
|
||||
try:
|
||||
asyncio.run(scenario())
|
||||
finally:
|
||||
release_worker.set()
|
||||
occupied.result(timeout=5)
|
||||
executor.submit(lambda: None).result(timeout=5)
|
||||
assert not request_sent.is_set()
|
||||
|
||||
|
||||
def test_low_level_start_keeps_implicit_registration_and_explicit_unregister(monkeypatch):
|
||||
client = CodexClient()
|
||||
|
||||
def request_raw(method, params):
|
||||
for event in turn_events(client):
|
||||
client._router.route_notification(event)
|
||||
return {"turn": {"id": "turn-1", "status": "completed", "items": []}}
|
||||
|
||||
monkeypatch.setattr(client, "_request_raw", request_raw)
|
||||
started = client.turn_start("thread-1", "hello")
|
||||
registered = client._router._turn_notifications[started.turn.id]
|
||||
assert client.turn_start("thread-1", "again").turn.id == started.turn.id
|
||||
assert client._router._turn_notifications[started.turn.id] is registered
|
||||
assert client.next_turn_notification(started.turn.id) == turn_events(client)[0]
|
||||
client.unregister_turn_notifications(started.turn.id)
|
||||
with pytest.raises(RuntimeError, match="not registered"):
|
||||
client.next_turn_notification(started.turn.id)
|
||||
assert client._router._turn_states == {}
|
||||
Reference in New Issue
Block a user