From f6f5a98a83779e1037b7ac1c4890f59c05f36f31 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 14 May 2026 06:36:39 +0100 Subject: [PATCH] Delete vendored Codex SDK scaffolding --- notes/fresh-workspace-handoff.md | 23 +- state/ledgers.msgpack | Bin 112450 -> 112843 bytes state/map.yaml | 21 +- vendor/codex/pnpm-lock.yaml | 54 - vendor/codex/pnpm-workspace.yaml | 1 - vendor/codex/sdk/python-runtime/README.md | 9 - .../codex/sdk/python-runtime/hatch_build.py | 30 - .../codex/sdk/python-runtime/pyproject.toml | 45 - .../src/codex_cli_bin/__init__.py | 19 - vendor/codex/sdk/python/README.md | 103 - vendor/codex/sdk/python/_runtime_setup.py | 359 - vendor/codex/sdk/python/docs/api-reference.md | 207 - vendor/codex/sdk/python/docs/faq.md | 98 - .../codex/sdk/python/docs/getting-started.md | 108 - .../01_quickstart_constructor/async.py | 32 - .../01_quickstart_constructor/sync.py | 24 - .../sdk/python/examples/02_turn_run/async.py | 43 - .../sdk/python/examples/02_turn_run/sync.py | 34 - .../examples/03_turn_stream_events/async.py | 63 - .../examples/03_turn_stream_events/sync.py | 55 - .../examples/04_models_and_metadata/async.py | 26 - .../examples/04_models_and_metadata/sync.py | 18 - .../examples/05_existing_thread/async.py | 34 - .../examples/05_existing_thread/sync.py | 25 - .../06_thread_lifecycle_and_controls/async.py | 70 - .../06_thread_lifecycle_and_controls/sync.py | 63 - .../examples/07_image_and_text/async.py | 42 - .../python/examples/07_image_and_text/sync.py | 33 - .../examples/08_local_image_and_text/async.py | 43 - .../examples/08_local_image_and_text/sync.py | 34 - .../python/examples/09_async_parity/sync.py | 31 - .../10_error_handling_and_retry/async.py | 98 - .../10_error_handling_and_retry/sync.py | 47 - .../python/examples/11_cli_mini_app/async.py | 96 - .../python/examples/11_cli_mini_app/sync.py | 89 - .../12_turn_params_kitchen_sink/async.py | 88 - .../12_turn_params_kitchen_sink/sync.py | 78 - .../13_model_select_and_turn_params/async.py | 125 - .../13_model_select_and_turn_params/sync.py | 116 - .../python/examples/14_turn_controls/async.py | 71 - .../python/examples/14_turn_controls/sync.py | 63 - vendor/codex/sdk/python/examples/README.md | 85 - .../codex/sdk/python/examples/_bootstrap.py | 152 - .../python/notebooks/sdk_walkthrough.ipynb | 587 -- vendor/codex/sdk/python/pyproject.toml | 62 - .../python/scripts/update_sdk_artifacts.py | 1100 --- .../python/src/codex_app_server/__init__.py | 113 - .../python/src/codex_app_server/_inputs.py | 63 - .../sdk/python/src/codex_app_server/_run.py | 112 - .../sdk/python/src/codex_app_server/api.py | 755 -- .../src/codex_app_server/async_client.py | 208 - .../sdk/python/src/codex_app_server/client.py | 541 -- .../sdk/python/src/codex_app_server/errors.py | 125 - .../codex_app_server/generated/__init__.py | 1 - .../generated/notification_registry.py | 122 - .../src/codex_app_server/generated/v2_all.py | 7764 ----------------- .../sdk/python/src/codex_app_server/models.py | 99 - .../sdk/python/src/codex_app_server/py.typed | 0 .../sdk/python/src/codex_app_server/retry.py | 41 - vendor/codex/sdk/python/tests/conftest.py | 16 - .../test_artifact_workflow_and_binaries.py | 514 -- .../tests/test_async_client_behavior.py | 64 - .../python/tests/test_client_rpc_methods.py | 95 - .../python/tests/test_contract_generation.py | 52 - .../tests/test_public_api_runtime_behavior.py | 575 -- .../tests/test_public_api_signatures.py | 260 - .../tests/test_real_app_server_integration.py | 545 -- vendor/codex/sdk/typescript/.prettierignore | 3 - vendor/codex/sdk/typescript/.prettierrc | 5 - vendor/codex/sdk/typescript/README.md | 149 - vendor/codex/sdk/typescript/eslint.config.js | 21 - vendor/codex/sdk/typescript/jest.config.cjs | 32 - vendor/codex/sdk/typescript/package.json | 67 - .../sdk/typescript/samples/basic_streaming.ts | 90 - .../codex/sdk/typescript/samples/helpers.ts | 8 - .../typescript/samples/structured_output.ts | 22 - .../samples/structured_output_zod.ts | 19 - vendor/codex/sdk/typescript/src/codex.ts | 39 - .../codex/sdk/typescript/src/codexOptions.ts | 22 - vendor/codex/sdk/typescript/src/events.ts | 80 - vendor/codex/sdk/typescript/src/exec.ts | 389 - vendor/codex/sdk/typescript/src/index.ts | 40 - vendor/codex/sdk/typescript/src/items.ts | 127 - .../sdk/typescript/src/outputSchemaFile.ts | 40 - vendor/codex/sdk/typescript/src/thread.ts | 155 - .../codex/sdk/typescript/src/threadOptions.ts | 20 - .../codex/sdk/typescript/src/turnOptions.ts | 6 - .../codex/sdk/typescript/tests/abort.test.ts | 165 - .../sdk/typescript/tests/codexExecSpy.ts | 37 - .../codex/sdk/typescript/tests/exec.test.ts | 145 - .../sdk/typescript/tests/responsesProxy.ts | 225 - vendor/codex/sdk/typescript/tests/run.test.ts | 807 -- .../sdk/typescript/tests/runStreamed.test.ts | 207 - .../sdk/typescript/tests/setupCodexHome.ts | 28 - .../codex/sdk/typescript/tests/testCodex.ts | 106 - vendor/codex/sdk/typescript/tsconfig.json | 24 - vendor/codex/sdk/typescript/tsup.config.ts | 12 - 97 files changed, 25 insertions(+), 19734 deletions(-) delete mode 100644 vendor/codex/sdk/python-runtime/README.md delete mode 100644 vendor/codex/sdk/python-runtime/hatch_build.py delete mode 100644 vendor/codex/sdk/python-runtime/pyproject.toml delete mode 100644 vendor/codex/sdk/python-runtime/src/codex_cli_bin/__init__.py delete mode 100644 vendor/codex/sdk/python/README.md delete mode 100644 vendor/codex/sdk/python/_runtime_setup.py delete mode 100644 vendor/codex/sdk/python/docs/api-reference.md delete mode 100644 vendor/codex/sdk/python/docs/faq.md delete mode 100644 vendor/codex/sdk/python/docs/getting-started.md delete mode 100644 vendor/codex/sdk/python/examples/01_quickstart_constructor/async.py delete mode 100644 vendor/codex/sdk/python/examples/01_quickstart_constructor/sync.py delete mode 100644 vendor/codex/sdk/python/examples/02_turn_run/async.py delete mode 100644 vendor/codex/sdk/python/examples/02_turn_run/sync.py delete mode 100644 vendor/codex/sdk/python/examples/03_turn_stream_events/async.py delete mode 100644 vendor/codex/sdk/python/examples/03_turn_stream_events/sync.py delete mode 100644 vendor/codex/sdk/python/examples/04_models_and_metadata/async.py delete mode 100644 vendor/codex/sdk/python/examples/04_models_and_metadata/sync.py delete mode 100644 vendor/codex/sdk/python/examples/05_existing_thread/async.py delete mode 100644 vendor/codex/sdk/python/examples/05_existing_thread/sync.py delete mode 100644 vendor/codex/sdk/python/examples/06_thread_lifecycle_and_controls/async.py delete mode 100644 vendor/codex/sdk/python/examples/06_thread_lifecycle_and_controls/sync.py delete mode 100644 vendor/codex/sdk/python/examples/07_image_and_text/async.py delete mode 100644 vendor/codex/sdk/python/examples/07_image_and_text/sync.py delete mode 100644 vendor/codex/sdk/python/examples/08_local_image_and_text/async.py delete mode 100644 vendor/codex/sdk/python/examples/08_local_image_and_text/sync.py delete mode 100644 vendor/codex/sdk/python/examples/09_async_parity/sync.py delete mode 100644 vendor/codex/sdk/python/examples/10_error_handling_and_retry/async.py delete mode 100644 vendor/codex/sdk/python/examples/10_error_handling_and_retry/sync.py delete mode 100644 vendor/codex/sdk/python/examples/11_cli_mini_app/async.py delete mode 100644 vendor/codex/sdk/python/examples/11_cli_mini_app/sync.py delete mode 100644 vendor/codex/sdk/python/examples/12_turn_params_kitchen_sink/async.py delete mode 100644 vendor/codex/sdk/python/examples/12_turn_params_kitchen_sink/sync.py delete mode 100644 vendor/codex/sdk/python/examples/13_model_select_and_turn_params/async.py delete mode 100644 vendor/codex/sdk/python/examples/13_model_select_and_turn_params/sync.py delete mode 100644 vendor/codex/sdk/python/examples/14_turn_controls/async.py delete mode 100644 vendor/codex/sdk/python/examples/14_turn_controls/sync.py delete mode 100644 vendor/codex/sdk/python/examples/README.md delete mode 100644 vendor/codex/sdk/python/examples/_bootstrap.py delete mode 100644 vendor/codex/sdk/python/notebooks/sdk_walkthrough.ipynb delete mode 100644 vendor/codex/sdk/python/pyproject.toml delete mode 100644 vendor/codex/sdk/python/scripts/update_sdk_artifacts.py delete mode 100644 vendor/codex/sdk/python/src/codex_app_server/__init__.py delete mode 100644 vendor/codex/sdk/python/src/codex_app_server/_inputs.py delete mode 100644 vendor/codex/sdk/python/src/codex_app_server/_run.py delete mode 100644 vendor/codex/sdk/python/src/codex_app_server/api.py delete mode 100644 vendor/codex/sdk/python/src/codex_app_server/async_client.py delete mode 100644 vendor/codex/sdk/python/src/codex_app_server/client.py delete mode 100644 vendor/codex/sdk/python/src/codex_app_server/errors.py delete mode 100644 vendor/codex/sdk/python/src/codex_app_server/generated/__init__.py delete mode 100644 vendor/codex/sdk/python/src/codex_app_server/generated/notification_registry.py delete mode 100644 vendor/codex/sdk/python/src/codex_app_server/generated/v2_all.py delete mode 100644 vendor/codex/sdk/python/src/codex_app_server/models.py delete mode 100644 vendor/codex/sdk/python/src/codex_app_server/py.typed delete mode 100644 vendor/codex/sdk/python/src/codex_app_server/retry.py delete mode 100644 vendor/codex/sdk/python/tests/conftest.py delete mode 100644 vendor/codex/sdk/python/tests/test_artifact_workflow_and_binaries.py delete mode 100644 vendor/codex/sdk/python/tests/test_async_client_behavior.py delete mode 100644 vendor/codex/sdk/python/tests/test_client_rpc_methods.py delete mode 100644 vendor/codex/sdk/python/tests/test_contract_generation.py delete mode 100644 vendor/codex/sdk/python/tests/test_public_api_runtime_behavior.py delete mode 100644 vendor/codex/sdk/python/tests/test_public_api_signatures.py delete mode 100644 vendor/codex/sdk/python/tests/test_real_app_server_integration.py delete mode 100644 vendor/codex/sdk/typescript/.prettierignore delete mode 100644 vendor/codex/sdk/typescript/.prettierrc delete mode 100644 vendor/codex/sdk/typescript/README.md delete mode 100644 vendor/codex/sdk/typescript/eslint.config.js delete mode 100644 vendor/codex/sdk/typescript/jest.config.cjs delete mode 100644 vendor/codex/sdk/typescript/package.json delete mode 100644 vendor/codex/sdk/typescript/samples/basic_streaming.ts delete mode 100644 vendor/codex/sdk/typescript/samples/helpers.ts delete mode 100644 vendor/codex/sdk/typescript/samples/structured_output.ts delete mode 100644 vendor/codex/sdk/typescript/samples/structured_output_zod.ts delete mode 100644 vendor/codex/sdk/typescript/src/codex.ts delete mode 100644 vendor/codex/sdk/typescript/src/codexOptions.ts delete mode 100644 vendor/codex/sdk/typescript/src/events.ts delete mode 100644 vendor/codex/sdk/typescript/src/exec.ts delete mode 100644 vendor/codex/sdk/typescript/src/index.ts delete mode 100644 vendor/codex/sdk/typescript/src/items.ts delete mode 100644 vendor/codex/sdk/typescript/src/outputSchemaFile.ts delete mode 100644 vendor/codex/sdk/typescript/src/thread.ts delete mode 100644 vendor/codex/sdk/typescript/src/threadOptions.ts delete mode 100644 vendor/codex/sdk/typescript/src/turnOptions.ts delete mode 100644 vendor/codex/sdk/typescript/tests/abort.test.ts delete mode 100644 vendor/codex/sdk/typescript/tests/codexExecSpy.ts delete mode 100644 vendor/codex/sdk/typescript/tests/exec.test.ts delete mode 100644 vendor/codex/sdk/typescript/tests/responsesProxy.ts delete mode 100644 vendor/codex/sdk/typescript/tests/run.test.ts delete mode 100644 vendor/codex/sdk/typescript/tests/runStreamed.test.ts delete mode 100644 vendor/codex/sdk/typescript/tests/setupCodexHome.ts delete mode 100644 vendor/codex/sdk/typescript/tests/testCodex.ts delete mode 100644 vendor/codex/sdk/typescript/tsconfig.json delete mode 100644 vendor/codex/sdk/typescript/tsup.config.ts diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 5d432316..6f475393 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -751,13 +751,14 @@ The Codex product-surface starvation cuts are landed too. App-server apps/skills/plugin/marketplace list routes are inert, mutation/detail routes return explicit disabled errors, the helper modules and stale v2 endpoint tests were deleted, and the broken private `processor_tests.rs` implementation-shape -suite is gone. `externalAgentConfig/*` is now a compatibility husk: detect -returns no imports, import is disabled, and the Claude/app/skill/plugin import -machinery plus tests were deleted. Config no longer treats `apps` or `plugins` -as supported runtime feature enablement, no longer refreshes app lists after -feature writes, no longer starts plugin warmups at app-server startup, and no -longer emits plugin-toggle analytics from config writes. App-server no longer -depends directly on `codex-chatgpt`, `codex-core-plugins`, or `codex-plugin`. +suite is gone. `externalAgentConfig/*` was later cut completely; there is no +detect/import route, import-completed notification, TUI prompt, migration +module, snapshot, disabled handler, or generated schema left. Config no longer +treats `apps` or `plugins` as supported runtime feature enablement, no longer +refreshes app lists after feature writes, no longer starts plugin warmups at +app-server startup, and no longer emits plugin-toggle analytics from config +writes. App-server no longer depends directly on `codex-chatgpt`, +`codex-core-plugins`, or `codex-plugin`. `codex_message_processor.rs` is still too large, but it is no longer carrying the plugin marketplace altar in its chest cavity. @@ -963,6 +964,14 @@ absolute-path, and template tests. A vendored-wide search for product-shaped test names now returns only external URLs, generic URL examples, and real package names such as `eslint-plugin`; not live Codex product machinery. +The vendored Codex SDK subtree is now deleted too. `vendor/codex/sdk` was not +runtime auth/model spine machinery; it was Python/TypeScript app-server client +and release packaging scaffolding, including stale generated Python types for +plugin, marketplace, and external-agent routes after the live Rust protocol had +already stopped owning those organs. The root pnpm workspace no longer lists +`sdk/typescript`, the lockfile SDK importer is gone, and a vendored-wide search +for those stale SDK/product route strings is empty. + The typed worker-result boundary is now stricter. `roleResult` and `reorientResult` read-back no longer falls back from `EpiphanyRuntimeRoleWorkerResult` / `EpiphanyRuntimeReorientWorkerResult` diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index 7291c148158c6dd5bf2451c053838076465e36be..54fccd44ad06712c562e845000eff52469bf3960 100644 GIT binary patch delta 398 zcmZ9IJxc>Y5QaI6fLPlPh+x3W#l%=7m1rXtf*+0DW^Zy?Zf|$lnM-07L3@>e_WlFG zph7BJ{Vjt3z`c}q^YP9*&&=mf?d!L8zp?WE@UrqKehsQu=pFJXMtu1?rtU3v$c^&#FMM(&X zVJrxQb1|VGp$DlI8csZF6hS~z3DIlOmXEps7;^dzGKi zWI+n=Re&KD8X-f2UU0~rE;D74LiilnX(2Je38Obc$0EoWye%1luN+bXPHouej4NPl zeNHauL6{V@l{u)wSs!Kt7U&CWvJh%T4B^6LX&}9F+=J7yDpr6MR~G1o80LwU*5CwD OSatpS|Fhk8=kgCxUyyA8 delta 49 zcmX^8k?qhswh78i+c`F>PGe-$Xx_uPeGemJ!B(+`Ek*`LX1WHZx`rkp2Bua` or `` prompt compatibility, memory usage classification, snapshot normalization, or cleanup paths. Remaining product-shaped skill residue is also cut from memory templates, app-server docs/tests/warnings, TUI tooltips/placeholders/warnings/comments, app-server v1 docs, agent-tool schema text, stale `UserInput::Skill` test arms, and obsolete feature flags/schema entries. App-instruction prompt compatibility is cut too: no `APPS_INSTRUCTIONS` protocol constants, no `` snapshot canonicalization, and MCP fixture tests now use neutral `demo_mcp` / `calendar_mcp` names instead of `codex_apps` / `/api/codex/apps` branding. The TUI app connector product path is also deleted: no `/apps` slash command, app-link view, connector AppEvent variants, app connector cache/popup/refresh loop, app mention insertion, `app://` mention codec support, stale app-popup tests, or TUI browser-opening shim remains. The `app/list` route and `app/list/updated` notification are gone from app-server protocol, generated schemas, app-server dispatch, test helpers, and docs; `AppInfo`/app-list metadata schema structs are deleted; the orphaned `codex-connectors` crate and `core::connectors` shim are deleted from the workspace; Codex app analytics no longer tracks `codex_app_mentioned` / `codex_app_used` facts, events, reducer arms, client APIs, or dedupe cache state; `[apps.*]`, `Feature::Apps`, `include_apps_instructions`, app config/read schemas, app managed requirements, app prompt tests, and app file-MCP tests are gone; `Feature::Plugins`, `Feature::RemotePlugin`, `plugin://` structured mentions, plugin instruction tags, and stale plugin popup snapshots are gone too; `[plugins]` / `[marketplaces]`, `PluginConfig`, `MarketplaceConfig`, marketplace edit helpers, stale plugin/external-agent README route claims, and generated schema entries are removed from config; and the bundled `codex-skills` sample-skill crate plus embedded imagegen/openai-docs/plugin-creator/skill-creator/skill-installer payloads are deleted from the workspace. Live MCP tool approval is named `McpToolApproval`, not `AppToolApproval`, and remains under MCP server config; live structured user-input mentions are MCP-shaped only. `codex_message_processor.rs` is about 9,482 lines; root `message_processor.rs` is about 1,292 lines after the external-agent/config-product cuts; `epiphany_read_routes.rs` is about 579 lines after the full view and read-response extractions; `epiphany_mutation_routes.rs` is about 694 lines after route-load/notification helper cuts and product-surface starvation; `epiphany_state_helpers.rs` is down to a 19-line rollout-state loader; and `codex_thread.rs` is about 1,425 lines after state-update law moved native. `epiphany-openai-adapter` defines CultCache `DatabaseEntry` request/event/receipt/auth-status documents with no Codex app-server or generic JSON dependency. `epiphany-openai-codex-spine` owns all direct Codex auth/model-transport imports for the native OpenAI path: it exposes `default_codex_home` and `auth_manager`, projects `AuthManager` / `CodexAuth` into typed `EpiphanyOpenAiAdapterStatus`, maps typed `EpiphanyOpenAiModelRequest` into Codex API `ResponsesApiRequest`, resolves auth/provider through keeper Codex crates, opens HTTP Responses streams through `codex-api`, maps deltas / completion into typed stream events and receipts, and no longer directly depends on `codex-app-server-protocol` just to name auth mode. `epiphany-openai-runtime` no longer depends directly on `codex-login`; it writes OpenAI status/request/stream-event/receipt records plus runtime sessions/jobs/results/events into `epiphany-core::runtime_spine_cache`, can emit the assistant text artifact for legacy result consumers, is now the default executor for startup-only repo birth specialists, and now has `run-worker` to load a durable `EpiphanyRuntimeWorkerLaunchRequest`, call the typed OpenAI runtime through the spine, persist typed `EpiphanyRuntimeRoleWorkerResult` / `EpiphanyRuntimeReorientWorkerResult` documents, and complete the original heartbeat/specialist runtime job without Codex worker execution; `codex exec` survives only as explicit fallback in repo-birth startup. `epiphany-mvp-coordinator` now invokes `epiphany-openai-runtime run-worker` for launched runtime job ids and no longer creates a second coordinator-owned shadow runtime job/result as a compensator. `epiphany-core::plan_runtime_spine_heartbeat_launch` validates launch contracts/conflicts and projects durable job bindings/runtime links; `epiphany-core::open_runtime_spine_heartbeat_job` owns the initialize-runtime/ensure-session/create-job sequence and now persists `EpiphanyRuntimeWorkerLaunchRequest` CultCache records keyed by runtime job id, with indexed kind/contract fields plus MessagePack-encoded typed launch documents instead of discarding work intent after queue receipt creation; `roleResult` and `reorientResult` now require typed worker result documents; generic job summaries are lifecycle receipts, not reviewable findings; `epiphany-core::EpiphanyStateUpdate`, `epiphany_state_update_validation_errors`, and `apply_epiphany_state_update` own state-update document shape and mutation law while `codex-core` calls them for compatibility. Vendored `CodexThread::epiphany_launch_job` is now mostly revision check, persistence validation, launch request handoff, and rollout/session writeback for the compatibility route. Vendored `codex-core` no longer has `epiphany_distillation`, `epiphany_promotion`, `epiphany_proposal`, or `epiphany_retrieval` husk modules; it re-exports native surfaces from `epiphany-core` directly, and now owns only the real Codex rollout adapter because it is a host seam. `epiphany-runtime-spine` advertises OpenAI adapter status/model-request/stream-event/receipt CultNet schemas and mutation contracts, so the native caller now has a real storage route instead of only JSON-RPC. MCP itself is correctly JSON at its protocol edge; the target is typed Epiphany intent/result/receipt wrappers around MCP, not replacing MCP JSON. The current OpenAI spine still pulls `codex-api` and a large transport dependency stack, so its next cut is dependency starvation after richer live callers move. + summary: The Codex starvation pass has five typing receipts, fifty-two processor/foundation cuts, a real physical extraction in `epiphany-codex-bridge`, a root `epiphany-state-model` crate for durable Epiphany state, a source-grounded Codex auth spine inventory, the native `epiphany-openai-adapter` document boundary, a buildable Codex auth/model wrapper in `epiphany-openai-codex-spine`, the first native runtime caller in `epiphany-openai-runtime`, native heartbeat launch planning/job opening in `epiphany-core`, native state-update contract/validation/application in `epiphany-core`, native exact retrieval path matching in `epiphany-core`, and the route-facing mutation/view/coordinator projection services in `epiphany-codex-bridge`. `codex-protocol` no longer defines the durable `Epiphany*` state structs; it re-exports the native model for legacy rollout/API compatibility while `epiphany-core` imports the native model directly. `epiphany-core` now has no direct vendored Codex dependency: pressure derivation accepts native `EpiphanyTokenUsageSnapshot`, Codex rollout replay moved to `codex-core::epiphany_rollout`, and exact retrieval search uses Epiphany-owned workspace walking/path scoring instead of `codex-file-search`. The bridge owns Codex-facing Epiphany adapters for scene, jobs, context/planning/graph query, retrieval/indexing projection, result projection, runtime-spine result adaptation, launch/prompt doctrine, mutation document mechanics, mutation service update/promote/role-accept/reorient-accept/role-launch/reorient-launch/job-launch/job-interrupt application, live-state projection, pressure/pre-compaction rendering, freshness/reorientation projection, CRRC/coordinator/role-board projection, watcher invalidation adaptation, full `thread/epiphany/view` response construction, freshness/context/graph-query response construction, role/reorient result response construction, distill/propose patch-response construction, coordinator status/view construction, and acceptance/evidence signal helpers. Vendored app-server no longer retains root Epiphany modules; `codex_message_processor.rs` still contains route dispatch, JSON-RPC response shaping, watcher registration/snapshotting calls, and notification emission, but its root no longer imports the evacuated Epiphany policy/protocol registry or owns the watcher invalidation manager. Codex product surfaces for apps, skills, plugins, marketplace, and external agent config import are cut from the live app-server/protocol path: list routes return empty lists only where compatibility shells still exist, mutation/detail routes report disabled where they survive, `externalAgentConfig/*` routes and import-completed notification are gone, helper/import modules and stale implementation-shape tests were deleted, runtime feature enablement no longer supports `apps` or `plugins`, config writes no longer emit plugin-toggle analytics, plugin/skill cache invalidation on config writes is gone, plugin startup warmups and app-list refreshes were removed, and app-server no longer directly depends on `codex-plugin`, `codex-chatgpt`, or `codex-core-plugins`. `Config::to_mcp_config` now keeps user-declared MCP servers but no longer accepts `PluginsManager`, folds plugin MCP servers into the runtime, enables Codex apps, enables skill MCP dependency install, or advertises plugin capability summaries; `TurnContext::apps_enabled()` now returns false so model turns cannot awaken Codex Apps through ChatGPT auth or feature flags; session startup and per-turn context no longer load skills, turns receive an empty `SkillLoadOutcome`, internal `Op::ListSkills` is gone from `codex-protocol` / `codex-core` / TUI command routing, the Codex skill watcher has been collapsed to a no-op marker with no file watcher, skill-root registration, cache-clear task, or `SkillsUpdateAvailable` session listener, model turns no longer run skill mention collection, skill env-var prompts, skill MCP dependency installation, skill instruction injection, or implicit skill invocation analytics from shell tools, and the turn prompt/router path no longer loads plugin/app capability summaries, injects available-skill/available-plugin/plugin instruction fragments, parses plugin/app mentions, records app/plugin invocation telemetry, or filters MCP tools through Codex app connectors. Skill mutation/list/notification is gone from the app-server edge too: `skills/list`, `skills/config/write`, `skills/changed`, `Op::ListSkills`, `EventMsg::ListSkillsResponse`, `EventMsg::SkillsUpdateAvailable`, the app-server handlers, TUI slash/startup/list/manage-skill surfaces, generated schema entries, core skill-list suite, and fake live-reload/developer-message tests were deleted. Skill mention plumbing is also gone from the live TUI/protocol edge: no `UserInput::Skill` variant, app-server schema branch, TUI skill popup, `skills_all` cache, composer `set_skill_mentions`, skill mention insertion, `skill://` / `SKILL.md` history decoding, or stale skill popup snapshot remains. The `codex-core-skills` crate, core `skills` re-export shim, no-op `skills_watcher`, session `SkillsManager` service, and per-turn `TurnSkillsContext` are deleted; core/protocol no longer keep legacy `` or `` prompt compatibility, memory usage classification, snapshot normalization, or cleanup paths. Remaining product-shaped skill residue is also cut from memory templates, app-server docs/tests/warnings, TUI tooltips/placeholders/warnings/comments, app-server v1 docs, agent-tool schema text, stale `UserInput::Skill` test arms, and obsolete feature flags/schema entries. App-instruction prompt compatibility is cut too: no `APPS_INSTRUCTIONS` protocol constants, no `` snapshot canonicalization, and MCP fixture tests now use neutral `demo_mcp` / `calendar_mcp` names instead of `codex_apps` / `/api/codex/apps` branding. The TUI app connector product path is also deleted: no `/apps` slash command, app-link view, connector AppEvent variants, app connector cache/popup/refresh loop, app mention insertion, `app://` mention codec support, stale app-popup tests, or TUI browser-opening shim remains. The `app/list` route and `app/list/updated` notification are gone from app-server protocol, generated schemas, app-server dispatch, test helpers, and docs; `AppInfo`/app-list metadata schema structs are deleted; the orphaned `codex-connectors` crate and `core::connectors` shim are deleted from the workspace; Codex app analytics no longer tracks `codex_app_mentioned` / `codex_app_used` facts, events, reducer arms, client APIs, or dedupe cache state; `[apps.*]`, `Feature::Apps`, `include_apps_instructions`, app config/read schemas, app managed requirements, app prompt tests, and app file-MCP tests are gone; `Feature::Plugins`, `Feature::RemotePlugin`, `plugin://` structured mentions, plugin instruction tags, and stale plugin popup snapshots are gone too; `[plugins]` / `[marketplaces]`, `PluginConfig`, `MarketplaceConfig`, marketplace edit helpers, stale plugin/external-agent README route claims, and generated schema entries are removed from config; and the bundled `codex-skills` sample-skill crate plus embedded imagegen/openai-docs/plugin-creator/skill-creator/skill-installer payloads are deleted from the workspace. The vendored `vendor/codex/sdk` subtree is deleted as non-spine app-server client/release scaffolding, including stale generated Python SDK route types for removed product surfaces; the root pnpm workspace no longer lists `sdk/typescript`. Live MCP tool approval is named `McpToolApproval`, not `AppToolApproval`, and remains under MCP server config; live structured user-input mentions are MCP-shaped only. `codex_message_processor.rs` is about 9,482 lines; root `message_processor.rs` is about 1,292 lines after the external-agent/config-product cuts; `epiphany_read_routes.rs` is about 579 lines after the full view and read-response extractions; `epiphany_mutation_routes.rs` is about 694 lines after route-load/notification helper cuts and product-surface starvation; `epiphany_state_helpers.rs` is down to a 19-line rollout-state loader; and `codex_thread.rs` is about 1,425 lines after state-update law moved native. `epiphany-openai-adapter` defines CultCache `DatabaseEntry` request/event/receipt/auth-status documents with no Codex app-server or generic JSON dependency. `epiphany-openai-codex-spine` owns all direct Codex auth/model-transport imports for the native OpenAI path: it exposes `default_codex_home` and `auth_manager`, projects `AuthManager` / `CodexAuth` into typed `EpiphanyOpenAiAdapterStatus`, maps typed `EpiphanyOpenAiModelRequest` into Codex API `ResponsesApiRequest`, resolves auth/provider through keeper Codex crates, opens HTTP Responses streams through `codex-api`, maps deltas / completion into typed stream events and receipts, and no longer directly depends on `codex-app-server-protocol` just to name auth mode. `epiphany-openai-runtime` no longer depends directly on `codex-login`; it writes OpenAI status/request/stream-event/receipt records plus runtime sessions/jobs/results/events into `epiphany-core::runtime_spine_cache`, can emit the assistant text artifact for legacy result consumers, is now the default executor for startup-only repo birth specialists, and now has `run-worker` to load a durable `EpiphanyRuntimeWorkerLaunchRequest`, call the typed OpenAI runtime through the spine, persist typed `EpiphanyRuntimeRoleWorkerResult` / `EpiphanyRuntimeReorientWorkerResult` documents, and complete the original heartbeat/specialist runtime job without Codex worker execution; `codex exec` survives only as explicit fallback in repo-birth startup. `epiphany-mvp-coordinator` now invokes `epiphany-openai-runtime run-worker` for launched runtime job ids and no longer creates a second coordinator-owned shadow runtime job/result as a compensator. `epiphany-core::plan_runtime_spine_heartbeat_launch` validates launch contracts/conflicts and projects durable job bindings/runtime links; `epiphany-core::open_runtime_spine_heartbeat_job` owns the initialize-runtime/ensure-session/create-job sequence and now persists `EpiphanyRuntimeWorkerLaunchRequest` CultCache records keyed by runtime job id, with indexed kind/contract fields plus MessagePack-encoded typed launch documents instead of discarding work intent after queue receipt creation; `roleResult` and `reorientResult` now require typed worker result documents; generic job summaries are lifecycle receipts, not reviewable findings; `epiphany-core::EpiphanyStateUpdate`, `epiphany_state_update_validation_errors`, and `apply_epiphany_state_update` own state-update document shape and mutation law while `codex-core` calls them for compatibility. Vendored `CodexThread::epiphany_launch_job` is now mostly revision check, persistence validation, launch request handoff, and rollout/session writeback for the compatibility route. Vendored `codex-core` no longer has `epiphany_distillation`, `epiphany_promotion`, `epiphany_proposal`, or `epiphany_retrieval` husk modules; it re-exports native surfaces from `epiphany-core` directly, and now owns only the real Codex rollout adapter because it is a host seam. `epiphany-runtime-spine` advertises OpenAI adapter status/model-request/stream-event/receipt CultNet schemas and mutation contracts, so the native caller now has a real storage route instead of only JSON-RPC. MCP itself is correctly JSON at its protocol edge; the target is typed Epiphany intent/result/receipt wrappers around MCP, not replacing MCP JSON. The current OpenAI spine still pulls `codex-api` and a large transport dependency stack, so its next cut is dependency starvation after richer live callers move. latest_cut: > - Runtime role/reorient read-back no longer falls back from typed - `EpiphanyRuntimeRoleWorkerResult` / `EpiphanyRuntimeReorientWorkerResult` - documents to generic `EpiphanyRuntimeJobResult` lifecycle receipts. A - completed runtime job without the typed worker-result CultCache document now - reports backend-unavailable with a repair note instead of manufacturing a - reviewable finding from summary strings. Generic runtime job results remain - lifecycle receipts; reviewable specialist findings are typed documents. The - unused bridge functions that accepted raw JSON findings were deleted, and - the remaining raw-result interpreters are private test fixtures rather than - public runtime API. - next_action: Continue starving coordinator/runtime execution and operator surfaces off app-server JSON-RPC and out of `codex_message_processor.rs`; keep the vestigial Codex organ narrowed to subscription auth/model transport. + The vendored Codex SDK subtree is cut. `vendor/codex/sdk` was release/client + scaffolding for Python and TypeScript app-server SDKs, including stale + generated Python routes for plugin, marketplace, and external-agent config + surfaces that the live Rust protocol no longer owned. No Rust runtime package + depended on it; the root pnpm workspace no longer lists `sdk/typescript`, and + offline pnpm lockfile refresh removed the SDK importer. The actual Codex + spine still builds after deletion. + next_action: Continue starving coordinator/runtime execution and operator surfaces off app-server JSON-RPC and out of `codex_message_processor.rs`; next suspicion is physical extraction of Epiphany route/helper logic from vendored app-server without inventing compensator traits. diff --git a/vendor/codex/pnpm-lock.yaml b/vendor/codex/pnpm-lock.yaml index 03ff4643..6d3b2238 100644 --- a/vendor/codex/pnpm-lock.yaml +++ b/vendor/codex/pnpm-lock.yaml @@ -31,60 +31,6 @@ importers: codex-rs/responses-api-proxy/npm: {} - sdk/typescript: - devDependencies: - '@modelcontextprotocol/sdk': - specifier: 1.26.0 - version: 1.26.0(zod@3.25.76) - '@types/jest': - specifier: ^29.5.14 - version: 29.5.14 - '@types/node': - specifier: ^20.19.18 - version: 20.19.18 - eslint: - specifier: ^9.36.0 - version: 9.36.0 - eslint-config-prettier: - specifier: ^9.1.2 - version: 9.1.2(eslint@9.36.0) - eslint-plugin-jest: - specifier: ^29.0.1 - version: 29.0.1(@typescript-eslint/eslint-plugin@8.45.0(@typescript-eslint/parser@8.45.0(eslint@9.36.0)(typescript@5.9.2))(eslint@9.36.0)(typescript@5.9.2))(eslint@9.36.0)(jest@29.7.0(@types/node@20.19.18)(ts-node@10.9.2(@types/node@20.19.18)(typescript@5.9.2)))(typescript@5.9.2) - eslint-plugin-node-import: - specifier: ^1.0.5 - version: 1.0.5(eslint@9.36.0) - jest: - specifier: ^29.7.0 - version: 29.7.0(@types/node@20.19.18)(ts-node@10.9.2(@types/node@20.19.18)(typescript@5.9.2)) - prettier: - specifier: ^3.6.2 - version: 3.6.2 - ts-jest: - specifier: ^29.3.4 - version: 29.4.4(@babel/core@7.28.4)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.28.4))(esbuild@0.25.10)(jest-util@29.7.0)(jest@29.7.0(@types/node@20.19.18)(ts-node@10.9.2(@types/node@20.19.18)(typescript@5.9.2)))(typescript@5.9.2) - ts-jest-mock-import-meta: - specifier: ^1.3.1 - version: 1.3.1(ts-jest@29.4.4(@babel/core@7.28.4)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.28.4))(esbuild@0.25.10)(jest-util@29.7.0)(jest@29.7.0(@types/node@20.19.18)(ts-node@10.9.2(@types/node@20.19.18)(typescript@5.9.2)))(typescript@5.9.2)) - ts-node: - specifier: ^10.9.2 - version: 10.9.2(@types/node@20.19.18)(typescript@5.9.2) - tsup: - specifier: ^8.5.0 - version: 8.5.0(postcss@8.5.6)(typescript@5.9.2)(yaml@2.8.1) - typescript: - specifier: ^5.9.2 - version: 5.9.2 - typescript-eslint: - specifier: ^8.45.0 - version: 8.45.0(eslint@9.36.0)(typescript@5.9.2) - zod: - specifier: ^3.24.2 - version: 3.25.76 - zod-to-json-schema: - specifier: ^3.24.6 - version: 3.24.6(zod@3.25.76) - packages: '@babel/code-frame@7.27.1': diff --git a/vendor/codex/pnpm-workspace.yaml b/vendor/codex/pnpm-workspace.yaml index 8643d3f9..888e78f0 100644 --- a/vendor/codex/pnpm-workspace.yaml +++ b/vendor/codex/pnpm-workspace.yaml @@ -1,7 +1,6 @@ packages: - codex-cli - codex-rs/responses-api-proxy/npm - - sdk/typescript ignoredBuiltDependencies: - esbuild diff --git a/vendor/codex/sdk/python-runtime/README.md b/vendor/codex/sdk/python-runtime/README.md deleted file mode 100644 index 22c59ef1..00000000 --- a/vendor/codex/sdk/python-runtime/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# Codex CLI Runtime for Python SDK - -Platform-specific runtime package consumed by the published `codex-app-server-sdk`. - -This package is staged during release so the SDK can pin an exact Codex CLI -version without checking platform binaries into the repo. - -`openai-codex-cli-bin` is intentionally wheel-only. Do not build or publish an -sdist for this package. diff --git a/vendor/codex/sdk/python-runtime/hatch_build.py b/vendor/codex/sdk/python-runtime/hatch_build.py deleted file mode 100644 index d49e3e10..00000000 --- a/vendor/codex/sdk/python-runtime/hatch_build.py +++ /dev/null @@ -1,30 +0,0 @@ -from __future__ import annotations - -import os - -from hatchling.builders.hooks.plugin.interface import BuildHookInterface - - -def _platform_tag() -> str: - from packaging.tags import sys_tags - - return next(iter(sys_tags())).platform - - -class RuntimeBuildHook(BuildHookInterface): - def initialize(self, version: str, build_data: dict[str, object]) -> None: - del version - if self.target_name == "sdist": - raise RuntimeError( - "openai-codex-cli-bin is wheel-only; build and publish platform wheels only." - ) - - platform_tag = self.config.get("platform-tag") or os.environ.get( - "CODEX_CLI_BIN_PLATFORM_TAG" - ) - if not isinstance(platform_tag, str) or not platform_tag: - platform_tag = _platform_tag() - - build_data["pure_python"] = False - build_data["infer_tag"] = False - build_data["tag"] = f"py3-none-{platform_tag}" diff --git a/vendor/codex/sdk/python-runtime/pyproject.toml b/vendor/codex/sdk/python-runtime/pyproject.toml deleted file mode 100644 index 281cb7d1..00000000 --- a/vendor/codex/sdk/python-runtime/pyproject.toml +++ /dev/null @@ -1,45 +0,0 @@ -[build-system] -requires = ["hatchling>=1.24.0"] -build-backend = "hatchling.build" - -[project] -name = "openai-codex-cli-bin" -version = "0.0.0-dev" -description = "Pinned Codex CLI runtime for the Python SDK" -readme = "README.md" -requires-python = ">=3.10" -license = { text = "Apache-2.0" } -authors = [{ name = "OpenAI" }] -classifiers = [ - "Development Status :: 4 - Beta", - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", -] - -[project.urls] -Homepage = "https://github.com/openai/codex" -Repository = "https://github.com/openai/codex" -Issues = "https://github.com/openai/codex/issues" - -[tool.hatch.build] -exclude = [ - ".venv/**", - ".pytest_cache/**", - "dist/**", - "build/**", -] - -[tool.hatch.build.targets.wheel] -packages = ["src/codex_cli_bin"] -include = ["src/codex_cli_bin/bin/**"] - -[tool.hatch.build.targets.wheel.hooks.custom] - -[tool.hatch.build.targets.sdist] - -[tool.hatch.build.targets.sdist.hooks.custom] diff --git a/vendor/codex/sdk/python-runtime/src/codex_cli_bin/__init__.py b/vendor/codex/sdk/python-runtime/src/codex_cli_bin/__init__.py deleted file mode 100644 index dbd9a6f6..00000000 --- a/vendor/codex/sdk/python-runtime/src/codex_cli_bin/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -from __future__ import annotations - -import os -from pathlib import Path - -PACKAGE_NAME = "openai-codex-cli-bin" - - -def bundled_codex_path() -> Path: - exe = "codex.exe" if os.name == "nt" else "codex" - path = Path(__file__).resolve().parent / "bin" / exe - if not path.is_file(): - raise FileNotFoundError( - f"{PACKAGE_NAME} is installed but missing its packaged codex binary at {path}" - ) - return path - - -__all__ = ["PACKAGE_NAME", "bundled_codex_path"] diff --git a/vendor/codex/sdk/python/README.md b/vendor/codex/sdk/python/README.md deleted file mode 100644 index 1331ebfe..00000000 --- a/vendor/codex/sdk/python/README.md +++ /dev/null @@ -1,103 +0,0 @@ -# Codex App Server Python SDK (Experimental) - -Experimental Python SDK for `codex app-server` JSON-RPC v2 over stdio, with a small default surface optimized for real scripts and apps. - -The generated wire-model layer is currently sourced from the bundled v2 schema and exposed as Pydantic models with snake_case Python fields that serialize back to the app-server’s camelCase wire format. - -## Install - -```bash -cd sdk/python -python -m pip install -e . -``` - -Published SDK builds pin an exact `openai-codex-cli-bin` runtime dependency. For local -repo development, either pass `AppServerConfig(codex_bin=...)` to point at a -local build explicitly, or use the repo examples/notebook bootstrap which -installs the pinned runtime package automatically. - -## Quickstart - -```python -from codex_app_server import Codex - -with Codex() as codex: - thread = codex.thread_start(model="gpt-5") - result = thread.run("Say hello in one sentence.") - print(result.final_response) - print(len(result.items)) -``` - -`result.final_response` is `None` when the turn completes without a final-answer -or phase-less assistant message item. - -## Docs map - -- Golden path tutorial: `docs/getting-started.md` -- API reference (signatures + behavior): `docs/api-reference.md` -- Common decisions and pitfalls: `docs/faq.md` -- Runnable examples index: `examples/README.md` -- Jupyter walkthrough notebook: `notebooks/sdk_walkthrough.ipynb` - -## Examples - -Start here: - -```bash -cd sdk/python -python examples/01_quickstart_constructor/sync.py -python examples/01_quickstart_constructor/async.py -``` - -## Runtime packaging - -The repo no longer checks `codex` binaries into `sdk/python`. - -Published SDK builds are pinned to an exact `openai-codex-cli-bin` package version, -and that runtime package carries the platform-specific binary for the target -wheel. - -For local repo development, the checked-in `sdk/python-runtime` package is only -a template for staged release artifacts. Editable installs should use an -explicit `codex_bin` override for manual SDK usage; the repo examples and -notebook bootstrap the pinned runtime package automatically. - -## Maintainer workflow - -```bash -cd sdk/python -python scripts/update_sdk_artifacts.py generate-types -python scripts/update_sdk_artifacts.py \ - stage-sdk \ - /tmp/codex-python-release/codex-app-server-sdk \ - --runtime-version 1.2.3 -python scripts/update_sdk_artifacts.py \ - stage-runtime \ - /tmp/codex-python-release/openai-codex-cli-bin \ - /path/to/codex \ - --runtime-version 1.2.3 -``` - -This supports the CI release flow: - -- run `generate-types` before packaging -- stage `codex-app-server-sdk` once with an exact `openai-codex-cli-bin==...` dependency -- stage `openai-codex-cli-bin` on each supported platform runner with the same pinned runtime version -- build and publish `openai-codex-cli-bin` as platform wheels only; do not publish an sdist - -## Compatibility and versioning - -- Package: `codex-app-server-sdk` -- Runtime package: `openai-codex-cli-bin` -- Current SDK version in this repo: `0.2.0` -- Python: `>=3.10` -- Target protocol: Codex `app-server` JSON-RPC v2 -- Recommendation: keep SDK and `codex` CLI reasonably up to date together - -## Notes - -- `Codex()` is eager and performs startup + `initialize` in the constructor. -- Use context managers (`with Codex() as codex:`) to ensure shutdown. -- Prefer `thread.run("...")` for the common case. Use `thread.turn(...)` when - you need streaming, steering, or interrupt control. -- For transient overload, use `codex_app_server.retry.retry_on_overload`. diff --git a/vendor/codex/sdk/python/_runtime_setup.py b/vendor/codex/sdk/python/_runtime_setup.py deleted file mode 100644 index 6c4cf457..00000000 --- a/vendor/codex/sdk/python/_runtime_setup.py +++ /dev/null @@ -1,359 +0,0 @@ -from __future__ import annotations - -import importlib -import importlib.util -import json -import os -import platform -import shutil -import subprocess -import sys -import tarfile -import tempfile -import urllib.error -import urllib.request -import zipfile -from pathlib import Path - -PACKAGE_NAME = "openai-codex-cli-bin" -PINNED_RUNTIME_VERSION = "0.116.0-alpha.1" -REPO_SLUG = "openai/codex" - - -class RuntimeSetupError(RuntimeError): - pass - - -def pinned_runtime_version() -> str: - return PINNED_RUNTIME_VERSION - - -def ensure_runtime_package_installed( - python_executable: str | Path, - sdk_python_dir: Path, - install_target: Path | None = None, -) -> str: - requested_version = pinned_runtime_version() - installed_version = None - if install_target is None: - installed_version = _installed_runtime_version(python_executable) - normalized_requested = _normalized_package_version(requested_version) - - if installed_version is not None and _normalized_package_version(installed_version) == normalized_requested: - return requested_version - - with tempfile.TemporaryDirectory(prefix="codex-python-runtime-") as temp_root_str: - temp_root = Path(temp_root_str) - archive_path = _download_release_archive(requested_version, temp_root) - runtime_binary = _extract_runtime_binary(archive_path, temp_root) - staged_runtime_dir = _stage_runtime_package( - sdk_python_dir, - requested_version, - runtime_binary, - temp_root / "runtime-stage", - ) - _install_runtime_package(python_executable, staged_runtime_dir, install_target) - - if install_target is not None: - return requested_version - - if Path(python_executable).resolve() == Path(sys.executable).resolve(): - importlib.invalidate_caches() - - installed_version = _installed_runtime_version(python_executable) - if installed_version is None or _normalized_package_version(installed_version) != normalized_requested: - raise RuntimeSetupError( - f"Expected {PACKAGE_NAME} {requested_version} in {python_executable}, " - f"but found {installed_version!r} after installation." - ) - return requested_version - - -def platform_asset_name() -> str: - system = platform.system().lower() - machine = platform.machine().lower() - - if system == "darwin": - if machine in {"arm64", "aarch64"}: - return "codex-aarch64-apple-darwin.tar.gz" - if machine in {"x86_64", "amd64"}: - return "codex-x86_64-apple-darwin.tar.gz" - elif system == "linux": - if machine in {"aarch64", "arm64"}: - return "codex-aarch64-unknown-linux-musl.tar.gz" - if machine in {"x86_64", "amd64"}: - return "codex-x86_64-unknown-linux-musl.tar.gz" - elif system == "windows": - if machine in {"aarch64", "arm64"}: - return "codex-aarch64-pc-windows-msvc.exe.zip" - if machine in {"x86_64", "amd64"}: - return "codex-x86_64-pc-windows-msvc.exe.zip" - - raise RuntimeSetupError( - f"Unsupported runtime artifact platform: system={platform.system()!r}, " - f"machine={platform.machine()!r}" - ) - - -def runtime_binary_name() -> str: - return "codex.exe" if platform.system().lower() == "windows" else "codex" - - -def _installed_runtime_version(python_executable: str | Path) -> str | None: - snippet = ( - "import importlib.metadata, json, sys\n" - "try:\n" - " from codex_cli_bin import bundled_codex_path\n" - " bundled_codex_path()\n" - f" print(json.dumps({{'version': importlib.metadata.version({PACKAGE_NAME!r})}}))\n" - "except Exception:\n" - " sys.exit(1)\n" - ) - result = subprocess.run( - [str(python_executable), "-c", snippet], - text=True, - capture_output=True, - check=False, - ) - if result.returncode != 0: - return None - return json.loads(result.stdout)["version"] - - -def _release_metadata(version: str) -> dict[str, object]: - url = f"https://api.github.com/repos/{REPO_SLUG}/releases/tags/rust-v{version}" - token = _github_token() - attempts = [True, False] if token is not None else [False] - last_error: urllib.error.HTTPError | None = None - - for include_auth in attempts: - headers = { - "Accept": "application/vnd.github+json", - "User-Agent": "codex-python-runtime-setup", - } - if include_auth and token is not None: - headers["Authorization"] = f"Bearer {token}" - - request = urllib.request.Request(url, headers=headers) - try: - with urllib.request.urlopen(request) as response: - return json.load(response) - except urllib.error.HTTPError as exc: - last_error = exc - if include_auth and exc.code == 401: - continue - break - - assert last_error is not None - raise RuntimeSetupError( - f"Failed to resolve release metadata for rust-v{version} from {REPO_SLUG}: " - f"{last_error.code} {last_error.reason}" - ) from last_error - - -def _download_release_archive(version: str, temp_root: Path) -> Path: - asset_name = platform_asset_name() - archive_path = temp_root / asset_name - - browser_download_url = ( - f"https://github.com/{REPO_SLUG}/releases/download/rust-v{version}/{asset_name}" - ) - request = urllib.request.Request( - browser_download_url, - headers={"User-Agent": "codex-python-runtime-setup"}, - ) - try: - with urllib.request.urlopen(request) as response, archive_path.open("wb") as fh: - shutil.copyfileobj(response, fh) - return archive_path - except urllib.error.HTTPError: - pass - - metadata = _release_metadata(version) - assets = metadata.get("assets") - if not isinstance(assets, list): - raise RuntimeSetupError(f"Release rust-v{version} returned malformed assets metadata.") - asset = next( - ( - item - for item in assets - if isinstance(item, dict) and item.get("name") == asset_name - ), - None, - ) - if asset is None: - raise RuntimeSetupError( - f"Release rust-v{version} does not contain asset {asset_name} for this platform." - ) - - api_url = asset.get("url") - if not isinstance(api_url, str): - api_url = None - - if api_url is not None: - token = _github_token() - if token is not None: - request = urllib.request.Request( - api_url, - headers=_github_api_headers("application/octet-stream"), - ) - try: - with urllib.request.urlopen(request) as response, archive_path.open("wb") as fh: - shutil.copyfileobj(response, fh) - return archive_path - except urllib.error.HTTPError: - pass - - if shutil.which("gh") is None: - raise RuntimeSetupError( - f"Unable to download {asset_name} for rust-v{version}. " - "Provide GH_TOKEN/GITHUB_TOKEN or install/authenticate GitHub CLI." - ) - - try: - subprocess.run( - [ - "gh", - "release", - "download", - f"rust-v{version}", - "--repo", - REPO_SLUG, - "--pattern", - asset_name, - "--dir", - str(temp_root), - ], - check=True, - text=True, - capture_output=True, - ) - except subprocess.CalledProcessError as exc: - raise RuntimeSetupError( - f"gh release download failed for rust-v{version} asset {asset_name}.\n" - f"STDOUT:\n{exc.stdout}\nSTDERR:\n{exc.stderr}" - ) from exc - return archive_path - - -def _extract_runtime_binary(archive_path: Path, temp_root: Path) -> Path: - extract_dir = temp_root / "extracted" - extract_dir.mkdir(parents=True, exist_ok=True) - if archive_path.name.endswith(".tar.gz"): - with tarfile.open(archive_path, "r:gz") as tar: - try: - tar.extractall(extract_dir, filter="data") - except TypeError: - tar.extractall(extract_dir) - elif archive_path.suffix == ".zip": - with zipfile.ZipFile(archive_path) as zip_file: - zip_file.extractall(extract_dir) - else: - raise RuntimeSetupError(f"Unsupported release archive format: {archive_path.name}") - - binary_name = runtime_binary_name() - archive_stem = archive_path.name.removesuffix(".tar.gz").removesuffix(".zip") - candidates = [ - path - for path in extract_dir.rglob("*") - if path.is_file() - and ( - path.name == binary_name - or path.name == archive_stem - or path.name.startswith("codex-") - ) - ] - if not candidates: - raise RuntimeSetupError( - f"Failed to find {binary_name} in extracted runtime archive {archive_path.name}." - ) - return candidates[0] - - -def _stage_runtime_package( - sdk_python_dir: Path, - runtime_version: str, - runtime_binary: Path, - staging_dir: Path, -) -> Path: - script_module = _load_update_script_module(sdk_python_dir) - return script_module.stage_python_runtime_package( # type: ignore[no-any-return] - staging_dir, - runtime_version, - runtime_binary.resolve(), - ) - - -def _install_runtime_package( - python_executable: str | Path, - staged_runtime_dir: Path, - install_target: Path | None, -) -> None: - args = [ - str(python_executable), - "-m", - "pip", - "install", - "--force-reinstall", - "--no-deps", - ] - if install_target is not None: - install_target.mkdir(parents=True, exist_ok=True) - args.extend(["--target", str(install_target)]) - args.append(str(staged_runtime_dir)) - try: - subprocess.run( - args, - check=True, - text=True, - capture_output=True, - ) - except subprocess.CalledProcessError as exc: - raise RuntimeSetupError( - f"Failed to install {PACKAGE_NAME} into {python_executable} from {staged_runtime_dir}.\n" - f"STDOUT:\n{exc.stdout}\nSTDERR:\n{exc.stderr}" - ) from exc - - -def _load_update_script_module(sdk_python_dir: Path): - script_path = sdk_python_dir / "scripts" / "update_sdk_artifacts.py" - spec = importlib.util.spec_from_file_location("update_sdk_artifacts", script_path) - if spec is None or spec.loader is None: - raise RuntimeSetupError(f"Failed to load {script_path}") - module = importlib.util.module_from_spec(spec) - sys.modules[spec.name] = module - spec.loader.exec_module(module) - return module - - -def _github_api_headers(accept: str) -> dict[str, str]: - headers = { - "Accept": accept, - "User-Agent": "codex-python-runtime-setup", - } - token = _github_token() - if token is not None: - headers["Authorization"] = f"Bearer {token}" - return headers - - -def _github_token() -> str | None: - for env_name in ("GH_TOKEN", "GITHUB_TOKEN"): - token = os.environ.get(env_name) - if token: - return token - return None - - -def _normalized_package_version(version: str) -> str: - return version.strip().replace("-alpha.", "a").replace("-beta.", "b") - - -__all__ = [ - "PACKAGE_NAME", - "PINNED_RUNTIME_VERSION", - "RuntimeSetupError", - "ensure_runtime_package_installed", - "pinned_runtime_version", - "platform_asset_name", -] diff --git a/vendor/codex/sdk/python/docs/api-reference.md b/vendor/codex/sdk/python/docs/api-reference.md deleted file mode 100644 index ddeaf39c..00000000 --- a/vendor/codex/sdk/python/docs/api-reference.md +++ /dev/null @@ -1,207 +0,0 @@ -# Codex App Server SDK — API Reference - -Public surface of `codex_app_server` for app-server v2. - -This SDK surface is experimental. The current implementation intentionally allows only one active turn consumer (`Thread.run()`, `TurnHandle.stream()`, or `TurnHandle.run()`) per client instance at a time. - -## Package Entry - -```python -from codex_app_server import ( - Codex, - AsyncCodex, - RunResult, - Thread, - AsyncThread, - TurnHandle, - AsyncTurnHandle, - InitializeResponse, - Input, - InputItem, - TextInput, - ImageInput, - LocalImageInput, - SkillInput, - MentionInput, - TurnStatus, -) -from codex_app_server.generated.v2_all import ThreadItem, ThreadTokenUsage -``` - -- Version: `codex_app_server.__version__` -- Requires Python >= 3.10 -- Canonical generated app-server models live in `codex_app_server.generated.v2_all` - -## Codex (sync) - -```python -Codex(config: AppServerConfig | None = None) -``` - -Properties/methods: - -- `metadata -> InitializeResponse` -- `close() -> None` -- `thread_start(*, approval_policy=None, base_instructions=None, config=None, cwd=None, developer_instructions=None, ephemeral=None, model=None, model_provider=None, personality=None, sandbox=None) -> Thread` -- `thread_list(*, archived=None, cursor=None, cwd=None, limit=None, model_providers=None, sort_key=None, source_kinds=None) -> ThreadListResponse` -- `thread_resume(thread_id: str, *, approval_policy=None, base_instructions=None, config=None, cwd=None, developer_instructions=None, model=None, model_provider=None, personality=None, sandbox=None) -> Thread` -- `thread_fork(thread_id: str, *, approval_policy=None, base_instructions=None, config=None, cwd=None, developer_instructions=None, model=None, model_provider=None, sandbox=None) -> Thread` -- `thread_archive(thread_id: str) -> ThreadArchiveResponse` -- `thread_unarchive(thread_id: str) -> Thread` -- `models(*, include_hidden: bool = False) -> ModelListResponse` - -Context manager: - -```python -with Codex() as codex: - ... -``` - -## AsyncCodex (async parity) - -```python -AsyncCodex(config: AppServerConfig | None = None) -``` - -Preferred usage: - -```python -async with AsyncCodex() as codex: - ... -``` - -`AsyncCodex` initializes lazily. Context entry is the standard path because it -ensures startup and shutdown are paired explicitly. - -Properties/methods: - -- `metadata -> InitializeResponse` -- `close() -> Awaitable[None]` -- `thread_start(*, approval_policy=None, base_instructions=None, config=None, cwd=None, developer_instructions=None, ephemeral=None, model=None, model_provider=None, personality=None, sandbox=None) -> Awaitable[AsyncThread]` -- `thread_list(*, archived=None, cursor=None, cwd=None, limit=None, model_providers=None, sort_key=None, source_kinds=None) -> Awaitable[ThreadListResponse]` -- `thread_resume(thread_id: str, *, approval_policy=None, base_instructions=None, config=None, cwd=None, developer_instructions=None, model=None, model_provider=None, personality=None, sandbox=None) -> Awaitable[AsyncThread]` -- `thread_fork(thread_id: str, *, approval_policy=None, base_instructions=None, config=None, cwd=None, developer_instructions=None, ephemeral=None, model=None, model_provider=None, sandbox=None) -> Awaitable[AsyncThread]` -- `thread_archive(thread_id: str) -> Awaitable[ThreadArchiveResponse]` -- `thread_unarchive(thread_id: str) -> Awaitable[AsyncThread]` -- `models(*, include_hidden: bool = False) -> Awaitable[ModelListResponse]` - -Async context manager: - -```python -async with AsyncCodex() as codex: - ... -``` - -## Thread / AsyncThread - -`Thread` and `AsyncThread` share the same shape and intent. - -### Thread - -- `run(input: str | Input, *, approval_policy=None, approvals_reviewer=None, cwd=None, effort=None, model=None, output_schema=None, personality=None, sandbox_policy=None, service_tier=None, summary=None) -> RunResult` -- `turn(input: Input, *, approval_policy=None, cwd=None, effort=None, model=None, output_schema=None, personality=None, sandbox_policy=None, summary=None) -> TurnHandle` -- `read(*, include_turns: bool = False) -> ThreadReadResponse` -- `set_name(name: str) -> ThreadSetNameResponse` -- `compact() -> ThreadCompactStartResponse` - -### AsyncThread - -- `run(input: str | Input, *, approval_policy=None, approvals_reviewer=None, cwd=None, effort=None, model=None, output_schema=None, personality=None, sandbox_policy=None, service_tier=None, summary=None) -> Awaitable[RunResult]` -- `turn(input: Input, *, approval_policy=None, cwd=None, effort=None, model=None, output_schema=None, personality=None, sandbox_policy=None, summary=None) -> Awaitable[AsyncTurnHandle]` -- `read(*, include_turns: bool = False) -> Awaitable[ThreadReadResponse]` -- `set_name(name: str) -> Awaitable[ThreadSetNameResponse]` -- `compact() -> Awaitable[ThreadCompactStartResponse]` - -`run(...)` is the common-case convenience path. It accepts plain strings, starts -the turn, consumes notifications until completion, and returns a small result -object with: - -- `final_response: str | None` -- `items: list[ThreadItem]` -- `usage: ThreadTokenUsage | None` - -`final_response` is `None` when the turn finishes without a final-answer or -phase-less assistant message item. - -Use `turn(...)` when you need low-level turn control (`stream()`, `steer()`, -`interrupt()`) or the canonical generated `Turn` from `TurnHandle.run()`. - -## TurnHandle / AsyncTurnHandle - -### TurnHandle - -- `steer(input: Input) -> TurnSteerResponse` -- `interrupt() -> TurnInterruptResponse` -- `stream() -> Iterator[Notification]` -- `run() -> codex_app_server.generated.v2_all.Turn` - -Behavior notes: - -- `stream()` and `run()` are exclusive per client instance in the current experimental build -- starting a second turn consumer on the same `Codex` instance raises `RuntimeError` - -### AsyncTurnHandle - -- `steer(input: Input) -> Awaitable[TurnSteerResponse]` -- `interrupt() -> Awaitable[TurnInterruptResponse]` -- `stream() -> AsyncIterator[Notification]` -- `run() -> Awaitable[codex_app_server.generated.v2_all.Turn]` - -Behavior notes: - -- `stream()` and `run()` are exclusive per client instance in the current experimental build -- starting a second turn consumer on the same `AsyncCodex` instance raises `RuntimeError` - -## Inputs - -```python -@dataclass class TextInput: text: str -@dataclass class ImageInput: url: str -@dataclass class LocalImageInput: path: str -@dataclass class SkillInput: name: str; path: str -@dataclass class MentionInput: name: str; path: str - -InputItem = TextInput | ImageInput | LocalImageInput | SkillInput | MentionInput -Input = list[InputItem] | InputItem -``` - -## Generated Models - -The SDK wrappers return and accept canonical generated app-server models wherever possible: - -```python -from codex_app_server.generated.v2_all import ( - AskForApproval, - ThreadReadResponse, - Turn, - TurnStartParams, - TurnStatus, -) -``` - -## Retry + errors - -```python -from codex_app_server import ( - retry_on_overload, - JsonRpcError, - MethodNotFoundError, - InvalidParamsError, - ServerBusyError, - is_retryable_error, -) -``` - -- `retry_on_overload(...)` retries transient overload errors with exponential backoff + jitter. -- `is_retryable_error(exc)` checks if an exception is transient/overload-like. - -## Example - -```python -from codex_app_server import Codex - -with Codex() as codex: - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - result = thread.run("Say hello in one sentence.") - print(result.final_response) -``` diff --git a/vendor/codex/sdk/python/docs/faq.md b/vendor/codex/sdk/python/docs/faq.md deleted file mode 100644 index af688a3a..00000000 --- a/vendor/codex/sdk/python/docs/faq.md +++ /dev/null @@ -1,98 +0,0 @@ -# FAQ - -## Thread vs turn - -- A `Thread` is conversation state. -- A `Turn` is one model execution inside that thread. -- Multi-turn chat means multiple turns on the same `Thread`. - -## `run()` vs `stream()` - -- `TurnHandle.run()` / `AsyncTurnHandle.run()` is the easiest path. It consumes events until completion and returns the canonical generated app-server `Turn` model. -- `TurnHandle.stream()` / `AsyncTurnHandle.stream()` yields raw notifications (`Notification`) so you can react event-by-event. - -Choose `run()` for most apps. Choose `stream()` for progress UIs, custom timeout logic, or custom parsing. - -## Sync vs async clients - -- `Codex` is the sync public API. -- `AsyncCodex` is an async replica of the same public API shape. -- Prefer `async with AsyncCodex()` for async code. It is the standard path for - explicit startup/shutdown, and `AsyncCodex` initializes lazily on context - entry or first awaited API use. - -If your app is not already async, stay with `Codex`. - -## Public kwargs are snake_case - -Public API keyword names are snake_case. The SDK still maps them to wire camelCase under the hood. - -If you are migrating older code, update these names: - -- `approvalPolicy` -> `approval_policy` -- `baseInstructions` -> `base_instructions` -- `developerInstructions` -> `developer_instructions` -- `modelProvider` -> `model_provider` -- `modelProviders` -> `model_providers` -- `sortKey` -> `sort_key` -- `sourceKinds` -> `source_kinds` -- `outputSchema` -> `output_schema` -- `sandboxPolicy` -> `sandbox_policy` - -## Why only `thread_start(...)` and `thread_resume(...)`? - -The public API keeps only explicit lifecycle calls: - -- `thread_start(...)` to create new threads -- `thread_resume(thread_id, ...)` to continue existing threads - -This avoids duplicate ways to do the same operation and keeps behavior explicit. - -## Why does constructor fail? - -`Codex()` is eager: it starts transport and calls `initialize` in `__init__`. - -Common causes: - -- published runtime package (`openai-codex-cli-bin`) is not installed -- local `codex_bin` override points to a missing file -- local auth/session is missing -- incompatible/old app-server - -Maintainers stage releases by building the SDK once and the runtime once per -platform with the same pinned runtime version. Publish `openai-codex-cli-bin` as -platform wheels only; do not publish an sdist: - -```bash -cd sdk/python -python scripts/update_sdk_artifacts.py generate-types -python scripts/update_sdk_artifacts.py \ - stage-sdk \ - /tmp/codex-python-release/codex-app-server-sdk \ - --runtime-version 1.2.3 -python scripts/update_sdk_artifacts.py \ - stage-runtime \ - /tmp/codex-python-release/openai-codex-cli-bin \ - /path/to/codex \ - --runtime-version 1.2.3 -``` - -## Why does a turn "hang"? - -A turn is complete only when `turn/completed` arrives for that turn ID. - -- `run()` waits for this automatically. -- With `stream()`, keep consuming notifications until completion. - -## How do I retry safely? - -Use `retry_on_overload(...)` for transient overload failures (`ServerBusyError`). - -Do not blindly retry all errors. For `InvalidParamsError` or `MethodNotFoundError`, fix inputs/version compatibility instead. - -## Common pitfalls - -- Starting a new thread for every prompt when you wanted continuity. -- Forgetting to `close()` (or not using context managers). -- Assuming `run()` returns extra SDK-only fields instead of the generated `Turn` model. -- Mixing SDK input classes with raw dicts incorrectly. diff --git a/vendor/codex/sdk/python/docs/getting-started.md b/vendor/codex/sdk/python/docs/getting-started.md deleted file mode 100644 index 70a193a3..00000000 --- a/vendor/codex/sdk/python/docs/getting-started.md +++ /dev/null @@ -1,108 +0,0 @@ -# Getting Started - -This is the fastest path from install to a multi-turn thread using the public SDK surface. - -The SDK is experimental. Treat the API, bundled runtime strategy, and packaging details as unstable until the first public release. - -## 1) Install - -From repo root: - -```bash -cd sdk/python -python -m pip install -e . -``` - -Requirements: - -- Python `>=3.10` -- installed `openai-codex-cli-bin` runtime package, or an explicit `codex_bin` override -- local Codex auth/session configured - -## 2) Run your first turn (sync) - -```python -from codex_app_server import Codex - -with Codex() as codex: - server = codex.metadata.serverInfo - print("Server:", None if server is None else server.name, None if server is None else server.version) - - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - result = thread.run("Say hello in one sentence.") - - print("Thread:", thread.id) - print("Text:", result.final_response) - print("Items:", len(result.items)) -``` - -What happened: - -- `Codex()` started and initialized `codex app-server`. -- `thread_start(...)` created a thread. -- `thread.run("...")` started a turn, consumed events until completion, and returned the final assistant response plus collected items and usage. -- `result.final_response` is `None` when no final-answer or phase-less assistant message item completes for the turn. -- use `thread.turn(...)` when you need a `TurnHandle` for streaming, steering, interrupting, or turn IDs/status -- one client can have only one active turn consumer (`thread.run(...)`, `TurnHandle.stream()`, or `TurnHandle.run()`) at a time in the current experimental build - -## 3) Continue the same thread (multi-turn) - -```python -from codex_app_server import Codex - -with Codex() as codex: - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - - first = thread.run("Summarize Rust ownership in 2 bullets.") - second = thread.run("Now explain it to a Python developer.") - - print("first:", first.final_response) - print("second:", second.final_response) -``` - -## 4) Async parity - -Use `async with AsyncCodex()` as the normal async entrypoint. `AsyncCodex` -initializes lazily, and context entry makes startup/shutdown explicit. - -```python -import asyncio -from codex_app_server import AsyncCodex - - -async def main() -> None: - async with AsyncCodex() as codex: - thread = await codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - result = await thread.run("Continue where we left off.") - print(result.final_response) - - -asyncio.run(main()) -``` - -## 5) Resume an existing thread - -```python -from codex_app_server import Codex - -THREAD_ID = "thr_123" # replace with a real id - -with Codex() as codex: - thread = codex.thread_resume(THREAD_ID) - result = thread.run("Continue where we left off.") - print(result.final_response) -``` - -## 6) Generated models - -The convenience wrappers live at the package root, but the canonical app-server models live under: - -```python -from codex_app_server.generated.v2_all import Turn, TurnStatus, ThreadReadResponse -``` - -## 7) Next stops - -- API surface and signatures: `docs/api-reference.md` -- Common decisions/pitfalls: `docs/faq.md` -- End-to-end runnable examples: `examples/README.md` diff --git a/vendor/codex/sdk/python/examples/01_quickstart_constructor/async.py b/vendor/codex/sdk/python/examples/01_quickstart_constructor/async.py deleted file mode 100644 index b9eedb76..00000000 --- a/vendor/codex/sdk/python/examples/01_quickstart_constructor/async.py +++ /dev/null @@ -1,32 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - ensure_local_sdk_src, - runtime_config, - server_label, -) - -ensure_local_sdk_src() - -import asyncio - -from codex_app_server import AsyncCodex - - -async def main() -> None: - async with AsyncCodex(config=runtime_config()) as codex: - print("Server:", server_label(codex.metadata)) - - thread = await codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - result = await thread.run("Say hello in one sentence.") - print("Items:", len(result.items)) - print("Text:", result.final_response) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/vendor/codex/sdk/python/examples/01_quickstart_constructor/sync.py b/vendor/codex/sdk/python/examples/01_quickstart_constructor/sync.py deleted file mode 100644 index 6970d5a2..00000000 --- a/vendor/codex/sdk/python/examples/01_quickstart_constructor/sync.py +++ /dev/null @@ -1,24 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - ensure_local_sdk_src, - runtime_config, - server_label, -) - -ensure_local_sdk_src() - -from codex_app_server import Codex - -with Codex(config=runtime_config()) as codex: - print("Server:", server_label(codex.metadata)) - - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - result = thread.run("Say hello in one sentence.") - print("Items:", len(result.items)) - print("Text:", result.final_response) diff --git a/vendor/codex/sdk/python/examples/02_turn_run/async.py b/vendor/codex/sdk/python/examples/02_turn_run/async.py deleted file mode 100644 index de681a82..00000000 --- a/vendor/codex/sdk/python/examples/02_turn_run/async.py +++ /dev/null @@ -1,43 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - find_turn_by_id, - runtime_config, -) - -ensure_local_sdk_src() - -import asyncio - -from codex_app_server import AsyncCodex, TextInput - - -async def main() -> None: - async with AsyncCodex(config=runtime_config()) as codex: - thread = await codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - turn = await thread.turn(TextInput("Give 3 bullets about SIMD.")) - result = await turn.run() - persisted = await thread.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, result.id) - - print("thread_id:", thread.id) - print("turn_id:", result.id) - print("status:", result.status) - if result.error is not None: - print("error:", result.error) - print("text:", assistant_text_from_turn(persisted_turn)) - print( - "persisted.items.count:", - 0 if persisted_turn is None else len(persisted_turn.items or []), - ) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/vendor/codex/sdk/python/examples/02_turn_run/sync.py b/vendor/codex/sdk/python/examples/02_turn_run/sync.py deleted file mode 100644 index 823ffb7f..00000000 --- a/vendor/codex/sdk/python/examples/02_turn_run/sync.py +++ /dev/null @@ -1,34 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - find_turn_by_id, - runtime_config, -) - -ensure_local_sdk_src() - -from codex_app_server import Codex, TextInput - -with Codex(config=runtime_config()) as codex: - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - result = thread.turn(TextInput("Give 3 bullets about SIMD.")).run() - persisted = thread.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, result.id) - - print("thread_id:", thread.id) - print("turn_id:", result.id) - print("status:", result.status) - if result.error is not None: - print("error:", result.error) - print("text:", assistant_text_from_turn(persisted_turn)) - print( - "persisted.items.count:", - 0 if persisted_turn is None else len(persisted_turn.items or []), - ) diff --git a/vendor/codex/sdk/python/examples/03_turn_stream_events/async.py b/vendor/codex/sdk/python/examples/03_turn_stream_events/async.py deleted file mode 100644 index 33509ffe..00000000 --- a/vendor/codex/sdk/python/examples/03_turn_stream_events/async.py +++ /dev/null @@ -1,63 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - find_turn_by_id, - runtime_config, -) - -ensure_local_sdk_src() - -import asyncio - -from codex_app_server import AsyncCodex, TextInput - - -async def main() -> None: - async with AsyncCodex(config=runtime_config()) as codex: - thread = await codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - turn = await thread.turn(TextInput("Explain SIMD in 3 short bullets.")) - - event_count = 0 - saw_started = False - saw_delta = False - completed_status = "unknown" - - async for event in turn.stream(): - event_count += 1 - if event.method == "turn/started": - saw_started = True - print("stream.started") - continue - if event.method == "item/agentMessage/delta": - delta = getattr(event.payload, "delta", "") - if delta: - if not saw_delta: - print("assistant> ", end="", flush=True) - print(delta, end="", flush=True) - saw_delta = True - continue - if event.method == "turn/completed": - completed_status = getattr(event.payload.turn.status, "value", str(event.payload.turn.status)) - - if saw_delta: - print() - else: - persisted = await thread.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, turn.id) - final_text = assistant_text_from_turn(persisted_turn).strip() or "[no assistant text]" - print("assistant>", final_text) - - print("stream.started.seen:", saw_started) - print("stream.completed:", completed_status) - print("events.count:", event_count) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/vendor/codex/sdk/python/examples/03_turn_stream_events/sync.py b/vendor/codex/sdk/python/examples/03_turn_stream_events/sync.py deleted file mode 100644 index d458e171..00000000 --- a/vendor/codex/sdk/python/examples/03_turn_stream_events/sync.py +++ /dev/null @@ -1,55 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - find_turn_by_id, - runtime_config, -) - -ensure_local_sdk_src() - -from codex_app_server import Codex, TextInput - -with Codex(config=runtime_config()) as codex: - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - turn = thread.turn(TextInput("Explain SIMD in 3 short bullets.")) - - event_count = 0 - saw_started = False - saw_delta = False - completed_status = "unknown" - - for event in turn.stream(): - event_count += 1 - if event.method == "turn/started": - saw_started = True - print("stream.started") - continue - if event.method == "item/agentMessage/delta": - delta = getattr(event.payload, "delta", "") - if delta: - if not saw_delta: - print("assistant> ", end="", flush=True) - print(delta, end="", flush=True) - saw_delta = True - continue - if event.method == "turn/completed": - completed_status = getattr(event.payload.turn.status, "value", str(event.payload.turn.status)) - - if saw_delta: - print() - else: - persisted = thread.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, turn.id) - final_text = assistant_text_from_turn(persisted_turn).strip() or "[no assistant text]" - print("assistant>", final_text) - - print("stream.started.seen:", saw_started) - print("stream.completed:", completed_status) - print("events.count:", event_count) diff --git a/vendor/codex/sdk/python/examples/04_models_and_metadata/async.py b/vendor/codex/sdk/python/examples/04_models_and_metadata/async.py deleted file mode 100644 index e434b432..00000000 --- a/vendor/codex/sdk/python/examples/04_models_and_metadata/async.py +++ /dev/null @@ -1,26 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ensure_local_sdk_src, runtime_config, server_label - -ensure_local_sdk_src() - -import asyncio - -from codex_app_server import AsyncCodex - - -async def main() -> None: - async with AsyncCodex(config=runtime_config()) as codex: - print("server:", server_label(codex.metadata)) - models = await codex.models() - print("models.count:", len(models.data)) - print("models:", ", ".join(model.id for model in models.data[:5]) or "[none]") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/vendor/codex/sdk/python/examples/04_models_and_metadata/sync.py b/vendor/codex/sdk/python/examples/04_models_and_metadata/sync.py deleted file mode 100644 index 66c33548..00000000 --- a/vendor/codex/sdk/python/examples/04_models_and_metadata/sync.py +++ /dev/null @@ -1,18 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ensure_local_sdk_src, runtime_config, server_label - -ensure_local_sdk_src() - -from codex_app_server import Codex - -with Codex(config=runtime_config()) as codex: - print("server:", server_label(codex.metadata)) - models = codex.models() - print("models.count:", len(models.data)) - print("models:", ", ".join(model.id for model in models.data[:5]) or "[none]") diff --git a/vendor/codex/sdk/python/examples/05_existing_thread/async.py b/vendor/codex/sdk/python/examples/05_existing_thread/async.py deleted file mode 100644 index 8ce2a1af..00000000 --- a/vendor/codex/sdk/python/examples/05_existing_thread/async.py +++ /dev/null @@ -1,34 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import assistant_text_from_turn, ensure_local_sdk_src, find_turn_by_id, runtime_config - -ensure_local_sdk_src() - -import asyncio - -from codex_app_server import AsyncCodex, TextInput - - -async def main() -> None: - async with AsyncCodex(config=runtime_config()) as codex: - original = await codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - - first_turn = await original.turn(TextInput("Tell me one fact about Saturn.")) - _ = await first_turn.run() - print("Created thread:", original.id) - - resumed = await codex.thread_resume(original.id) - second_turn = await resumed.turn(TextInput("Continue with one more fact.")) - second = await second_turn.run() - persisted = await resumed.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, second.id) - print(assistant_text_from_turn(persisted_turn)) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/vendor/codex/sdk/python/examples/05_existing_thread/sync.py b/vendor/codex/sdk/python/examples/05_existing_thread/sync.py deleted file mode 100644 index f5a0c4ec..00000000 --- a/vendor/codex/sdk/python/examples/05_existing_thread/sync.py +++ /dev/null @@ -1,25 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import assistant_text_from_turn, ensure_local_sdk_src, find_turn_by_id, runtime_config - -ensure_local_sdk_src() - -from codex_app_server import Codex, TextInput - -with Codex(config=runtime_config()) as codex: - # Create an initial thread and turn so we have a real thread to resume. - original = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - first = original.turn(TextInput("Tell me one fact about Saturn.")).run() - print("Created thread:", original.id) - - # Resume the existing thread by ID. - resumed = codex.thread_resume(original.id) - second = resumed.turn(TextInput("Continue with one more fact.")).run() - persisted = resumed.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, second.id) - print(assistant_text_from_turn(persisted_turn)) diff --git a/vendor/codex/sdk/python/examples/06_thread_lifecycle_and_controls/async.py b/vendor/codex/sdk/python/examples/06_thread_lifecycle_and_controls/async.py deleted file mode 100644 index 1600b7b8..00000000 --- a/vendor/codex/sdk/python/examples/06_thread_lifecycle_and_controls/async.py +++ /dev/null @@ -1,70 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ensure_local_sdk_src, runtime_config - -ensure_local_sdk_src() - -import asyncio - -from codex_app_server import AsyncCodex, TextInput - - -async def main() -> None: - async with AsyncCodex(config=runtime_config()) as codex: - thread = await codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - first = await (await thread.turn(TextInput("One sentence about structured planning."))).run() - second = await (await thread.turn(TextInput("Now restate it for a junior engineer."))).run() - - reopened = await codex.thread_resume(thread.id) - listing_active = await codex.thread_list(limit=20, archived=False) - reading = await reopened.read(include_turns=True) - - _ = await reopened.set_name("sdk-lifecycle-demo") - _ = await codex.thread_archive(reopened.id) - listing_archived = await codex.thread_list(limit=20, archived=True) - unarchived = await codex.thread_unarchive(reopened.id) - - resumed_info = "n/a" - try: - resumed = await codex.thread_resume( - unarchived.id, - model="gpt-5.4", - config={"model_reasoning_effort": "high"}, - ) - resumed_result = await (await resumed.turn(TextInput("Continue in one short sentence."))).run() - resumed_info = f"{resumed_result.id} {resumed_result.status}" - except Exception as exc: - resumed_info = f"skipped({type(exc).__name__})" - - forked_info = "n/a" - try: - forked = await codex.thread_fork(unarchived.id, model="gpt-5.4") - forked_result = await (await forked.turn(TextInput("Take a different angle in one short sentence."))).run() - forked_info = f"{forked_result.id} {forked_result.status}" - except Exception as exc: - forked_info = f"skipped({type(exc).__name__})" - - compact_info = "sent" - try: - _ = await unarchived.compact() - except Exception as exc: - compact_info = f"skipped({type(exc).__name__})" - - print("Lifecycle OK:", thread.id) - print("first:", first.id, first.status) - print("second:", second.id, second.status) - print("read.turns:", len(reading.thread.turns or [])) - print("list.active:", len(listing_active.data)) - print("list.archived:", len(listing_archived.data)) - print("resumed:", resumed_info) - print("forked:", forked_info) - print("compact:", compact_info) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/vendor/codex/sdk/python/examples/06_thread_lifecycle_and_controls/sync.py b/vendor/codex/sdk/python/examples/06_thread_lifecycle_and_controls/sync.py deleted file mode 100644 index f485ce3c..00000000 --- a/vendor/codex/sdk/python/examples/06_thread_lifecycle_and_controls/sync.py +++ /dev/null @@ -1,63 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ensure_local_sdk_src, runtime_config - -ensure_local_sdk_src() - -from codex_app_server import Codex, TextInput - - -with Codex(config=runtime_config()) as codex: - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - first = thread.turn(TextInput("One sentence about structured planning.")).run() - second = thread.turn(TextInput("Now restate it for a junior engineer.")).run() - - reopened = codex.thread_resume(thread.id) - listing_active = codex.thread_list(limit=20, archived=False) - reading = reopened.read(include_turns=True) - - _ = reopened.set_name("sdk-lifecycle-demo") - _ = codex.thread_archive(reopened.id) - listing_archived = codex.thread_list(limit=20, archived=True) - unarchived = codex.thread_unarchive(reopened.id) - - resumed_info = "n/a" - try: - resumed = codex.thread_resume( - unarchived.id, - model="gpt-5.4", - config={"model_reasoning_effort": "high"}, - ) - resumed_result = resumed.turn(TextInput("Continue in one short sentence.")).run() - resumed_info = f"{resumed_result.id} {resumed_result.status}" - except Exception as exc: - resumed_info = f"skipped({type(exc).__name__})" - - forked_info = "n/a" - try: - forked = codex.thread_fork(unarchived.id, model="gpt-5.4") - forked_result = forked.turn(TextInput("Take a different angle in one short sentence.")).run() - forked_info = f"{forked_result.id} {forked_result.status}" - except Exception as exc: - forked_info = f"skipped({type(exc).__name__})" - - compact_info = "sent" - try: - _ = unarchived.compact() - except Exception as exc: - compact_info = f"skipped({type(exc).__name__})" - - print("Lifecycle OK:", thread.id) - print("first:", first.id, first.status) - print("second:", second.id, second.status) - print("read.turns:", len(reading.thread.turns or [])) - print("list.active:", len(listing_active.data)) - print("list.archived:", len(listing_archived.data)) - print("resumed:", resumed_info) - print("forked:", forked_info) - print("compact:", compact_info) diff --git a/vendor/codex/sdk/python/examples/07_image_and_text/async.py b/vendor/codex/sdk/python/examples/07_image_and_text/async.py deleted file mode 100644 index 6087222d..00000000 --- a/vendor/codex/sdk/python/examples/07_image_and_text/async.py +++ /dev/null @@ -1,42 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - find_turn_by_id, - runtime_config, -) - -ensure_local_sdk_src() - -import asyncio - -from codex_app_server import AsyncCodex, ImageInput, TextInput - -REMOTE_IMAGE_URL = "https://raw.githubusercontent.com/github/explore/main/topics/python/python.png" - - -async def main() -> None: - async with AsyncCodex(config=runtime_config()) as codex: - thread = await codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - turn = await thread.turn( - [ - TextInput("What is in this image? Give 3 bullets."), - ImageInput(REMOTE_IMAGE_URL), - ] - ) - result = await turn.run() - persisted = await thread.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, result.id) - - print("Status:", result.status) - print(assistant_text_from_turn(persisted_turn)) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/vendor/codex/sdk/python/examples/07_image_and_text/sync.py b/vendor/codex/sdk/python/examples/07_image_and_text/sync.py deleted file mode 100644 index a857fab8..00000000 --- a/vendor/codex/sdk/python/examples/07_image_and_text/sync.py +++ /dev/null @@ -1,33 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - find_turn_by_id, - runtime_config, -) - -ensure_local_sdk_src() - -from codex_app_server import Codex, ImageInput, TextInput - -REMOTE_IMAGE_URL = "https://raw.githubusercontent.com/github/explore/main/topics/python/python.png" - -with Codex(config=runtime_config()) as codex: - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - result = thread.turn( - [ - TextInput("What is in this image? Give 3 bullets."), - ImageInput(REMOTE_IMAGE_URL), - ] - ).run() - persisted = thread.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, result.id) - - print("Status:", result.status) - print(assistant_text_from_turn(persisted_turn)) diff --git a/vendor/codex/sdk/python/examples/08_local_image_and_text/async.py b/vendor/codex/sdk/python/examples/08_local_image_and_text/async.py deleted file mode 100644 index 07f06b31..00000000 --- a/vendor/codex/sdk/python/examples/08_local_image_and_text/async.py +++ /dev/null @@ -1,43 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - find_turn_by_id, - runtime_config, - temporary_sample_image_path, -) - -ensure_local_sdk_src() - -import asyncio - -from codex_app_server import AsyncCodex, LocalImageInput, TextInput - - -async def main() -> None: - with temporary_sample_image_path() as image_path: - async with AsyncCodex(config=runtime_config()) as codex: - thread = await codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - - turn = await thread.turn( - [ - TextInput("Read this generated local image and summarize the colors/layout in 2 bullets."), - LocalImageInput(str(image_path.resolve())), - ] - ) - result = await turn.run() - persisted = await thread.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, result.id) - - print("Status:", result.status) - print(assistant_text_from_turn(persisted_turn)) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/vendor/codex/sdk/python/examples/08_local_image_and_text/sync.py b/vendor/codex/sdk/python/examples/08_local_image_and_text/sync.py deleted file mode 100644 index 883e05a6..00000000 --- a/vendor/codex/sdk/python/examples/08_local_image_and_text/sync.py +++ /dev/null @@ -1,34 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - find_turn_by_id, - runtime_config, - temporary_sample_image_path, -) - -ensure_local_sdk_src() - -from codex_app_server import Codex, LocalImageInput, TextInput - -with temporary_sample_image_path() as image_path: - with Codex(config=runtime_config()) as codex: - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - - result = thread.turn( - [ - TextInput("Read this generated local image and summarize the colors/layout in 2 bullets."), - LocalImageInput(str(image_path.resolve())), - ] - ).run() - persisted = thread.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, result.id) - - print("Status:", result.status) - print(assistant_text_from_turn(persisted_turn)) diff --git a/vendor/codex/sdk/python/examples/09_async_parity/sync.py b/vendor/codex/sdk/python/examples/09_async_parity/sync.py deleted file mode 100644 index 25770729..00000000 --- a/vendor/codex/sdk/python/examples/09_async_parity/sync.py +++ /dev/null @@ -1,31 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - find_turn_by_id, - runtime_config, - server_label, -) - -ensure_local_sdk_src() - -from codex_app_server import Codex, TextInput - -with Codex(config=runtime_config()) as codex: - print("Server:", server_label(codex.metadata)) - - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - turn = thread.turn(TextInput("Say hello in one sentence.")) - result = turn.run() - persisted = thread.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, result.id) - - print("Thread:", thread.id) - print("Turn:", result.id) - print("Text:", assistant_text_from_turn(persisted_turn).strip()) diff --git a/vendor/codex/sdk/python/examples/10_error_handling_and_retry/async.py b/vendor/codex/sdk/python/examples/10_error_handling_and_retry/async.py deleted file mode 100644 index c23ee008..00000000 --- a/vendor/codex/sdk/python/examples/10_error_handling_and_retry/async.py +++ /dev/null @@ -1,98 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - find_turn_by_id, - runtime_config, -) - -ensure_local_sdk_src() - -import asyncio -import random -from collections.abc import Awaitable, Callable -from typing import TypeVar - -from codex_app_server import ( - AsyncCodex, - JsonRpcError, - ServerBusyError, - TextInput, - TurnStatus, - is_retryable_error, -) - -ResultT = TypeVar("ResultT") - - -async def retry_on_overload_async( - op: Callable[[], Awaitable[ResultT]], - *, - max_attempts: int = 3, - initial_delay_s: float = 0.25, - max_delay_s: float = 2.0, - jitter_ratio: float = 0.2, -) -> ResultT: - if max_attempts < 1: - raise ValueError("max_attempts must be >= 1") - - delay = initial_delay_s - attempt = 0 - while True: - attempt += 1 - try: - return await op() - except Exception as exc: # noqa: BLE001 - if attempt >= max_attempts or not is_retryable_error(exc): - raise - jitter = delay * jitter_ratio - sleep_for = min(max_delay_s, delay) + random.uniform(-jitter, jitter) - if sleep_for > 0: - await asyncio.sleep(sleep_for) - delay = min(max_delay_s, delay * 2) - - -async def main() -> None: - async with AsyncCodex(config=runtime_config()) as codex: - thread = await codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - - try: - result = await retry_on_overload_async( - _run_turn(thread, "Summarize retry best practices in 3 bullets."), - max_attempts=3, - initial_delay_s=0.25, - max_delay_s=2.0, - ) - except ServerBusyError as exc: - print("Server overloaded after retries:", exc.message) - print("Text:") - return - except JsonRpcError as exc: - print(f"JSON-RPC error {exc.code}: {exc.message}") - print("Text:") - return - - persisted = await thread.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, result.id) - if result.status == TurnStatus.failed: - print("Turn failed:", result.error) - - print("Text:", assistant_text_from_turn(persisted_turn)) - - -def _run_turn(thread, prompt: str): - async def _inner(): - turn = await thread.turn(TextInput(prompt)) - return await turn.run() - - return _inner - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/vendor/codex/sdk/python/examples/10_error_handling_and_retry/sync.py b/vendor/codex/sdk/python/examples/10_error_handling_and_retry/sync.py deleted file mode 100644 index 585f24a9..00000000 --- a/vendor/codex/sdk/python/examples/10_error_handling_and_retry/sync.py +++ /dev/null @@ -1,47 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - find_turn_by_id, - runtime_config, -) - -ensure_local_sdk_src() - -from codex_app_server import ( - Codex, - JsonRpcError, - ServerBusyError, - TextInput, - TurnStatus, - retry_on_overload, -) - -with Codex(config=runtime_config()) as codex: - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - - try: - result = retry_on_overload( - lambda: thread.turn(TextInput("Summarize retry best practices in 3 bullets.")).run(), - max_attempts=3, - initial_delay_s=0.25, - max_delay_s=2.0, - ) - except ServerBusyError as exc: - print("Server overloaded after retries:", exc.message) - print("Text:") - except JsonRpcError as exc: - print(f"JSON-RPC error {exc.code}: {exc.message}") - print("Text:") - else: - persisted = thread.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, result.id) - if result.status == TurnStatus.failed: - print("Turn failed:", result.error) - print("Text:", assistant_text_from_turn(persisted_turn)) diff --git a/vendor/codex/sdk/python/examples/11_cli_mini_app/async.py b/vendor/codex/sdk/python/examples/11_cli_mini_app/async.py deleted file mode 100644 index 4216cf78..00000000 --- a/vendor/codex/sdk/python/examples/11_cli_mini_app/async.py +++ /dev/null @@ -1,96 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ensure_local_sdk_src, runtime_config - -ensure_local_sdk_src() - -import asyncio - -from codex_app_server import ( - AsyncCodex, - TextInput, - ThreadTokenUsageUpdatedNotification, - TurnCompletedNotification, -) - - -def _status_value(status: object | None) -> str: - return str(getattr(status, "value", status)) - - -def _format_usage(usage: object | None) -> str: - if usage is None: - return "usage> (none)" - - last = getattr(usage, "last", None) - total = getattr(usage, "total", None) - if last is None or total is None: - return f"usage> {usage}" - - return ( - "usage>\n" - f" last: input={last.input_tokens} output={last.output_tokens} reasoning={last.reasoning_output_tokens} total={last.total_tokens} cached={last.cached_input_tokens}\n" - f" total: input={total.input_tokens} output={total.output_tokens} reasoning={total.reasoning_output_tokens} total={total.total_tokens} cached={total.cached_input_tokens}" - ) - - -async def main() -> None: - print("Codex async mini CLI. Type /exit to quit.") - - async with AsyncCodex(config=runtime_config()) as codex: - thread = await codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - print("Thread:", thread.id) - - while True: - try: - user_input = (await asyncio.to_thread(input, "you> ")).strip() - except EOFError: - break - - if not user_input: - continue - if user_input in {"/exit", "/quit"}: - break - - turn = await thread.turn(TextInput(user_input)) - usage = None - status = None - error = None - printed_delta = False - - print("assistant> ", end="", flush=True) - async for event in turn.stream(): - payload = event.payload - if event.method == "item/agentMessage/delta": - delta = getattr(payload, "delta", "") - if delta: - print(delta, end="", flush=True) - printed_delta = True - continue - if isinstance(payload, ThreadTokenUsageUpdatedNotification): - usage = payload.token_usage - continue - if isinstance(payload, TurnCompletedNotification): - status = payload.turn.status - error = payload.turn.error - - if printed_delta: - print() - else: - print("[no text]") - - status_text = _status_value(status) - print(f"assistant.status> {status_text}") - if status_text == "failed": - print("assistant.error>", error) - - print(_format_usage(usage)) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/vendor/codex/sdk/python/examples/11_cli_mini_app/sync.py b/vendor/codex/sdk/python/examples/11_cli_mini_app/sync.py deleted file mode 100644 index e961cfbc..00000000 --- a/vendor/codex/sdk/python/examples/11_cli_mini_app/sync.py +++ /dev/null @@ -1,89 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ensure_local_sdk_src, runtime_config - -ensure_local_sdk_src() - -from codex_app_server import ( - Codex, - TextInput, - ThreadTokenUsageUpdatedNotification, - TurnCompletedNotification, -) - -print("Codex mini CLI. Type /exit to quit.") - - -def _status_value(status: object | None) -> str: - return str(getattr(status, "value", status)) - - -def _format_usage(usage: object | None) -> str: - if usage is None: - return "usage> (none)" - - last = getattr(usage, "last", None) - total = getattr(usage, "total", None) - if last is None or total is None: - return f"usage> {usage}" - - return ( - "usage>\n" - f" last: input={last.input_tokens} output={last.output_tokens} reasoning={last.reasoning_output_tokens} total={last.total_tokens} cached={last.cached_input_tokens}\n" - f" total: input={total.input_tokens} output={total.output_tokens} reasoning={total.reasoning_output_tokens} total={total.total_tokens} cached={total.cached_input_tokens}" - ) - - -with Codex(config=runtime_config()) as codex: - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - print("Thread:", thread.id) - - while True: - try: - user_input = input("you> ").strip() - except EOFError: - break - - if not user_input: - continue - if user_input in {"/exit", "/quit"}: - break - - turn = thread.turn(TextInput(user_input)) - usage = None - status = None - error = None - printed_delta = False - - print("assistant> ", end="", flush=True) - for event in turn.stream(): - payload = event.payload - if event.method == "item/agentMessage/delta": - delta = getattr(payload, "delta", "") - if delta: - print(delta, end="", flush=True) - printed_delta = True - continue - if isinstance(payload, ThreadTokenUsageUpdatedNotification): - usage = payload.token_usage - continue - if isinstance(payload, TurnCompletedNotification): - status = payload.turn.status - error = payload.turn.error - - if printed_delta: - print() - else: - print("[no text]") - - status_text = _status_value(status) - print(f"assistant.status> {status_text}") - if status_text == "failed": - print("assistant.error>", error) - - print(_format_usage(usage)) diff --git a/vendor/codex/sdk/python/examples/12_turn_params_kitchen_sink/async.py b/vendor/codex/sdk/python/examples/12_turn_params_kitchen_sink/async.py deleted file mode 100644 index 88a24535..00000000 --- a/vendor/codex/sdk/python/examples/12_turn_params_kitchen_sink/async.py +++ /dev/null @@ -1,88 +0,0 @@ -import json -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - find_turn_by_id, - runtime_config, -) - -ensure_local_sdk_src() - -import asyncio - -from codex_app_server import ( - AskForApproval, - AsyncCodex, - Personality, - ReasoningSummary, - TextInput, -) - -OUTPUT_SCHEMA = { - "type": "object", - "properties": { - "summary": {"type": "string"}, - "actions": { - "type": "array", - "items": {"type": "string"}, - }, - }, - "required": ["summary", "actions"], - "additionalProperties": False, -} - -SUMMARY = ReasoningSummary.model_validate("concise") - -PROMPT = ( - "Analyze a safe rollout plan for enabling a feature flag in production. " - "Return JSON matching the requested schema." -) -APPROVAL_POLICY = AskForApproval.model_validate("never") - - -async def main() -> None: - async with AsyncCodex(config=runtime_config()) as codex: - thread = await codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - - turn = await thread.turn( - TextInput(PROMPT), - approval_policy=APPROVAL_POLICY, - output_schema=OUTPUT_SCHEMA, - personality=Personality.pragmatic, - summary=SUMMARY, - ) - result = await turn.run() - persisted = await thread.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, result.id) - structured_text = assistant_text_from_turn(persisted_turn).strip() - try: - structured = json.loads(structured_text) - except json.JSONDecodeError as exc: - raise RuntimeError(f"Expected JSON matching OUTPUT_SCHEMA, got: {structured_text!r}") from exc - - summary = structured.get("summary") - actions = structured.get("actions") - if not isinstance(summary, str) or not isinstance(actions, list) or not all( - isinstance(action, str) for action in actions - ): - raise RuntimeError( - f"Expected structured output with string summary/actions, got: {structured!r}" - ) - - print("Status:", result.status) - print("summary:", summary) - print("actions:") - for action in actions: - print("-", action) - print("Items:", 0 if persisted_turn is None else len(persisted_turn.items or [])) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/vendor/codex/sdk/python/examples/12_turn_params_kitchen_sink/sync.py b/vendor/codex/sdk/python/examples/12_turn_params_kitchen_sink/sync.py deleted file mode 100644 index e4095c8e..00000000 --- a/vendor/codex/sdk/python/examples/12_turn_params_kitchen_sink/sync.py +++ /dev/null @@ -1,78 +0,0 @@ -import json -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - find_turn_by_id, - runtime_config, -) - -ensure_local_sdk_src() - -from codex_app_server import ( - AskForApproval, - Codex, - Personality, - ReasoningSummary, - TextInput, -) - -OUTPUT_SCHEMA = { - "type": "object", - "properties": { - "summary": {"type": "string"}, - "actions": { - "type": "array", - "items": {"type": "string"}, - }, - }, - "required": ["summary", "actions"], - "additionalProperties": False, -} - -SUMMARY = ReasoningSummary.model_validate("concise") - -PROMPT = ( - "Analyze a safe rollout plan for enabling a feature flag in production. " - "Return JSON matching the requested schema." -) -APPROVAL_POLICY = AskForApproval.model_validate("never") - -with Codex(config=runtime_config()) as codex: - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - - turn = thread.turn( - TextInput(PROMPT), - approval_policy=APPROVAL_POLICY, - output_schema=OUTPUT_SCHEMA, - personality=Personality.pragmatic, - summary=SUMMARY, - ) - result = turn.run() - persisted = thread.read(include_turns=True) - persisted_turn = find_turn_by_id(persisted.thread.turns, result.id) - structured_text = assistant_text_from_turn(persisted_turn).strip() - try: - structured = json.loads(structured_text) - except json.JSONDecodeError as exc: - raise RuntimeError(f"Expected JSON matching OUTPUT_SCHEMA, got: {structured_text!r}") from exc - - summary = structured.get("summary") - actions = structured.get("actions") - if not isinstance(summary, str) or not isinstance(actions, list) or not all( - isinstance(action, str) for action in actions - ): - raise RuntimeError(f"Expected structured output with string summary/actions, got: {structured!r}") - - print("Status:", result.status) - print("summary:", summary) - print("actions:") - for action in actions: - print("-", action) - print("Items:", 0 if persisted_turn is None else len(persisted_turn.items or [])) diff --git a/vendor/codex/sdk/python/examples/13_model_select_and_turn_params/async.py b/vendor/codex/sdk/python/examples/13_model_select_and_turn_params/async.py deleted file mode 100644 index cbbcff46..00000000 --- a/vendor/codex/sdk/python/examples/13_model_select_and_turn_params/async.py +++ /dev/null @@ -1,125 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import assistant_text_from_turn, ensure_local_sdk_src, find_turn_by_id, runtime_config - -ensure_local_sdk_src() - -import asyncio - -from codex_app_server import ( - AskForApproval, - AsyncCodex, - Personality, - ReasoningEffort, - ReasoningSummary, - SandboxPolicy, - TextInput, -) - -REASONING_RANK = { - "none": 0, - "minimal": 1, - "low": 2, - "medium": 3, - "high": 4, - "xhigh": 5, -} -PREFERRED_MODEL = "gpt-5.4" - - -def _pick_highest_model(models): - visible = [m for m in models if not m.hidden] or models - preferred = next((m for m in visible if m.model == PREFERRED_MODEL or m.id == PREFERRED_MODEL), None) - if preferred is not None: - return preferred - known_names = {m.id for m in visible} | {m.model for m in visible} - top_candidates = [m for m in visible if not (m.upgrade and m.upgrade in known_names)] - pool = top_candidates or visible - return max(pool, key=lambda m: (m.model, m.id)) - - -def _pick_highest_turn_effort(model) -> ReasoningEffort: - if not model.supported_reasoning_efforts: - return ReasoningEffort.medium - - best = max( - model.supported_reasoning_efforts, - key=lambda option: REASONING_RANK.get(option.reasoning_effort.value, -1), - ) - return ReasoningEffort(best.reasoning_effort.value) - - -OUTPUT_SCHEMA = { - "type": "object", - "properties": { - "summary": {"type": "string"}, - "actions": { - "type": "array", - "items": {"type": "string"}, - }, - }, - "required": ["summary", "actions"], - "additionalProperties": False, -} - -SANDBOX_POLICY = SandboxPolicy.model_validate( - { - "type": "readOnly", - "access": {"type": "fullAccess"}, - } -) -APPROVAL_POLICY = AskForApproval.model_validate("never") - - -async def main() -> None: - async with AsyncCodex(config=runtime_config()) as codex: - models = await codex.models(include_hidden=True) - selected_model = _pick_highest_model(models.data) - selected_effort = _pick_highest_turn_effort(selected_model) - - print("selected.model:", selected_model.model) - print("selected.effort:", selected_effort.value) - - thread = await codex.thread_start( - model=selected_model.model, - config={"model_reasoning_effort": selected_effort.value}, - ) - - first_turn = await thread.turn( - TextInput("Give one short sentence about reliable production releases."), - model=selected_model.model, - effort=selected_effort, - ) - first = await first_turn.run() - persisted = await thread.read(include_turns=True) - first_persisted_turn = find_turn_by_id(persisted.thread.turns, first.id) - - print("agent.message:", assistant_text_from_turn(first_persisted_turn)) - print("items:", 0 if first_persisted_turn is None else len(first_persisted_turn.items or [])) - - second_turn = await thread.turn( - TextInput("Return JSON for a safe feature-flag rollout plan."), - approval_policy=APPROVAL_POLICY, - cwd=str(Path.cwd()), - effort=selected_effort, - model=selected_model.model, - output_schema=OUTPUT_SCHEMA, - personality=Personality.pragmatic, - sandbox_policy=SANDBOX_POLICY, - summary=ReasoningSummary.model_validate("concise"), - ) - second = await second_turn.run() - persisted = await thread.read(include_turns=True) - second_persisted_turn = find_turn_by_id(persisted.thread.turns, second.id) - - print("agent.message.params:", assistant_text_from_turn(second_persisted_turn)) - print("items.params:", 0 if second_persisted_turn is None else len(second_persisted_turn.items or [])) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/vendor/codex/sdk/python/examples/13_model_select_and_turn_params/sync.py b/vendor/codex/sdk/python/examples/13_model_select_and_turn_params/sync.py deleted file mode 100644 index e02d99cf..00000000 --- a/vendor/codex/sdk/python/examples/13_model_select_and_turn_params/sync.py +++ /dev/null @@ -1,116 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import assistant_text_from_turn, ensure_local_sdk_src, find_turn_by_id, runtime_config - -ensure_local_sdk_src() - -from codex_app_server import ( - AskForApproval, - Codex, - Personality, - ReasoningEffort, - ReasoningSummary, - SandboxPolicy, - TextInput, -) - -REASONING_RANK = { - "none": 0, - "minimal": 1, - "low": 2, - "medium": 3, - "high": 4, - "xhigh": 5, -} -PREFERRED_MODEL = "gpt-5.4" - - -def _pick_highest_model(models): - visible = [m for m in models if not m.hidden] or models - preferred = next((m for m in visible if m.model == PREFERRED_MODEL or m.id == PREFERRED_MODEL), None) - if preferred is not None: - return preferred - known_names = {m.id for m in visible} | {m.model for m in visible} - top_candidates = [m for m in visible if not (m.upgrade and m.upgrade in known_names)] - pool = top_candidates or visible - return max(pool, key=lambda m: (m.model, m.id)) - - -def _pick_highest_turn_effort(model) -> ReasoningEffort: - if not model.supported_reasoning_efforts: - return ReasoningEffort.medium - - best = max( - model.supported_reasoning_efforts, - key=lambda option: REASONING_RANK.get(option.reasoning_effort.value, -1), - ) - return ReasoningEffort(best.reasoning_effort.value) - - -OUTPUT_SCHEMA = { - "type": "object", - "properties": { - "summary": {"type": "string"}, - "actions": { - "type": "array", - "items": {"type": "string"}, - }, - }, - "required": ["summary", "actions"], - "additionalProperties": False, -} - -SANDBOX_POLICY = SandboxPolicy.model_validate( - { - "type": "readOnly", - "access": {"type": "fullAccess"}, - } -) -APPROVAL_POLICY = AskForApproval.model_validate("never") - - -with Codex(config=runtime_config()) as codex: - models = codex.models(include_hidden=True) - selected_model = _pick_highest_model(models.data) - selected_effort = _pick_highest_turn_effort(selected_model) - - print("selected.model:", selected_model.model) - print("selected.effort:", selected_effort.value) - - thread = codex.thread_start( - model=selected_model.model, - config={"model_reasoning_effort": selected_effort.value}, - ) - - first = thread.turn( - TextInput("Give one short sentence about reliable production releases."), - model=selected_model.model, - effort=selected_effort, - ).run() - persisted = thread.read(include_turns=True) - first_turn = find_turn_by_id(persisted.thread.turns, first.id) - - print("agent.message:", assistant_text_from_turn(first_turn)) - print("items:", 0 if first_turn is None else len(first_turn.items or [])) - - second = thread.turn( - TextInput("Return JSON for a safe feature-flag rollout plan."), - approval_policy=APPROVAL_POLICY, - cwd=str(Path.cwd()), - effort=selected_effort, - model=selected_model.model, - output_schema=OUTPUT_SCHEMA, - personality=Personality.pragmatic, - sandbox_policy=SANDBOX_POLICY, - summary=ReasoningSummary.model_validate("concise"), - ).run() - persisted = thread.read(include_turns=True) - second_turn = find_turn_by_id(persisted.thread.turns, second.id) - - print("agent.message.params:", assistant_text_from_turn(second_turn)) - print("items.params:", 0 if second_turn is None else len(second_turn.items or [])) diff --git a/vendor/codex/sdk/python/examples/14_turn_controls/async.py b/vendor/codex/sdk/python/examples/14_turn_controls/async.py deleted file mode 100644 index e180482e..00000000 --- a/vendor/codex/sdk/python/examples/14_turn_controls/async.py +++ /dev/null @@ -1,71 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - runtime_config, -) - -ensure_local_sdk_src() - -import asyncio - -from codex_app_server import AsyncCodex, TextInput - - -async def main() -> None: - async with AsyncCodex(config=runtime_config()) as codex: - thread = await codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - steer_turn = await thread.turn(TextInput("Count from 1 to 40 with commas, then one summary sentence.")) - steer_result = "sent" - try: - _ = await steer_turn.steer(TextInput("Keep it brief and stop after 10 numbers.")) - except Exception as exc: - steer_result = f"skipped {type(exc).__name__}" - - steer_event_count = 0 - steer_completed_status = "unknown" - steer_completed_turn = None - async for event in steer_turn.stream(): - steer_event_count += 1 - if event.method == "turn/completed": - steer_completed_turn = event.payload.turn - steer_completed_status = getattr(event.payload.turn.status, "value", str(event.payload.turn.status)) - - steer_preview = assistant_text_from_turn(steer_completed_turn).strip() or "[no assistant text]" - - interrupt_turn = await thread.turn(TextInput("Count from 1 to 200 with commas, then one summary sentence.")) - interrupt_result = "sent" - try: - _ = await interrupt_turn.interrupt() - except Exception as exc: - interrupt_result = f"skipped {type(exc).__name__}" - - interrupt_event_count = 0 - interrupt_completed_status = "unknown" - interrupt_completed_turn = None - async for event in interrupt_turn.stream(): - interrupt_event_count += 1 - if event.method == "turn/completed": - interrupt_completed_turn = event.payload.turn - interrupt_completed_status = getattr(event.payload.turn.status, "value", str(event.payload.turn.status)) - - interrupt_preview = assistant_text_from_turn(interrupt_completed_turn).strip() or "[no assistant text]" - - print("steer.result:", steer_result) - print("steer.final.status:", steer_completed_status) - print("steer.events.count:", steer_event_count) - print("steer.assistant.preview:", steer_preview) - print("interrupt.result:", interrupt_result) - print("interrupt.final.status:", interrupt_completed_status) - print("interrupt.events.count:", interrupt_event_count) - print("interrupt.assistant.preview:", interrupt_preview) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/vendor/codex/sdk/python/examples/14_turn_controls/sync.py b/vendor/codex/sdk/python/examples/14_turn_controls/sync.py deleted file mode 100644 index 9e9de4dc..00000000 --- a/vendor/codex/sdk/python/examples/14_turn_controls/sync.py +++ /dev/null @@ -1,63 +0,0 @@ -import sys -from pathlib import Path - -_EXAMPLES_ROOT = Path(__file__).resolve().parents[1] -if str(_EXAMPLES_ROOT) not in sys.path: - sys.path.insert(0, str(_EXAMPLES_ROOT)) - -from _bootstrap import ( - assistant_text_from_turn, - ensure_local_sdk_src, - runtime_config, -) - -ensure_local_sdk_src() - -from codex_app_server import Codex, TextInput - -with Codex(config=runtime_config()) as codex: - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - steer_turn = thread.turn(TextInput("Count from 1 to 40 with commas, then one summary sentence.")) - steer_result = "sent" - try: - _ = steer_turn.steer(TextInput("Keep it brief and stop after 10 numbers.")) - except Exception as exc: - steer_result = f"skipped {type(exc).__name__}" - - steer_event_count = 0 - steer_completed_status = "unknown" - steer_completed_turn = None - for event in steer_turn.stream(): - steer_event_count += 1 - if event.method == "turn/completed": - steer_completed_turn = event.payload.turn - steer_completed_status = getattr(event.payload.turn.status, "value", str(event.payload.turn.status)) - - steer_preview = assistant_text_from_turn(steer_completed_turn).strip() or "[no assistant text]" - - interrupt_turn = thread.turn(TextInput("Count from 1 to 200 with commas, then one summary sentence.")) - interrupt_result = "sent" - try: - _ = interrupt_turn.interrupt() - except Exception as exc: - interrupt_result = f"skipped {type(exc).__name__}" - - interrupt_event_count = 0 - interrupt_completed_status = "unknown" - interrupt_completed_turn = None - for event in interrupt_turn.stream(): - interrupt_event_count += 1 - if event.method == "turn/completed": - interrupt_completed_turn = event.payload.turn - interrupt_completed_status = getattr(event.payload.turn.status, "value", str(event.payload.turn.status)) - - interrupt_preview = assistant_text_from_turn(interrupt_completed_turn).strip() or "[no assistant text]" - - print("steer.result:", steer_result) - print("steer.final.status:", steer_completed_status) - print("steer.events.count:", steer_event_count) - print("steer.assistant.preview:", steer_preview) - print("interrupt.result:", interrupt_result) - print("interrupt.final.status:", interrupt_completed_status) - print("interrupt.events.count:", interrupt_event_count) - print("interrupt.assistant.preview:", interrupt_preview) diff --git a/vendor/codex/sdk/python/examples/README.md b/vendor/codex/sdk/python/examples/README.md deleted file mode 100644 index ffdc8616..00000000 --- a/vendor/codex/sdk/python/examples/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# Python SDK Examples - -Each example folder contains runnable versions: - -- `sync.py` (public sync surface: `Codex`) -- `async.py` (public async surface: `AsyncCodex`) - -All examples intentionally use only public SDK exports from `codex_app_server`. - -## Prerequisites - -- Python `>=3.10` -- Install SDK dependencies for the same Python interpreter you will use to run examples - -Recommended setup (from `sdk/python`): - -```bash -python -m venv .venv -source .venv/bin/activate -python -m pip install -U pip -python -m pip install -e . -``` - -When running examples from this repo checkout, the SDK source uses the local -tree and does not bundle a runtime binary. The helper in `examples/_bootstrap.py` -uses the installed `openai-codex-cli-bin` runtime package. - -If the pinned `openai-codex-cli-bin` runtime is not already installed, the bootstrap -will download the matching GitHub release artifact, stage a temporary local -`openai-codex-cli-bin` package, install it into your active interpreter, and clean up -the temporary files afterward. - -Current pinned runtime version: `0.116.0-alpha.1` - -## Run examples - -From `sdk/python`: - -```bash -python examples//sync.py -python examples//async.py -``` - -The examples bootstrap local imports from `sdk/python/src` automatically, so no -SDK wheel install is required. You only need the Python dependencies for your -active interpreter and an installed `openai-codex-cli-bin` runtime package (either -already present or automatically provisioned by the bootstrap). - -## Recommended first run - -```bash -python examples/01_quickstart_constructor/sync.py -python examples/01_quickstart_constructor/async.py -``` - -## Index - -- `01_quickstart_constructor/` - - first run / sanity check -- `02_turn_run/` - - inspect full turn output fields -- `03_turn_stream_events/` - - stream a turn with a small curated event view -- `04_models_and_metadata/` - - discover visible models for the connected runtime -- `05_existing_thread/` - - resume a real existing thread (created in-script) -- `06_thread_lifecycle_and_controls/` - - thread lifecycle + control calls -- `07_image_and_text/` - - remote image URL + text multimodal turn -- `08_local_image_and_text/` - - local image + text multimodal turn using a generated temporary sample image -- `09_async_parity/` - - parity-style sync flow (see async parity in other examples) -- `10_error_handling_and_retry/` - - overload retry pattern + typed error handling structure -- `11_cli_mini_app/` - - interactive chat loop -- `12_turn_params_kitchen_sink/` - - structured output with a curated advanced `turn(...)` configuration -- `13_model_select_and_turn_params/` - - list models, pick highest model + highest supported reasoning effort, run turns, print message and usage -- `14_turn_controls/` - - separate best-effort `steer()` and `interrupt()` demos with concise summaries diff --git a/vendor/codex/sdk/python/examples/_bootstrap.py b/vendor/codex/sdk/python/examples/_bootstrap.py deleted file mode 100644 index 00cd62a0..00000000 --- a/vendor/codex/sdk/python/examples/_bootstrap.py +++ /dev/null @@ -1,152 +0,0 @@ -from __future__ import annotations - -import contextlib -import importlib.util -import os -import sys -import tempfile -import zlib -from pathlib import Path -from typing import Iterable, Iterator - -_SDK_PYTHON_DIR = Path(__file__).resolve().parents[1] -_SDK_PYTHON_STR = str(_SDK_PYTHON_DIR) -if _SDK_PYTHON_STR not in sys.path: - sys.path.insert(0, _SDK_PYTHON_STR) - -from _runtime_setup import ensure_runtime_package_installed - - -def _ensure_runtime_dependencies(sdk_python_dir: Path) -> None: - if importlib.util.find_spec("pydantic") is not None: - return - - python = sys.executable - raise RuntimeError( - "Missing required dependency: pydantic.\n" - f"Interpreter: {python}\n" - "Install dependencies with the same interpreter used to run this example:\n" - f" {python} -m pip install -e {sdk_python_dir}\n" - "If you installed with `pip` from another Python, reinstall using the command above." - ) - - -def ensure_local_sdk_src() -> Path: - """Add sdk/python/src to sys.path so examples run without installing the package.""" - sdk_python_dir = _SDK_PYTHON_DIR - src_dir = sdk_python_dir / "src" - package_dir = src_dir / "codex_app_server" - if not package_dir.exists(): - raise RuntimeError(f"Could not locate local SDK package at {package_dir}") - - _ensure_runtime_dependencies(sdk_python_dir) - - src_str = str(src_dir) - if src_str not in sys.path: - sys.path.insert(0, src_str) - return src_dir - - -def runtime_config(): - """Return an example-friendly AppServerConfig for repo-source SDK usage.""" - from codex_app_server import AppServerConfig - - ensure_runtime_package_installed(sys.executable, _SDK_PYTHON_DIR) - return AppServerConfig() - - -def _png_chunk(chunk_type: bytes, data: bytes) -> bytes: - import struct - - payload = chunk_type + data - checksum = zlib.crc32(payload) & 0xFFFFFFFF - return struct.pack(">I", len(data)) + payload + struct.pack(">I", checksum) - - -def _generated_sample_png_bytes() -> bytes: - import struct - - width = 96 - height = 96 - top_left = (120, 180, 255) - top_right = (255, 220, 90) - bottom_left = (90, 180, 95) - bottom_right = (180, 85, 85) - - rows = bytearray() - for y in range(height): - rows.append(0) - for x in range(width): - if y < height // 2 and x < width // 2: - color = top_left - elif y < height // 2: - color = top_right - elif x < width // 2: - color = bottom_left - else: - color = bottom_right - rows.extend(color) - - header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) - return ( - b"\x89PNG\r\n\x1a\n" - + _png_chunk(b"IHDR", header) - + _png_chunk(b"IDAT", zlib.compress(bytes(rows))) - + _png_chunk(b"IEND", b"") - ) - - -@contextlib.contextmanager -def temporary_sample_image_path() -> Iterator[Path]: - with tempfile.TemporaryDirectory(prefix="codex-python-example-image-") as temp_root: - image_path = Path(temp_root) / "generated_sample.png" - image_path.write_bytes(_generated_sample_png_bytes()) - yield image_path - - -def server_label(metadata: object) -> str: - server = getattr(metadata, "serverInfo", None) - server_name = ((getattr(server, "name", None) or "") if server is not None else "").strip() - server_version = ((getattr(server, "version", None) or "") if server is not None else "").strip() - if server_name and server_version: - return f"{server_name} {server_version}" - - user_agent = ((getattr(metadata, "userAgent", None) or "") if metadata is not None else "").strip() - return user_agent or "unknown" - - -def find_turn_by_id(turns: Iterable[object] | None, turn_id: str) -> object | None: - for turn in turns or []: - if getattr(turn, "id", None) == turn_id: - return turn - return None - - -def assistant_text_from_turn(turn: object | None) -> str: - if turn is None: - return "" - - chunks: list[str] = [] - for item in getattr(turn, "items", []) or []: - raw_item = item.model_dump(mode="json") if hasattr(item, "model_dump") else item - if not isinstance(raw_item, dict): - continue - - item_type = raw_item.get("type") - if item_type == "agentMessage": - text = raw_item.get("text") - if isinstance(text, str) and text: - chunks.append(text) - continue - - if item_type != "message" or raw_item.get("role") != "assistant": - continue - - for content in raw_item.get("content") or []: - if not isinstance(content, dict) or content.get("type") != "output_text": - continue - text = content.get("text") - if isinstance(text, str) and text: - chunks.append(text) - - return "".join(chunks) diff --git a/vendor/codex/sdk/python/notebooks/sdk_walkthrough.ipynb b/vendor/codex/sdk/python/notebooks/sdk_walkthrough.ipynb deleted file mode 100644 index 951cb24e..00000000 --- a/vendor/codex/sdk/python/notebooks/sdk_walkthrough.ipynb +++ /dev/null @@ -1,587 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Codex Python SDK Walkthrough\n", - "\n", - "Public SDK surface only (`codex_app_server` root exports)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Cell 1: bootstrap local SDK imports + pinned runtime package\n", - "import os\n", - "import sys\n", - "from pathlib import Path\n", - "\n", - "if sys.version_info < (3, 10):\n", - " raise RuntimeError(\n", - " f'Notebook requires Python 3.10+; current interpreter is {sys.version.split()[0]}.'\n", - " )\n", - "\n", - "try:\n", - " _ = os.getcwd()\n", - "except FileNotFoundError:\n", - " os.chdir(str(Path.home()))\n", - "\n", - "\n", - "def _is_sdk_python_dir(path: Path) -> bool:\n", - " return (path / 'pyproject.toml').exists() and (path / 'src' / 'codex_app_server').exists()\n", - "\n", - "\n", - "def _iter_home_fallback_candidates(home: Path):\n", - " # bounded depth scan under home to support launching notebooks from unrelated cwd values\n", - " patterns = ('sdk/python', '*/sdk/python', '*/*/sdk/python', '*/*/*/sdk/python')\n", - " for pattern in patterns:\n", - " yield from home.glob(pattern)\n", - "\n", - "\n", - "def _find_sdk_python_dir(start: Path) -> Path | None:\n", - " checked = set()\n", - "\n", - " def _consider(candidate: Path) -> Path | None:\n", - " resolved = candidate.resolve()\n", - " if resolved in checked:\n", - " return None\n", - " checked.add(resolved)\n", - " if _is_sdk_python_dir(resolved):\n", - " return resolved\n", - " return None\n", - "\n", - " for candidate in [start, *start.parents]:\n", - " found = _consider(candidate)\n", - " if found is not None:\n", - " return found\n", - "\n", - " for candidate in [start / 'sdk' / 'python', *(parent / 'sdk' / 'python' for parent in start.parents)]:\n", - " found = _consider(candidate)\n", - " if found is not None:\n", - " return found\n", - "\n", - " env_dir = os.environ.get('CODEX_PYTHON_SDK_DIR')\n", - " if env_dir:\n", - " found = _consider(Path(env_dir).expanduser())\n", - " if found is not None:\n", - " return found\n", - "\n", - " for entry in sys.path:\n", - " if not entry:\n", - " continue\n", - " entry_path = Path(entry).expanduser()\n", - " for candidate in (entry_path, entry_path / 'sdk' / 'python'):\n", - " found = _consider(candidate)\n", - " if found is not None:\n", - " return found\n", - "\n", - " home = Path.home()\n", - " for candidate in _iter_home_fallback_candidates(home):\n", - " found = _consider(candidate)\n", - " if found is not None:\n", - " return found\n", - "\n", - " return None\n", - "\n", - "\n", - "repo_python_dir = _find_sdk_python_dir(Path.cwd())\n", - "if repo_python_dir is None:\n", - " raise RuntimeError('Could not locate sdk/python. Set CODEX_PYTHON_SDK_DIR to your sdk/python path.')\n", - "\n", - "repo_python_str = str(repo_python_dir)\n", - "if repo_python_str not in sys.path:\n", - " sys.path.insert(0, repo_python_str)\n", - "\n", - "from _runtime_setup import ensure_runtime_package_installed\n", - "\n", - "runtime_version = ensure_runtime_package_installed(\n", - " sys.executable,\n", - " repo_python_dir,\n", - ")\n", - "\n", - "src_dir = repo_python_dir / 'src'\n", - "examples_dir = repo_python_dir / 'examples'\n", - "src_str = str(src_dir)\n", - "examples_str = str(examples_dir)\n", - "if src_str not in sys.path:\n", - " sys.path.insert(0, src_str)\n", - "if examples_str not in sys.path:\n", - " sys.path.insert(0, examples_str)\n", - "\n", - "# Force fresh imports after SDK upgrades in the same notebook kernel.\n", - "for module_name in list(sys.modules):\n", - " if module_name == 'codex_app_server' or module_name.startswith('codex_app_server.'):\n", - " sys.modules.pop(module_name, None)\n", - "\n", - "print('Kernel:', sys.executable)\n", - "print('SDK source:', src_dir)\n", - "print('Runtime package:', runtime_version)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Cell 2: imports (public only)\n", - "from _bootstrap import assistant_text_from_turn, find_turn_by_id, server_label\n", - "from codex_app_server import (\n", - " AsyncCodex,\n", - " Codex,\n", - " ImageInput,\n", - " LocalImageInput,\n", - " TextInput,\n", - " retry_on_overload,\n", - ")\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Cell 3: simple sync conversation\n", - "with Codex() as codex:\n", - " thread = codex.thread_start(model='gpt-5.4', config={'model_reasoning_effort': 'high'})\n", - " turn = thread.turn(TextInput('Explain gradient descent in 3 bullets.'))\n", - " result = turn.run()\n", - " persisted = thread.read(include_turns=True)\n", - " persisted_turn = find_turn_by_id(persisted.thread.turns, result.id)\n", - "\n", - " print('server:', server_label(codex.metadata))\n", - " print('status:', result.status)\n", - " print(assistant_text_from_turn(persisted_turn))\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Cell 4: multi-turn continuity in same thread\n", - "with Codex() as codex:\n", - " thread = codex.thread_start(model='gpt-5.4', config={'model_reasoning_effort': 'high'})\n", - "\n", - " first = thread.turn(TextInput('Give a short summary of transformers.')).run()\n", - " second = thread.turn(TextInput('Now explain that to a high-school student.')).run()\n", - " persisted = thread.read(include_turns=True)\n", - " second_turn = find_turn_by_id(persisted.thread.turns, second.id)\n", - "\n", - " print('first status:', first.status)\n", - " print('second status:', second.status)\n", - " print('second text:', assistant_text_from_turn(second_turn))\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Cell 5: full thread lifecycle and branching (sync)\n", - "with Codex() as codex:\n", - " thread = codex.thread_start(model='gpt-5.4', config={'model_reasoning_effort': 'high'})\n", - " first = thread.turn(TextInput('One sentence about structured planning.')).run()\n", - " second = thread.turn(TextInput('Now restate it for a junior engineer.')).run()\n", - "\n", - " reopened = codex.thread_resume(thread.id)\n", - " listing_active = codex.thread_list(limit=20, archived=False)\n", - " reading = reopened.read(include_turns=True)\n", - "\n", - " _ = reopened.set_name('sdk-lifecycle-demo')\n", - " _ = codex.thread_archive(reopened.id)\n", - " listing_archived = codex.thread_list(limit=20, archived=True)\n", - " unarchived = codex.thread_unarchive(reopened.id)\n", - "\n", - " resumed_info = 'n/a'\n", - " try:\n", - " resumed = codex.thread_resume(\n", - " unarchived.id,\n", - " model='gpt-5.4',\n", - " config={'model_reasoning_effort': 'high'},\n", - " )\n", - " resumed_result = resumed.turn(TextInput('Continue in one short sentence.')).run()\n", - " resumed_info = f'{resumed_result.id} {resumed_result.status}'\n", - " except Exception as e:\n", - " resumed_info = f'skipped({type(e).__name__})'\n", - "\n", - " forked_info = 'n/a'\n", - " try:\n", - " forked = codex.thread_fork(unarchived.id, model='gpt-5.4')\n", - " forked_result = forked.turn(TextInput('Take a different angle in one short sentence.')).run()\n", - " forked_info = f'{forked_result.id} {forked_result.status}'\n", - " except Exception as e:\n", - " forked_info = f'skipped({type(e).__name__})'\n", - "\n", - " compact_info = 'sent'\n", - " try:\n", - " _ = unarchived.compact()\n", - " except Exception as e:\n", - " compact_info = f'skipped({type(e).__name__})'\n", - "\n", - " print('Lifecycle OK:', thread.id)\n", - " print('first:', first.id, first.status)\n", - " print('second:', second.id, second.status)\n", - " print('read.turns:', len(reading.thread.turns or []))\n", - " print('list.active:', len(listing_active.data))\n", - " print('list.archived:', len(listing_archived.data))\n", - " print('resumed:', resumed_info)\n", - " print('forked:', forked_info)\n", - " print('compact:', compact_info)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Cell 5b: one turn with most optional turn params\n", - "from pathlib import Path\n", - "from codex_app_server import (\n", - " AskForApproval,\n", - " Personality,\n", - " ReasoningEffort,\n", - " ReasoningSummary,\n", - " SandboxPolicy,\n", - ")\n", - "\n", - "output_schema = {\n", - " 'type': 'object',\n", - " 'properties': {\n", - " 'summary': {'type': 'string'},\n", - " 'actions': {'type': 'array', 'items': {'type': 'string'}},\n", - " },\n", - " 'required': ['summary', 'actions'],\n", - " 'additionalProperties': False,\n", - "}\n", - "\n", - "sandbox_policy = SandboxPolicy.model_validate({'type': 'readOnly', 'access': {'type': 'fullAccess'}})\n", - "summary = ReasoningSummary.model_validate('concise')\n", - "\n", - "with Codex() as codex:\n", - " thread = codex.thread_start(model='gpt-5.4', config={'model_reasoning_effort': 'high'})\n", - " turn = thread.turn(\n", - " TextInput('Propose a safe production feature-flag rollout. Return JSON matching the schema.'),\n", - " approval_policy=AskForApproval.model_validate('never'),\n", - " cwd=str(Path.cwd()),\n", - " effort=ReasoningEffort.medium,\n", - " model='gpt-5.4',\n", - " output_schema=output_schema,\n", - " personality=Personality.pragmatic,\n", - " sandbox_policy=sandbox_policy,\n", - " summary=summary,\n", - " )\n", - " result = turn.run()\n", - " persisted = thread.read(include_turns=True)\n", - " persisted_turn = find_turn_by_id(persisted.thread.turns, result.id)\n", - "\n", - " print('status:', result.status)\n", - " print(assistant_text_from_turn(persisted_turn))\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Cell 5c: choose highest model + highest supported reasoning, then run turns\n", - "from pathlib import Path\n", - "from codex_app_server import (\n", - " AskForApproval,\n", - " Personality,\n", - " ReasoningEffort,\n", - " ReasoningSummary,\n", - " SandboxPolicy,\n", - ")\n", - "\n", - "reasoning_rank = {\n", - " 'none': 0,\n", - " 'minimal': 1,\n", - " 'low': 2,\n", - " 'medium': 3,\n", - " 'high': 4,\n", - " 'xhigh': 5,\n", - "}\n", - "\n", - "\n", - "def pick_highest_model(models):\n", - " visible = [m for m in models if not m.hidden] or models\n", - " known_names = {m.id for m in visible} | {m.model for m in visible}\n", - " top_candidates = [m for m in visible if not (m.upgrade and m.upgrade in known_names)]\n", - " pool = top_candidates or visible\n", - " return max(pool, key=lambda m: (m.model, m.id))\n", - "\n", - "\n", - "def pick_highest_turn_effort(model) -> ReasoningEffort:\n", - " if not model.supported_reasoning_efforts:\n", - " return ReasoningEffort.medium\n", - " best = max(model.supported_reasoning_efforts, key=lambda opt: reasoning_rank.get(opt.reasoning_effort.value, -1))\n", - " return ReasoningEffort(best.reasoning_effort.value)\n", - "\n", - "\n", - "output_schema = {\n", - " 'type': 'object',\n", - " 'properties': {\n", - " 'summary': {'type': 'string'},\n", - " 'actions': {'type': 'array', 'items': {'type': 'string'}},\n", - " },\n", - " 'required': ['summary', 'actions'],\n", - " 'additionalProperties': False,\n", - "}\n", - "sandbox_policy = SandboxPolicy.model_validate({'type': 'readOnly', 'access': {'type': 'fullAccess'}})\n", - "\n", - "with Codex() as codex:\n", - " models = codex.models(include_hidden=True)\n", - " selected_model = pick_highest_model(models.data)\n", - " selected_effort = pick_highest_turn_effort(selected_model)\n", - "\n", - " print('selected.model:', selected_model.model)\n", - " print('selected.effort:', selected_effort.value)\n", - "\n", - " thread = codex.thread_start(model=selected_model.model, config={'model_reasoning_effort': selected_effort.value})\n", - "\n", - " first = thread.turn(\n", - " TextInput('Give one short sentence about reliable production releases.'),\n", - " model=selected_model.model,\n", - " effort=selected_effort,\n", - " ).run()\n", - " persisted = thread.read(include_turns=True)\n", - " first_turn = find_turn_by_id(persisted.thread.turns, first.id)\n", - " print('agent.message:', assistant_text_from_turn(first_turn))\n", - " print('items:', 0 if first_turn is None else len(first_turn.items or []))\n", - "\n", - " second = thread.turn(\n", - " TextInput('Return JSON for a safe feature-flag rollout plan.'),\n", - " approval_policy=AskForApproval.model_validate('never'),\n", - " cwd=str(Path.cwd()),\n", - " effort=selected_effort,\n", - " model=selected_model.model,\n", - " output_schema=output_schema,\n", - " personality=Personality.pragmatic,\n", - " sandbox_policy=sandbox_policy,\n", - " summary=ReasoningSummary.model_validate('concise'),\n", - " ).run()\n", - " persisted = thread.read(include_turns=True)\n", - " second_turn = find_turn_by_id(persisted.thread.turns, second.id)\n", - " print('agent.message.params:', assistant_text_from_turn(second_turn))\n", - " print('items.params:', 0 if second_turn is None else len(second_turn.items or []))\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Cell 6: multimodal with remote image\n", - "remote_image_url = 'https://raw.githubusercontent.com/github/explore/main/topics/python/python.png'\n", - "\n", - "with Codex() as codex:\n", - " thread = codex.thread_start(model='gpt-5.4', config={'model_reasoning_effort': 'high'})\n", - " result = thread.turn([\n", - " TextInput('What do you see in this image? 3 bullets.'),\n", - " ImageInput(remote_image_url),\n", - " ]).run()\n", - " persisted = thread.read(include_turns=True)\n", - " persisted_turn = find_turn_by_id(persisted.thread.turns, result.id)\n", - "\n", - " print('status:', result.status)\n", - " print(assistant_text_from_turn(persisted_turn))\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Cell 7: multimodal with local image (generated temporary file)\n", - "with temporary_sample_image_path() as local_image_path:\n", - " with Codex() as codex:\n", - " thread = codex.thread_start(model='gpt-5.4', config={'model_reasoning_effort': 'high'})\n", - " result = thread.turn([\n", - " TextInput('Describe the colors and layout in this generated local image in 2 bullets.'),\n", - " LocalImageInput(str(local_image_path.resolve())),\n", - " ]).run()\n", - " persisted = thread.read(include_turns=True)\n", - " persisted_turn = find_turn_by_id(persisted.thread.turns, result.id)\n", - "\n", - " print('status:', result.status)\n", - " print(assistant_text_from_turn(persisted_turn))\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Cell 8: retry-on-overload pattern\n", - "with Codex() as codex:\n", - " thread = codex.thread_start(model='gpt-5.4', config={'model_reasoning_effort': 'high'})\n", - "\n", - " result = retry_on_overload(\n", - " lambda: thread.turn(TextInput('List 5 failure modes in distributed systems.')).run(),\n", - " max_attempts=3,\n", - " initial_delay_s=0.25,\n", - " max_delay_s=2.0,\n", - " )\n", - " persisted = thread.read(include_turns=True)\n", - " persisted_turn = find_turn_by_id(persisted.thread.turns, result.id)\n", - "\n", - " print('status:', result.status)\n", - " print(assistant_text_from_turn(persisted_turn))\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Cell 9: full thread lifecycle and branching (async)\n", - "import asyncio\n", - "\n", - "\n", - "async def async_lifecycle_demo():\n", - " async with AsyncCodex() as codex:\n", - " thread = await codex.thread_start(model='gpt-5.4', config={'model_reasoning_effort': 'high'})\n", - " first = await (await thread.turn(TextInput('One sentence about structured planning.'))).run()\n", - " second = await (await thread.turn(TextInput('Now restate it for a junior engineer.'))).run()\n", - "\n", - " reopened = await codex.thread_resume(thread.id)\n", - " listing_active = await codex.thread_list(limit=20, archived=False)\n", - " reading = await reopened.read(include_turns=True)\n", - "\n", - " _ = await reopened.set_name('sdk-lifecycle-demo')\n", - " _ = await codex.thread_archive(reopened.id)\n", - " listing_archived = await codex.thread_list(limit=20, archived=True)\n", - " unarchived = await codex.thread_unarchive(reopened.id)\n", - "\n", - " resumed_info = 'n/a'\n", - " try:\n", - " resumed = await codex.thread_resume(\n", - " unarchived.id,\n", - " model='gpt-5.4',\n", - " config={'model_reasoning_effort': 'high'},\n", - " )\n", - " resumed_result = await (await resumed.turn(TextInput('Continue in one short sentence.'))).run()\n", - " resumed_info = f'{resumed_result.id} {resumed_result.status}'\n", - " except Exception as e:\n", - " resumed_info = f'skipped({type(e).__name__})'\n", - "\n", - " forked_info = 'n/a'\n", - " try:\n", - " forked = await codex.thread_fork(unarchived.id, model='gpt-5.4')\n", - " forked_result = await (await forked.turn(TextInput('Take a different angle in one short sentence.'))).run()\n", - " forked_info = f'{forked_result.id} {forked_result.status}'\n", - " except Exception as e:\n", - " forked_info = f'skipped({type(e).__name__})'\n", - "\n", - " compact_info = 'sent'\n", - " try:\n", - " _ = await unarchived.compact()\n", - " except Exception as e:\n", - " compact_info = f'skipped({type(e).__name__})'\n", - "\n", - " print('Lifecycle OK:', thread.id)\n", - " print('first:', first.id, first.status)\n", - " print('second:', second.id, second.status)\n", - " print('read.turns:', len(reading.thread.turns or []))\n", - " print('list.active:', len(listing_active.data))\n", - " print('list.archived:', len(listing_archived.data))\n", - " print('resumed:', resumed_info)\n", - " print('forked:', forked_info)\n", - " print('compact:', compact_info)\n", - "\n", - "\n", - "await async_lifecycle_demo()\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Cell 10: async turn controls (best effort steer + interrupt)\n", - "import asyncio\n", - "\n", - "\n", - "async def async_stream_demo():\n", - " async with AsyncCodex() as codex:\n", - " thread = await codex.thread_start(model='gpt-5.4', config={'model_reasoning_effort': 'high'})\n", - " steer_turn = await thread.turn(TextInput('Count from 1 to 40 with commas, then one summary sentence.'))\n", - "\n", - " steer_result = 'sent'\n", - " try:\n", - " _ = await steer_turn.steer(TextInput('Keep it brief and stop after 10 numbers.'))\n", - " except Exception as e:\n", - " steer_result = f'skipped {type(e).__name__}'\n", - "\n", - " steer_event_count = 0\n", - " steer_completed_status = 'unknown'\n", - " steer_completed_turn = None\n", - " async for event in steer_turn.stream():\n", - " steer_event_count += 1\n", - " if event.method == 'turn/completed':\n", - " steer_completed_turn = event.payload.turn\n", - " steer_completed_status = getattr(event.payload.turn.status, 'value', str(event.payload.turn.status))\n", - "\n", - " steer_preview = assistant_text_from_turn(steer_completed_turn).strip() or '[no assistant text]'\n", - "\n", - " interrupt_turn = await thread.turn(TextInput('Count from 1 to 200 with commas, then one summary sentence.'))\n", - " interrupt_result = 'sent'\n", - " try:\n", - " _ = await interrupt_turn.interrupt()\n", - " except Exception as e:\n", - " interrupt_result = f'skipped {type(e).__name__}'\n", - "\n", - " interrupt_event_count = 0\n", - " interrupt_completed_status = 'unknown'\n", - " interrupt_completed_turn = None\n", - " async for event in interrupt_turn.stream():\n", - " interrupt_event_count += 1\n", - " if event.method == 'turn/completed':\n", - " interrupt_completed_turn = event.payload.turn\n", - " interrupt_completed_status = getattr(event.payload.turn.status, 'value', str(event.payload.turn.status))\n", - "\n", - " interrupt_preview = assistant_text_from_turn(interrupt_completed_turn).strip() or '[no assistant text]'\n", - "\n", - " print('steer.result:', steer_result)\n", - " print('steer.final.status:', steer_completed_status)\n", - " print('steer.events.count:', steer_event_count)\n", - " print('steer.assistant.preview:', steer_preview)\n", - " print('interrupt.result:', interrupt_result)\n", - " print('interrupt.final.status:', interrupt_completed_status)\n", - " print('interrupt.events.count:', interrupt_event_count)\n", - " print('interrupt.assistant.preview:', interrupt_preview)\n", - "\n", - "\n", - "await async_stream_demo()\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "name": "python", - "version": "3.10+" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/vendor/codex/sdk/python/pyproject.toml b/vendor/codex/sdk/python/pyproject.toml deleted file mode 100644 index f5129cbf..00000000 --- a/vendor/codex/sdk/python/pyproject.toml +++ /dev/null @@ -1,62 +0,0 @@ -[build-system] -requires = ["hatchling>=1.24.0"] -build-backend = "hatchling.build" - -[project] -name = "codex-app-server-sdk" -version = "0.2.0" -description = "Python SDK for Codex app-server v2" -readme = "README.md" -requires-python = ">=3.10" -license = { text = "Apache-2.0" } -authors = [{ name = "OpenClaw Assistant" }] -keywords = ["codex", "json-rpc", "sdk", "llm", "app-server"] -classifiers = [ - "Development Status :: 4 - Beta", - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Topic :: Software Development :: Libraries :: Python Modules", -] -dependencies = ["pydantic>=2.12"] - -[project.urls] -Homepage = "https://github.com/openai/codex" -Repository = "https://github.com/openai/codex" -Issues = "https://github.com/openai/codex/issues" - -[project.optional-dependencies] -dev = ["pytest>=8.0", "datamodel-code-generator==0.31.2", "ruff>=0.11"] - -[tool.hatch.build] -exclude = [ - ".venv/**", - ".venv2/**", - ".pytest_cache/**", - "dist/**", - "build/**", -] - -[tool.hatch.build.targets.wheel] -packages = ["src/codex_app_server"] -include = [ - "src/codex_app_server/py.typed", -] - -[tool.hatch.build.targets.sdist] -include = [ - "src/codex_app_server/**", - "README.md", - "CHANGELOG.md", - "CONTRIBUTING.md", - "RELEASE_CHECKLIST.md", - "pyproject.toml", -] - -[tool.pytest.ini_options] -addopts = "-q" -testpaths = ["tests"] diff --git a/vendor/codex/sdk/python/scripts/update_sdk_artifacts.py b/vendor/codex/sdk/python/scripts/update_sdk_artifacts.py deleted file mode 100644 index 42c1ec09..00000000 --- a/vendor/codex/sdk/python/scripts/update_sdk_artifacts.py +++ /dev/null @@ -1,1100 +0,0 @@ -#!/usr/bin/env python3 -from __future__ import annotations - -import argparse -import importlib -import json -import platform -import re -import shutil -import stat -import subprocess -import sys -import tempfile -import types -import typing -from dataclasses import dataclass -from pathlib import Path -from typing import Any, Callable, Sequence, get_args, get_origin - -RUNTIME_DISTRIBUTION_NAME = "openai-codex-cli-bin" - - -def repo_root() -> Path: - return Path(__file__).resolve().parents[3] - - -def sdk_root() -> Path: - return repo_root() / "sdk" / "python" - - -def python_runtime_root() -> Path: - return repo_root() / "sdk" / "python-runtime" - - -def schema_bundle_path() -> Path: - return ( - repo_root() - / "codex-rs" - / "app-server-protocol" - / "schema" - / "json" - / "codex_app_server_protocol.v2.schemas.json" - ) - - -def schema_root_dir() -> Path: - return repo_root() / "codex-rs" / "app-server-protocol" / "schema" / "json" - - -def _is_windows() -> bool: - return platform.system().lower().startswith("win") - - -def runtime_binary_name() -> str: - return "codex.exe" if _is_windows() else "codex" - - -def staged_runtime_bin_path(root: Path) -> Path: - return root / "src" / "codex_cli_bin" / "bin" / runtime_binary_name() - - -def run(cmd: list[str], cwd: Path) -> None: - subprocess.run(cmd, cwd=str(cwd), check=True) - - -def run_python_module(module: str, args: list[str], cwd: Path) -> None: - run([sys.executable, "-m", module, *args], cwd) - - -def current_sdk_version() -> str: - match = re.search( - r'^version = "([^"]+)"$', - (sdk_root() / "pyproject.toml").read_text(), - flags=re.MULTILINE, - ) - if match is None: - raise RuntimeError("Could not determine Python SDK version from pyproject.toml") - return match.group(1) - - -def normalize_codex_version(version: str) -> str: - normalized = version.strip() - if normalized.startswith("rust-v"): - normalized = normalized.removeprefix("rust-v") - elif normalized.startswith("v"): - normalized = normalized.removeprefix("v") - - normalized = re.sub(r"-alpha\.?([0-9]+)$", r"a\1", normalized) - normalized = re.sub(r"-beta\.?([0-9]+)$", r"b\1", normalized) - normalized = re.sub(r"-rc\.?([0-9]+)$", r"rc\1", normalized) - - if not re.fullmatch(r"[0-9]+(?:\.[0-9]+)*(?:(?:a|b|rc)[0-9]+)?", normalized): - raise RuntimeError( - f"Could not normalize Codex version {version!r} to a PEP 440 version" - ) - return normalized - - -def _copy_package_tree(src: Path, dst: Path) -> None: - if dst.exists(): - if dst.is_dir(): - shutil.rmtree(dst) - else: - dst.unlink() - shutil.copytree( - src, - dst, - ignore=shutil.ignore_patterns( - ".venv", - ".venv2", - ".pytest_cache", - "__pycache__", - "build", - "dist", - "*.pyc", - ), - ) - - -def _rewrite_project_version(pyproject_text: str, version: str) -> str: - updated, count = re.subn( - r'^version = "[^"]+"$', - f'version = "{version}"', - pyproject_text, - count=1, - flags=re.MULTILINE, - ) - if count != 1: - raise RuntimeError("Could not rewrite project version in pyproject.toml") - return updated - - -def _rewrite_runtime_platform_tag(pyproject_text: str, platform_tag: str) -> str: - section = "[tool.hatch.build.targets.wheel.hooks.custom]" - section_index = pyproject_text.find(section) - if section_index == -1: - raise RuntimeError("Could not find runtime wheel custom hook config") - - next_section_index = pyproject_text.find("\n[", section_index + len(section)) - if next_section_index == -1: - section_text = pyproject_text[section_index:] - tail = "" - else: - section_text = pyproject_text[section_index:next_section_index] - tail = pyproject_text[next_section_index:] - - updated_section, count = re.subn( - r'^platform-tag = "[^"]*"$', - f'platform-tag = "{platform_tag}"', - section_text, - count=1, - flags=re.MULTILINE, - ) - if count == 0: - updated_section = section_text.rstrip() + f'\nplatform-tag = "{platform_tag}"\n' - - return pyproject_text[:section_index] + updated_section + tail - - -def _rewrite_project_name(pyproject_text: str, name: str) -> str: - updated, count = re.subn( - r'^name = "[^"]+"$', - f'name = "{name}"', - pyproject_text, - count=1, - flags=re.MULTILINE, - ) - if count != 1: - raise RuntimeError("Could not rewrite project name in pyproject.toml") - return updated - - -def _rewrite_sdk_runtime_dependency(pyproject_text: str, runtime_version: str) -> str: - match = re.search(r"^dependencies = \[(.*?)\]$", pyproject_text, flags=re.MULTILINE) - if match is None: - raise RuntimeError( - "Could not find dependencies array in sdk/python/pyproject.toml" - ) - - raw_items = [item.strip() for item in match.group(1).split(",") if item.strip()] - raw_items = [item for item in raw_items if "codex-cli-bin" not in item] - raw_items.append(f'"{RUNTIME_DISTRIBUTION_NAME}=={runtime_version}"') - replacement = "dependencies = [\n " + ",\n ".join(raw_items) + ",\n]" - return pyproject_text[: match.start()] + replacement + pyproject_text[match.end() :] - - -def stage_python_sdk_package( - staging_dir: Path, sdk_version: str, runtime_version: str -) -> Path: - _copy_package_tree(sdk_root(), staging_dir) - sdk_bin_dir = staging_dir / "src" / "codex_app_server" / "bin" - if sdk_bin_dir.exists(): - shutil.rmtree(sdk_bin_dir) - - pyproject_path = staging_dir / "pyproject.toml" - pyproject_text = pyproject_path.read_text() - pyproject_text = _rewrite_project_version(pyproject_text, sdk_version) - pyproject_text = _rewrite_sdk_runtime_dependency(pyproject_text, runtime_version) - pyproject_path.write_text(pyproject_text) - return staging_dir - - -def stage_python_runtime_package( - staging_dir: Path, - codex_version: str, - binary_path: Path, - platform_tag: str | None = None, -) -> Path: - package_version = normalize_codex_version(codex_version) - _copy_package_tree(python_runtime_root(), staging_dir) - - pyproject_path = staging_dir / "pyproject.toml" - pyproject_text = pyproject_path.read_text() - pyproject_text = _rewrite_project_name(pyproject_text, RUNTIME_DISTRIBUTION_NAME) - pyproject_text = _rewrite_project_version(pyproject_text, package_version) - if platform_tag is not None: - pyproject_text = _rewrite_runtime_platform_tag(pyproject_text, platform_tag) - pyproject_path.write_text(pyproject_text) - - out_bin = staged_runtime_bin_path(staging_dir) - out_bin.parent.mkdir(parents=True, exist_ok=True) - shutil.copy2(binary_path, out_bin) - if not _is_windows(): - out_bin.chmod( - out_bin.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH - ) - return staging_dir - - -def _flatten_string_enum_one_of(definition: dict[str, Any]) -> bool: - branches = definition.get("oneOf") - if not isinstance(branches, list) or not branches: - return False - - enum_values: list[str] = [] - for branch in branches: - if not isinstance(branch, dict): - return False - if branch.get("type") != "string": - return False - - enum = branch.get("enum") - if not isinstance(enum, list) or len(enum) != 1 or not isinstance(enum[0], str): - return False - - extra_keys = set(branch) - {"type", "enum", "description", "title"} - if extra_keys: - return False - - enum_values.append(enum[0]) - - description = definition.get("description") - title = definition.get("title") - definition.clear() - definition["type"] = "string" - definition["enum"] = enum_values - if isinstance(description, str): - definition["description"] = description - if isinstance(title, str): - definition["title"] = title - return True - - -DISCRIMINATOR_KEYS = ("type", "method", "mode", "state", "status", "role", "reason") - - -def _to_pascal_case(value: str) -> str: - parts = re.split(r"[^0-9A-Za-z]+", value) - compact = "".join(part[:1].upper() + part[1:] for part in parts if part) - return compact or "Value" - - -def _string_literal(value: Any) -> str | None: - if not isinstance(value, dict): - return None - const = value.get("const") - if isinstance(const, str): - return const - - enum = value.get("enum") - if isinstance(enum, list) and enum and len(enum) == 1 and isinstance(enum[0], str): - return enum[0] - return None - - -def _enum_literals(value: Any) -> list[str] | None: - if not isinstance(value, dict): - return None - enum = value.get("enum") - if ( - not isinstance(enum, list) - or not enum - or not all(isinstance(item, str) for item in enum) - ): - return None - return list(enum) - - -def _literal_from_property(props: dict[str, Any], key: str) -> str | None: - return _string_literal(props.get(key)) - - -def _variant_definition_name(base: str, variant: dict[str, Any]) -> str | None: - # datamodel-code-generator invents numbered helper names for inline union - # branches unless they carry a stable, unique title up front. We derive - # those titles from the branch discriminator or other identifying shape. - props = variant.get("properties") - if isinstance(props, dict): - for key in DISCRIMINATOR_KEYS: - literal = _literal_from_property(props, key) - if literal is None: - continue - pascal = _to_pascal_case(literal) - if base == "ClientRequest": - return f"{pascal}Request" - if base == "ServerRequest": - return f"{pascal}ServerRequest" - if base == "ClientNotification": - return f"{pascal}ClientNotification" - if base == "ServerNotification": - return f"{pascal}ServerNotification" - if base == "EventMsg": - return f"{pascal}EventMsg" - return f"{pascal}{base}" - - if len(props) == 1: - key = next(iter(props)) - pascal = _string_literal(props[key]) - return f"{_to_pascal_case(pascal or key)}{base}" - - required = variant.get("required") - if ( - isinstance(required, list) - and len(required) == 1 - and isinstance(required[0], str) - ): - return f"{_to_pascal_case(required[0])}{base}" - - enum_literals = _enum_literals(variant) - if enum_literals is not None: - if len(enum_literals) == 1: - return f"{_to_pascal_case(enum_literals[0])}{base}" - return f"{base}Value" - - return None - - -def _variant_collision_key( - base: str, variant: dict[str, Any], generated_name: str -) -> str: - parts = [f"base={base}", f"generated={generated_name}"] - props = variant.get("properties") - if isinstance(props, dict): - for key in DISCRIMINATOR_KEYS: - literal = _literal_from_property(props, key) - if literal is not None: - parts.append(f"{key}={literal}") - if len(props) == 1: - parts.append(f"only_property={next(iter(props))}") - - required = variant.get("required") - if ( - isinstance(required, list) - and len(required) == 1 - and isinstance(required[0], str) - ): - parts.append(f"required_only={required[0]}") - - enum_literals = _enum_literals(variant) - if enum_literals is not None: - parts.append(f"enum={'|'.join(enum_literals)}") - - return "|".join(parts) - - -def _set_discriminator_titles(props: dict[str, Any], owner: str) -> None: - for key in DISCRIMINATOR_KEYS: - prop = props.get(key) - if not isinstance(prop, dict): - continue - if _string_literal(prop) is None or "title" in prop: - continue - prop["title"] = f"{owner}{_to_pascal_case(key)}" - - -def _annotate_variant_list(variants: list[Any], base: str | None) -> None: - seen = { - variant["title"] - for variant in variants - if isinstance(variant, dict) and isinstance(variant.get("title"), str) - } - - for variant in variants: - if not isinstance(variant, dict): - continue - - variant_name = variant.get("title") - generated_name = _variant_definition_name(base, variant) if base else None - if generated_name is not None and ( - not isinstance(variant_name, str) - or "/" in variant_name - or variant_name != generated_name - ): - # Titles like `Thread/startedNotification` sanitize poorly in - # Python, and envelope titles like `ErrorNotification` collide - # with their payload model names. Rewrite them before codegen so - # we get `ThreadStartedServerNotification` instead of `...1`. - if generated_name in seen and variant_name != generated_name: - raise RuntimeError( - "Variant title naming collision detected: " - f"{_variant_collision_key(base or '', variant, generated_name)}" - ) - variant["title"] = generated_name - seen.add(generated_name) - variant_name = generated_name - - if isinstance(variant_name, str): - props = variant.get("properties") - if isinstance(props, dict): - _set_discriminator_titles(props, variant_name) - - _annotate_schema(variant, base) - - -def _annotate_schema(value: Any, base: str | None = None) -> None: - if isinstance(value, list): - for item in value: - _annotate_schema(item, base) - return - - if not isinstance(value, dict): - return - - owner = value.get("title") - props = value.get("properties") - if isinstance(owner, str) and isinstance(props, dict): - _set_discriminator_titles(props, owner) - - one_of = value.get("oneOf") - if isinstance(one_of, list): - # Walk nested unions recursively so every inline branch gets the same - # title normalization treatment before we hand the bundle to Python - # codegen. - _annotate_variant_list(one_of, base) - - any_of = value.get("anyOf") - if isinstance(any_of, list): - _annotate_variant_list(any_of, base) - - definitions = value.get("definitions") - if isinstance(definitions, dict): - for name, schema in definitions.items(): - _annotate_schema(schema, name if isinstance(name, str) else base) - - defs = value.get("$defs") - if isinstance(defs, dict): - for name, schema in defs.items(): - _annotate_schema(schema, name if isinstance(name, str) else base) - - for key, child in value.items(): - if key in {"oneOf", "anyOf", "definitions", "$defs"}: - continue - _annotate_schema(child, base) - - -def _normalized_schema_bundle_text() -> str: - schema = json.loads(schema_bundle_path().read_text()) - definitions = schema.get("definitions", {}) - if isinstance(definitions, dict): - for definition in definitions.values(): - if isinstance(definition, dict): - _flatten_string_enum_one_of(definition) - # Normalize the schema into something datamodel-code-generator can map to - # stable class names instead of anonymous numbered helpers. - _annotate_schema(schema) - return json.dumps(schema, indent=2, sort_keys=True) + "\n" - - -def generate_v2_all() -> None: - out_path = sdk_root() / "src" / "codex_app_server" / "generated" / "v2_all.py" - out_dir = out_path.parent - old_package_dir = out_dir / "v2_all" - if old_package_dir.exists(): - shutil.rmtree(old_package_dir) - out_dir.mkdir(parents=True, exist_ok=True) - with tempfile.TemporaryDirectory() as td: - normalized_bundle = Path(td) / schema_bundle_path().name - normalized_bundle.write_text(_normalized_schema_bundle_text()) - run_python_module( - "datamodel_code_generator", - [ - "--input", - str(normalized_bundle), - "--input-file-type", - "jsonschema", - "--output", - str(out_path), - "--output-model-type", - "pydantic_v2.BaseModel", - "--target-python-version", - "3.11", - "--use-standard-collections", - "--enum-field-as-literal", - "one", - "--field-constraints", - "--use-default-kwarg", - "--snake-case-field", - "--allow-population-by-field-name", - # Once the schema prepass has assigned stable titles, tell the - # generator to prefer those titles as the emitted class names. - "--use-title-as-name", - "--use-annotated", - "--use-union-operator", - "--disable-timestamp", - # Keep the generated file formatted deterministically so the - # checked-in artifact only changes when the schema does. - "--formatters", - "ruff-format", - ], - cwd=sdk_root(), - ) - _normalize_generated_timestamps(out_path) - - -def _notification_specs() -> list[tuple[str, str]]: - server_notifications = json.loads( - (schema_root_dir() / "ServerNotification.json").read_text() - ) - one_of = server_notifications.get("oneOf", []) - generated_source = ( - sdk_root() / "src" / "codex_app_server" / "generated" / "v2_all.py" - ).read_text() - - specs: list[tuple[str, str]] = [] - - for variant in one_of: - props = variant.get("properties", {}) - method_meta = props.get("method", {}) - params_meta = props.get("params", {}) - - methods = method_meta.get("enum", []) - if len(methods) != 1: - continue - method = methods[0] - if not isinstance(method, str): - continue - - ref = params_meta.get("$ref") - if not isinstance(ref, str) or not ref.startswith("#/definitions/"): - continue - class_name = ref.split("/")[-1] - if ( - f"class {class_name}(" not in generated_source - and f"{class_name} =" not in generated_source - ): - # Skip schema variants that are not emitted into the generated v2 surface. - continue - specs.append((method, class_name)) - - specs.sort() - return specs - - -def generate_notification_registry() -> None: - out = ( - sdk_root() - / "src" - / "codex_app_server" - / "generated" - / "notification_registry.py" - ) - specs = _notification_specs() - class_names = sorted({class_name for _, class_name in specs}) - - lines = [ - "# Auto-generated by scripts/update_sdk_artifacts.py", - "# DO NOT EDIT MANUALLY.", - "", - "from __future__ import annotations", - "", - "from pydantic import BaseModel", - "", - ] - - for class_name in class_names: - lines.append(f"from .v2_all import {class_name}") - lines.extend( - [ - "", - "NOTIFICATION_MODELS: dict[str, type[BaseModel]] = {", - ] - ) - for method, class_name in specs: - lines.append(f' "{method}": {class_name},') - lines.extend(["}", ""]) - - out.write_text("\n".join(lines)) - - -def _normalize_generated_timestamps(root: Path) -> None: - timestamp_re = re.compile(r"^#\s+timestamp:\s+.+$", flags=re.MULTILINE) - py_files = [root] if root.is_file() else sorted(root.rglob("*.py")) - for py_file in py_files: - content = py_file.read_text() - normalized = timestamp_re.sub("# timestamp: ", content) - if normalized != content: - py_file.write_text(normalized) - - -FIELD_ANNOTATION_OVERRIDES: dict[str, str] = { - # Keep public API typed without falling back to `Any`. - "config": "JsonObject", - "output_schema": "JsonObject", -} - - -@dataclass(slots=True) -class PublicFieldSpec: - wire_name: str - py_name: str - annotation: str - required: bool - - -@dataclass(frozen=True) -class CliOps: - generate_types: Callable[[], None] - stage_python_sdk_package: Callable[[Path, str, str], Path] - stage_python_runtime_package: Callable[[Path, str, Path, str | None], Path] - current_sdk_version: Callable[[], str] - - -def _annotation_to_source(annotation: Any) -> str: - origin = get_origin(annotation) - if origin is typing.Annotated: - return _annotation_to_source(get_args(annotation)[0]) - if origin in (typing.Union, types.UnionType): - parts: list[str] = [] - for arg in get_args(annotation): - rendered = _annotation_to_source(arg) - if rendered not in parts: - parts.append(rendered) - return " | ".join(parts) - if origin is list: - args = get_args(annotation) - item = _annotation_to_source(args[0]) if args else "Any" - return f"list[{item}]" - if origin is dict: - args = get_args(annotation) - key = _annotation_to_source(args[0]) if args else "str" - val = _annotation_to_source(args[1]) if len(args) > 1 else "Any" - return f"dict[{key}, {val}]" - if annotation is Any or annotation is typing.Any: - return "Any" - if annotation is None or annotation is type(None): - return "None" - if isinstance(annotation, type): - if annotation.__module__ == "builtins": - return annotation.__name__ - return annotation.__name__ - return repr(annotation) - - -def _camel_to_snake(name: str) -> str: - head = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", name) - return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", head).lower() - - -def _load_public_fields( - module_name: str, class_name: str, *, exclude: set[str] | None = None -) -> list[PublicFieldSpec]: - exclude = exclude or set() - module = importlib.import_module(module_name) - model = getattr(module, class_name) - fields: list[PublicFieldSpec] = [] - for name, field in model.model_fields.items(): - if name in exclude: - continue - required = field.is_required() - annotation = _annotation_to_source(field.annotation) - override = FIELD_ANNOTATION_OVERRIDES.get(name) - if override is not None: - annotation = override if required else f"{override} | None" - fields.append( - PublicFieldSpec( - wire_name=name, - py_name=name, - annotation=annotation, - required=required, - ) - ) - return fields - - -def _kw_signature_lines(fields: list[PublicFieldSpec]) -> list[str]: - lines: list[str] = [] - for field in fields: - default = "" if field.required else " = None" - lines.append(f" {field.py_name}: {field.annotation}{default},") - return lines - - -def _model_arg_lines( - fields: list[PublicFieldSpec], *, indent: str = " " -) -> list[str]: - return [f"{indent}{field.wire_name}={field.py_name}," for field in fields] - - -def _replace_generated_block(source: str, block_name: str, body: str) -> str: - start_tag = f" # BEGIN GENERATED: {block_name}" - end_tag = f" # END GENERATED: {block_name}" - pattern = re.compile(rf"(?s){re.escape(start_tag)}\n.*?\n{re.escape(end_tag)}") - replacement = f"{start_tag}\n{body.rstrip()}\n{end_tag}" - updated, count = pattern.subn(replacement, source, count=1) - if count != 1: - raise RuntimeError(f"Could not update generated block: {block_name}") - return updated - - -def _render_codex_block( - thread_start_fields: list[PublicFieldSpec], - thread_list_fields: list[PublicFieldSpec], - resume_fields: list[PublicFieldSpec], - fork_fields: list[PublicFieldSpec], -) -> str: - lines = [ - " def thread_start(", - " self,", - " *,", - *_kw_signature_lines(thread_start_fields), - " ) -> Thread:", - " params = ThreadStartParams(", - *_model_arg_lines(thread_start_fields), - " )", - " started = self._client.thread_start(params)", - " return Thread(self._client, started.thread.id)", - "", - " def thread_list(", - " self,", - " *,", - *_kw_signature_lines(thread_list_fields), - " ) -> ThreadListResponse:", - " params = ThreadListParams(", - *_model_arg_lines(thread_list_fields), - " )", - " return self._client.thread_list(params)", - "", - " def thread_resume(", - " self,", - " thread_id: str,", - " *,", - *_kw_signature_lines(resume_fields), - " ) -> Thread:", - " params = ThreadResumeParams(", - " thread_id=thread_id,", - *_model_arg_lines(resume_fields), - " )", - " resumed = self._client.thread_resume(thread_id, params)", - " return Thread(self._client, resumed.thread.id)", - "", - " def thread_fork(", - " self,", - " thread_id: str,", - " *,", - *_kw_signature_lines(fork_fields), - " ) -> Thread:", - " params = ThreadForkParams(", - " thread_id=thread_id,", - *_model_arg_lines(fork_fields), - " )", - " forked = self._client.thread_fork(thread_id, params)", - " return Thread(self._client, forked.thread.id)", - "", - " def thread_archive(self, thread_id: str) -> ThreadArchiveResponse:", - " return self._client.thread_archive(thread_id)", - "", - " def thread_unarchive(self, thread_id: str) -> Thread:", - " unarchived = self._client.thread_unarchive(thread_id)", - " return Thread(self._client, unarchived.thread.id)", - ] - return "\n".join(lines) - - -def _render_async_codex_block( - thread_start_fields: list[PublicFieldSpec], - thread_list_fields: list[PublicFieldSpec], - resume_fields: list[PublicFieldSpec], - fork_fields: list[PublicFieldSpec], -) -> str: - lines = [ - " async def thread_start(", - " self,", - " *,", - *_kw_signature_lines(thread_start_fields), - " ) -> AsyncThread:", - " await self._ensure_initialized()", - " params = ThreadStartParams(", - *_model_arg_lines(thread_start_fields), - " )", - " started = await self._client.thread_start(params)", - " return AsyncThread(self, started.thread.id)", - "", - " async def thread_list(", - " self,", - " *,", - *_kw_signature_lines(thread_list_fields), - " ) -> ThreadListResponse:", - " await self._ensure_initialized()", - " params = ThreadListParams(", - *_model_arg_lines(thread_list_fields), - " )", - " return await self._client.thread_list(params)", - "", - " async def thread_resume(", - " self,", - " thread_id: str,", - " *,", - *_kw_signature_lines(resume_fields), - " ) -> AsyncThread:", - " await self._ensure_initialized()", - " params = ThreadResumeParams(", - " thread_id=thread_id,", - *_model_arg_lines(resume_fields), - " )", - " resumed = await self._client.thread_resume(thread_id, params)", - " return AsyncThread(self, resumed.thread.id)", - "", - " async def thread_fork(", - " self,", - " thread_id: str,", - " *,", - *_kw_signature_lines(fork_fields), - " ) -> AsyncThread:", - " await self._ensure_initialized()", - " params = ThreadForkParams(", - " thread_id=thread_id,", - *_model_arg_lines(fork_fields), - " )", - " forked = await self._client.thread_fork(thread_id, params)", - " return AsyncThread(self, forked.thread.id)", - "", - " async def thread_archive(self, thread_id: str) -> ThreadArchiveResponse:", - " await self._ensure_initialized()", - " return await self._client.thread_archive(thread_id)", - "", - " async def thread_unarchive(self, thread_id: str) -> AsyncThread:", - " await self._ensure_initialized()", - " unarchived = await self._client.thread_unarchive(thread_id)", - " return AsyncThread(self, unarchived.thread.id)", - ] - return "\n".join(lines) - - -def _render_thread_block( - turn_fields: list[PublicFieldSpec], -) -> str: - lines = [ - " def turn(", - " self,", - " input: Input,", - " *,", - *_kw_signature_lines(turn_fields), - " ) -> TurnHandle:", - " wire_input = _to_wire_input(input)", - " params = TurnStartParams(", - " thread_id=self.id,", - " input=wire_input,", - *_model_arg_lines(turn_fields), - " )", - " turn = self._client.turn_start(self.id, wire_input, params=params)", - " return TurnHandle(self._client, self.id, turn.turn.id)", - ] - return "\n".join(lines) - - -def _render_async_thread_block( - turn_fields: list[PublicFieldSpec], -) -> str: - lines = [ - " async def turn(", - " self,", - " input: Input,", - " *,", - *_kw_signature_lines(turn_fields), - " ) -> AsyncTurnHandle:", - " await self._codex._ensure_initialized()", - " wire_input = _to_wire_input(input)", - " params = TurnStartParams(", - " thread_id=self.id,", - " input=wire_input,", - *_model_arg_lines(turn_fields), - " )", - " turn = await self._codex._client.turn_start(", - " self.id,", - " wire_input,", - " params=params,", - " )", - " return AsyncTurnHandle(self._codex, self.id, turn.turn.id)", - ] - return "\n".join(lines) - - -def generate_public_api_flat_methods() -> None: - src_dir = sdk_root() / "src" - public_api_path = src_dir / "codex_app_server" / "api.py" - if not public_api_path.exists(): - # PR2 can run codegen before the ergonomic public API layer is added. - return - src_dir_str = str(src_dir) - if src_dir_str not in sys.path: - sys.path.insert(0, src_dir_str) - - thread_start_fields = _load_public_fields( - "codex_app_server.generated.v2_all", - "ThreadStartParams", - ) - thread_list_fields = _load_public_fields( - "codex_app_server.generated.v2_all", - "ThreadListParams", - ) - thread_resume_fields = _load_public_fields( - "codex_app_server.generated.v2_all", - "ThreadResumeParams", - exclude={"thread_id"}, - ) - thread_fork_fields = _load_public_fields( - "codex_app_server.generated.v2_all", - "ThreadForkParams", - exclude={"thread_id"}, - ) - turn_start_fields = _load_public_fields( - "codex_app_server.generated.v2_all", - "TurnStartParams", - exclude={"thread_id", "input"}, - ) - - source = public_api_path.read_text() - source = _replace_generated_block( - source, - "Codex.flat_methods", - _render_codex_block( - thread_start_fields, - thread_list_fields, - thread_resume_fields, - thread_fork_fields, - ), - ) - source = _replace_generated_block( - source, - "AsyncCodex.flat_methods", - _render_async_codex_block( - thread_start_fields, - thread_list_fields, - thread_resume_fields, - thread_fork_fields, - ), - ) - source = _replace_generated_block( - source, - "Thread.flat_methods", - _render_thread_block(turn_start_fields), - ) - source = _replace_generated_block( - source, - "AsyncThread.flat_methods", - _render_async_thread_block(turn_start_fields), - ) - public_api_path.write_text(source) - - -def generate_types() -> None: - # v2_all is the authoritative generated surface. - generate_v2_all() - generate_notification_registry() - generate_public_api_flat_methods() - - -def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(description="Single SDK maintenance entrypoint") - subparsers = parser.add_subparsers(dest="command", required=True) - - subparsers.add_parser( - "generate-types", help="Regenerate Python protocol-derived types" - ) - - stage_sdk_parser = subparsers.add_parser( - "stage-sdk", - help="Stage a releasable SDK package pinned to a runtime version", - ) - stage_sdk_parser.add_argument( - "staging_dir", - type=Path, - help="Output directory for the staged SDK package", - ) - stage_sdk_parser.add_argument( - "--runtime-version", - required=True, - help="Pinned openai-codex-cli-bin version for the staged SDK package", - ) - stage_sdk_parser.add_argument( - "--sdk-version", - help="Version to write into the staged SDK package (defaults to sdk/python current version)", - ) - - stage_runtime_parser = subparsers.add_parser( - "stage-runtime", - help="Stage a releasable runtime package for the current platform", - ) - stage_runtime_parser.add_argument( - "staging_dir", - type=Path, - help="Output directory for the staged runtime package", - ) - stage_runtime_parser.add_argument( - "runtime_binary", - type=Path, - help="Path to the codex binary to package for this platform", - ) - stage_runtime_parser.add_argument( - "--codex-version", - help=( - "Codex release version to write into the staged runtime package. " - "Accepts PEP 440 versions or release tags such as rust-v0.116.0-alpha.1." - ), - ) - stage_runtime_parser.add_argument( - "--runtime-version", - help=argparse.SUPPRESS, - ) - stage_runtime_parser.add_argument( - "--platform-tag", - help=( - "Optional wheel platform tag override, for example " - "macosx_11_0_arm64 or musllinux_1_1_x86_64." - ), - ) - return parser - - -def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: - return build_parser().parse_args(list(argv) if argv is not None else None) - - -def default_cli_ops() -> CliOps: - return CliOps( - generate_types=generate_types, - stage_python_sdk_package=stage_python_sdk_package, - stage_python_runtime_package=stage_python_runtime_package, - current_sdk_version=current_sdk_version, - ) - - -def _resolve_runtime_version(args: argparse.Namespace) -> str: - versions = [ - value - for value in ( - getattr(args, "codex_version", None), - getattr(args, "runtime_version", None), - ) - if value is not None - ] - if not versions: - raise RuntimeError("Pass --codex-version to stage the Python runtime package") - - normalized_versions = [normalize_codex_version(version) for version in versions] - if len(set(normalized_versions)) != 1: - raise RuntimeError( - "Runtime package versions must match; pass one --codex-version" - ) - return normalized_versions[0] - - -def run_command(args: argparse.Namespace, ops: CliOps) -> None: - if args.command == "generate-types": - ops.generate_types() - elif args.command == "stage-sdk": - ops.generate_types() - ops.stage_python_sdk_package( - args.staging_dir, - args.sdk_version or ops.current_sdk_version(), - args.runtime_version, - ) - elif args.command == "stage-runtime": - runtime_version = _resolve_runtime_version(args) - ops.stage_python_runtime_package( - args.staging_dir, - runtime_version, - args.runtime_binary.resolve(), - args.platform_tag, - ) - - -def main(argv: Sequence[str] | None = None, ops: CliOps | None = None) -> None: - args = parse_args(argv) - run_command(args, ops or default_cli_ops()) - print("Done.") - - -if __name__ == "__main__": - main() diff --git a/vendor/codex/sdk/python/src/codex_app_server/__init__.py b/vendor/codex/sdk/python/src/codex_app_server/__init__.py deleted file mode 100644 index c35ce0eb..00000000 --- a/vendor/codex/sdk/python/src/codex_app_server/__init__.py +++ /dev/null @@ -1,113 +0,0 @@ -from .async_client import AsyncAppServerClient -from .client import AppServerClient, AppServerConfig -from .errors import ( - AppServerError, - AppServerRpcError, - InternalRpcError, - InvalidParamsError, - InvalidRequestError, - JsonRpcError, - MethodNotFoundError, - ParseError, - RetryLimitExceededError, - ServerBusyError, - TransportClosedError, - is_retryable_error, -) -from .generated.v2_all import ( - AskForApproval, - Personality, - PlanType, - ReasoningEffort, - ReasoningSummary, - SandboxMode, - SandboxPolicy, - ServiceTier, - ThreadItem, - ThreadForkParams, - ThreadListParams, - ThreadResumeParams, - ThreadSortKey, - ThreadSourceKind, - ThreadStartParams, - ThreadTokenUsageUpdatedNotification, - TurnCompletedNotification, - TurnStartParams, - TurnStatus, - TurnSteerParams, -) -from .models import InitializeResponse -from .api import ( - AsyncCodex, - AsyncThread, - AsyncTurnHandle, - Codex, - ImageInput, - Input, - InputItem, - LocalImageInput, - MentionInput, - RunResult, - SkillInput, - TextInput, - Thread, - TurnHandle, -) -from .retry import retry_on_overload - -__version__ = "0.2.0" - -__all__ = [ - "__version__", - "AppServerClient", - "AsyncAppServerClient", - "AppServerConfig", - "Codex", - "AsyncCodex", - "Thread", - "AsyncThread", - "TurnHandle", - "AsyncTurnHandle", - "InitializeResponse", - "RunResult", - "Input", - "InputItem", - "TextInput", - "ImageInput", - "LocalImageInput", - "SkillInput", - "MentionInput", - "ThreadItem", - "ThreadTokenUsageUpdatedNotification", - "TurnCompletedNotification", - "AskForApproval", - "Personality", - "PlanType", - "ReasoningEffort", - "ReasoningSummary", - "SandboxMode", - "SandboxPolicy", - "ServiceTier", - "ThreadStartParams", - "ThreadResumeParams", - "ThreadListParams", - "ThreadSortKey", - "ThreadSourceKind", - "ThreadForkParams", - "TurnStatus", - "TurnStartParams", - "TurnSteerParams", - "retry_on_overload", - "AppServerError", - "TransportClosedError", - "JsonRpcError", - "AppServerRpcError", - "ParseError", - "InvalidRequestError", - "MethodNotFoundError", - "InvalidParamsError", - "InternalRpcError", - "ServerBusyError", - "RetryLimitExceededError", - "is_retryable_error", -] diff --git a/vendor/codex/sdk/python/src/codex_app_server/_inputs.py b/vendor/codex/sdk/python/src/codex_app_server/_inputs.py deleted file mode 100644 index e3cd1c39..00000000 --- a/vendor/codex/sdk/python/src/codex_app_server/_inputs.py +++ /dev/null @@ -1,63 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass - -from .models import JsonObject - - -@dataclass(slots=True) -class TextInput: - text: str - - -@dataclass(slots=True) -class ImageInput: - url: str - - -@dataclass(slots=True) -class LocalImageInput: - path: str - - -@dataclass(slots=True) -class SkillInput: - name: str - path: str - - -@dataclass(slots=True) -class MentionInput: - name: str - path: str - - -InputItem = TextInput | ImageInput | LocalImageInput | SkillInput | MentionInput -Input = list[InputItem] | InputItem -RunInput = Input | str - - -def _to_wire_item(item: InputItem) -> JsonObject: - if isinstance(item, TextInput): - return {"type": "text", "text": item.text} - if isinstance(item, ImageInput): - return {"type": "image", "url": item.url} - if isinstance(item, LocalImageInput): - return {"type": "localImage", "path": item.path} - if isinstance(item, SkillInput): - return {"type": "skill", "name": item.name, "path": item.path} - if isinstance(item, MentionInput): - return {"type": "mention", "name": item.name, "path": item.path} - raise TypeError(f"unsupported input item: {type(item)!r}") - - -def _to_wire_input(input: Input) -> list[JsonObject]: - if isinstance(input, list): - return [_to_wire_item(i) for i in input] - return [_to_wire_item(input)] - - -def _normalize_run_input(input: RunInput) -> Input: - if isinstance(input, str): - return TextInput(input) - return input diff --git a/vendor/codex/sdk/python/src/codex_app_server/_run.py b/vendor/codex/sdk/python/src/codex_app_server/_run.py deleted file mode 100644 index 73ec3624..00000000 --- a/vendor/codex/sdk/python/src/codex_app_server/_run.py +++ /dev/null @@ -1,112 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from typing import AsyncIterator, Iterator - -from .generated.v2_all import ( - AgentMessageThreadItem, - ItemCompletedNotification, - MessagePhase, - ThreadItem, - ThreadTokenUsage, - ThreadTokenUsageUpdatedNotification, - Turn as AppServerTurn, - TurnCompletedNotification, - TurnStatus, -) -from .models import Notification - - -@dataclass(slots=True) -class RunResult: - final_response: str | None - items: list[ThreadItem] - usage: ThreadTokenUsage | None - - -def _agent_message_item_from_thread_item( - item: ThreadItem, -) -> AgentMessageThreadItem | None: - thread_item = item.root if hasattr(item, "root") else item - if isinstance(thread_item, AgentMessageThreadItem): - return thread_item - return None - - -def _final_assistant_response_from_items(items: list[ThreadItem]) -> str | None: - last_unknown_phase_response: str | None = None - - for item in reversed(items): - agent_message = _agent_message_item_from_thread_item(item) - if agent_message is None: - continue - if agent_message.phase == MessagePhase.final_answer: - return agent_message.text - if agent_message.phase is None and last_unknown_phase_response is None: - last_unknown_phase_response = agent_message.text - - return last_unknown_phase_response - - -def _raise_for_failed_turn(turn: AppServerTurn) -> None: - if turn.status != TurnStatus.failed: - return - if turn.error is not None and turn.error.message: - raise RuntimeError(turn.error.message) - raise RuntimeError(f"turn failed with status {turn.status.value}") - - -def _collect_run_result(stream: Iterator[Notification], *, turn_id: str) -> RunResult: - completed: TurnCompletedNotification | None = None - items: list[ThreadItem] = [] - usage: ThreadTokenUsage | None = None - - for event in stream: - payload = event.payload - if isinstance(payload, ItemCompletedNotification) and payload.turn_id == turn_id: - items.append(payload.item) - continue - if isinstance(payload, ThreadTokenUsageUpdatedNotification) and payload.turn_id == turn_id: - usage = payload.token_usage - continue - if isinstance(payload, TurnCompletedNotification) and payload.turn.id == turn_id: - completed = payload - - if completed is None: - raise RuntimeError("turn completed event not received") - - _raise_for_failed_turn(completed.turn) - return RunResult( - final_response=_final_assistant_response_from_items(items), - items=items, - usage=usage, - ) - - -async def _collect_async_run_result( - stream: AsyncIterator[Notification], *, turn_id: str -) -> RunResult: - completed: TurnCompletedNotification | None = None - items: list[ThreadItem] = [] - usage: ThreadTokenUsage | None = None - - async for event in stream: - payload = event.payload - if isinstance(payload, ItemCompletedNotification) and payload.turn_id == turn_id: - items.append(payload.item) - continue - if isinstance(payload, ThreadTokenUsageUpdatedNotification) and payload.turn_id == turn_id: - usage = payload.token_usage - continue - if isinstance(payload, TurnCompletedNotification) and payload.turn.id == turn_id: - completed = payload - - if completed is None: - raise RuntimeError("turn completed event not received") - - _raise_for_failed_turn(completed.turn) - return RunResult( - final_response=_final_assistant_response_from_items(items), - items=items, - usage=usage, - ) diff --git a/vendor/codex/sdk/python/src/codex_app_server/api.py b/vendor/codex/sdk/python/src/codex_app_server/api.py deleted file mode 100644 index c330e3f7..00000000 --- a/vendor/codex/sdk/python/src/codex_app_server/api.py +++ /dev/null @@ -1,755 +0,0 @@ -from __future__ import annotations - -import asyncio -from dataclasses import dataclass -from typing import AsyncIterator, Iterator - -from .async_client import AsyncAppServerClient -from .client import AppServerClient, AppServerConfig -from .generated.v2_all import ( - ApprovalsReviewer, - AskForApproval, - ModelListResponse, - Personality, - ReasoningEffort, - ReasoningSummary, - SandboxMode, - SandboxPolicy, - ServiceTier, - ThreadArchiveResponse, - ThreadCompactStartResponse, - ThreadForkParams, - ThreadListParams, - ThreadListResponse, - ThreadReadResponse, - ThreadResumeParams, - ThreadSetNameResponse, - ThreadSortKey, - ThreadSourceKind, - ThreadStartParams, - Turn as AppServerTurn, - TurnCompletedNotification, - TurnInterruptResponse, - TurnStartParams, - TurnSteerResponse, -) -from .models import InitializeResponse, JsonObject, Notification, ServerInfo -from ._inputs import ( - ImageInput, - Input, - InputItem, - LocalImageInput, - MentionInput, - RunInput, - SkillInput, - TextInput, - _normalize_run_input, - _to_wire_input, -) -from ._run import ( - RunResult, - _collect_async_run_result, - _collect_run_result, -) - - -def _split_user_agent(user_agent: str) -> tuple[str | None, str | None]: - raw = user_agent.strip() - if not raw: - return None, None - if "/" in raw: - name, version = raw.split("/", 1) - return (name or None), (version or None) - parts = raw.split(maxsplit=1) - if len(parts) == 2: - return parts[0], parts[1] - return raw, None - - -class Codex: - """Minimal typed SDK surface for app-server v2.""" - - def __init__(self, config: AppServerConfig | None = None) -> None: - self._client = AppServerClient(config=config) - try: - self._client.start() - self._init = self._validate_initialize(self._client.initialize()) - except Exception: - self._client.close() - raise - - def __enter__(self) -> "Codex": - return self - - def __exit__(self, _exc_type, _exc, _tb) -> None: - self.close() - - @staticmethod - def _validate_initialize(payload: InitializeResponse) -> InitializeResponse: - user_agent = (payload.userAgent or "").strip() - server = payload.serverInfo - - server_name: str | None = None - server_version: str | None = None - - if server is not None: - server_name = (server.name or "").strip() or None - server_version = (server.version or "").strip() or None - - if (server_name is None or server_version is None) and user_agent: - parsed_name, parsed_version = _split_user_agent(user_agent) - if server_name is None: - server_name = parsed_name - if server_version is None: - server_version = parsed_version - - normalized_server_name = (server_name or "").strip() - normalized_server_version = (server_version or "").strip() - if ( - not user_agent - or not normalized_server_name - or not normalized_server_version - ): - raise RuntimeError( - "initialize response missing required metadata " - f"(user_agent={user_agent!r}, server_name={normalized_server_name!r}, server_version={normalized_server_version!r})" - ) - - if server is None: - payload.serverInfo = ServerInfo( - name=normalized_server_name, - version=normalized_server_version, - ) - else: - server.name = normalized_server_name - server.version = normalized_server_version - - return payload - - @property - def metadata(self) -> InitializeResponse: - return self._init - - def close(self) -> None: - self._client.close() - - # BEGIN GENERATED: Codex.flat_methods - def thread_start( - self, - *, - approval_policy: AskForApproval | None = None, - approvals_reviewer: ApprovalsReviewer | None = None, - base_instructions: str | None = None, - config: JsonObject | None = None, - cwd: str | None = None, - developer_instructions: str | None = None, - ephemeral: bool | None = None, - model: str | None = None, - model_provider: str | None = None, - personality: Personality | None = None, - sandbox: SandboxMode | None = None, - service_name: str | None = None, - service_tier: ServiceTier | None = None, - session_start_source: ThreadStartSource | None = None, - ) -> Thread: - params = ThreadStartParams( - approval_policy=approval_policy, - approvals_reviewer=approvals_reviewer, - base_instructions=base_instructions, - config=config, - cwd=cwd, - developer_instructions=developer_instructions, - ephemeral=ephemeral, - model=model, - model_provider=model_provider, - personality=personality, - sandbox=sandbox, - service_name=service_name, - service_tier=service_tier, - session_start_source=session_start_source, - ) - started = self._client.thread_start(params) - return Thread(self._client, started.thread.id) - - def thread_list( - self, - *, - archived: bool | None = None, - cursor: str | None = None, - cwd: str | None = None, - limit: int | None = None, - model_providers: list[str] | None = None, - search_term: str | None = None, - sort_direction: SortDirection | None = None, - sort_key: ThreadSortKey | None = None, - source_kinds: list[ThreadSourceKind] | None = None, - ) -> ThreadListResponse: - params = ThreadListParams( - archived=archived, - cursor=cursor, - cwd=cwd, - limit=limit, - model_providers=model_providers, - search_term=search_term, - sort_direction=sort_direction, - sort_key=sort_key, - source_kinds=source_kinds, - ) - return self._client.thread_list(params) - - def thread_resume( - self, - thread_id: str, - *, - approval_policy: AskForApproval | None = None, - approvals_reviewer: ApprovalsReviewer | None = None, - base_instructions: str | None = None, - config: JsonObject | None = None, - cwd: str | None = None, - developer_instructions: str | None = None, - model: str | None = None, - model_provider: str | None = None, - personality: Personality | None = None, - sandbox: SandboxMode | None = None, - service_tier: ServiceTier | None = None, - ) -> Thread: - params = ThreadResumeParams( - thread_id=thread_id, - approval_policy=approval_policy, - approvals_reviewer=approvals_reviewer, - base_instructions=base_instructions, - config=config, - cwd=cwd, - developer_instructions=developer_instructions, - model=model, - model_provider=model_provider, - personality=personality, - sandbox=sandbox, - service_tier=service_tier, - ) - resumed = self._client.thread_resume(thread_id, params) - return Thread(self._client, resumed.thread.id) - - def thread_fork( - self, - thread_id: str, - *, - approval_policy: AskForApproval | None = None, - approvals_reviewer: ApprovalsReviewer | None = None, - base_instructions: str | None = None, - config: JsonObject | None = None, - cwd: str | None = None, - developer_instructions: str | None = None, - ephemeral: bool | None = None, - model: str | None = None, - model_provider: str | None = None, - sandbox: SandboxMode | None = None, - service_tier: ServiceTier | None = None, - ) -> Thread: - params = ThreadForkParams( - thread_id=thread_id, - approval_policy=approval_policy, - approvals_reviewer=approvals_reviewer, - base_instructions=base_instructions, - config=config, - cwd=cwd, - developer_instructions=developer_instructions, - ephemeral=ephemeral, - model=model, - model_provider=model_provider, - sandbox=sandbox, - service_tier=service_tier, - ) - forked = self._client.thread_fork(thread_id, params) - return Thread(self._client, forked.thread.id) - - def thread_archive(self, thread_id: str) -> ThreadArchiveResponse: - return self._client.thread_archive(thread_id) - - def thread_unarchive(self, thread_id: str) -> Thread: - unarchived = self._client.thread_unarchive(thread_id) - return Thread(self._client, unarchived.thread.id) - # END GENERATED: Codex.flat_methods - - def models(self, *, include_hidden: bool = False) -> ModelListResponse: - return self._client.model_list(include_hidden=include_hidden) - - -class AsyncCodex: - """Async mirror of :class:`Codex`. - - Prefer ``async with AsyncCodex()`` so initialization and shutdown are - explicit and paired. The async client initializes lazily on context entry - or first awaited API use. - """ - - def __init__(self, config: AppServerConfig | None = None) -> None: - self._client = AsyncAppServerClient(config=config) - self._init: InitializeResponse | None = None - self._initialized = False - self._init_lock = asyncio.Lock() - - async def __aenter__(self) -> "AsyncCodex": - await self._ensure_initialized() - return self - - async def __aexit__(self, _exc_type, _exc, _tb) -> None: - await self.close() - - async def _ensure_initialized(self) -> None: - if self._initialized: - return - async with self._init_lock: - if self._initialized: - return - try: - await self._client.start() - payload = await self._client.initialize() - self._init = Codex._validate_initialize(payload) - self._initialized = True - except Exception: - await self._client.close() - self._init = None - self._initialized = False - raise - - @property - def metadata(self) -> InitializeResponse: - if self._init is None: - raise RuntimeError( - "AsyncCodex is not initialized yet. Prefer `async with AsyncCodex()`; " - "initialization also happens on first awaited API use." - ) - return self._init - - async def close(self) -> None: - await self._client.close() - self._init = None - self._initialized = False - - # BEGIN GENERATED: AsyncCodex.flat_methods - async def thread_start( - self, - *, - approval_policy: AskForApproval | None = None, - approvals_reviewer: ApprovalsReviewer | None = None, - base_instructions: str | None = None, - config: JsonObject | None = None, - cwd: str | None = None, - developer_instructions: str | None = None, - ephemeral: bool | None = None, - model: str | None = None, - model_provider: str | None = None, - personality: Personality | None = None, - sandbox: SandboxMode | None = None, - service_name: str | None = None, - service_tier: ServiceTier | None = None, - session_start_source: ThreadStartSource | None = None, - ) -> AsyncThread: - await self._ensure_initialized() - params = ThreadStartParams( - approval_policy=approval_policy, - approvals_reviewer=approvals_reviewer, - base_instructions=base_instructions, - config=config, - cwd=cwd, - developer_instructions=developer_instructions, - ephemeral=ephemeral, - model=model, - model_provider=model_provider, - personality=personality, - sandbox=sandbox, - service_name=service_name, - service_tier=service_tier, - session_start_source=session_start_source, - ) - started = await self._client.thread_start(params) - return AsyncThread(self, started.thread.id) - - async def thread_list( - self, - *, - archived: bool | None = None, - cursor: str | None = None, - cwd: str | None = None, - limit: int | None = None, - model_providers: list[str] | None = None, - search_term: str | None = None, - sort_direction: SortDirection | None = None, - sort_key: ThreadSortKey | None = None, - source_kinds: list[ThreadSourceKind] | None = None, - ) -> ThreadListResponse: - await self._ensure_initialized() - params = ThreadListParams( - archived=archived, - cursor=cursor, - cwd=cwd, - limit=limit, - model_providers=model_providers, - search_term=search_term, - sort_direction=sort_direction, - sort_key=sort_key, - source_kinds=source_kinds, - ) - return await self._client.thread_list(params) - - async def thread_resume( - self, - thread_id: str, - *, - approval_policy: AskForApproval | None = None, - approvals_reviewer: ApprovalsReviewer | None = None, - base_instructions: str | None = None, - config: JsonObject | None = None, - cwd: str | None = None, - developer_instructions: str | None = None, - model: str | None = None, - model_provider: str | None = None, - personality: Personality | None = None, - sandbox: SandboxMode | None = None, - service_tier: ServiceTier | None = None, - ) -> AsyncThread: - await self._ensure_initialized() - params = ThreadResumeParams( - thread_id=thread_id, - approval_policy=approval_policy, - approvals_reviewer=approvals_reviewer, - base_instructions=base_instructions, - config=config, - cwd=cwd, - developer_instructions=developer_instructions, - model=model, - model_provider=model_provider, - personality=personality, - sandbox=sandbox, - service_tier=service_tier, - ) - resumed = await self._client.thread_resume(thread_id, params) - return AsyncThread(self, resumed.thread.id) - - async def thread_fork( - self, - thread_id: str, - *, - approval_policy: AskForApproval | None = None, - approvals_reviewer: ApprovalsReviewer | None = None, - base_instructions: str | None = None, - config: JsonObject | None = None, - cwd: str | None = None, - developer_instructions: str | None = None, - ephemeral: bool | None = None, - model: str | None = None, - model_provider: str | None = None, - sandbox: SandboxMode | None = None, - service_tier: ServiceTier | None = None, - ) -> AsyncThread: - await self._ensure_initialized() - params = ThreadForkParams( - thread_id=thread_id, - approval_policy=approval_policy, - approvals_reviewer=approvals_reviewer, - base_instructions=base_instructions, - config=config, - cwd=cwd, - developer_instructions=developer_instructions, - ephemeral=ephemeral, - model=model, - model_provider=model_provider, - sandbox=sandbox, - service_tier=service_tier, - ) - forked = await self._client.thread_fork(thread_id, params) - return AsyncThread(self, forked.thread.id) - - async def thread_archive(self, thread_id: str) -> ThreadArchiveResponse: - await self._ensure_initialized() - return await self._client.thread_archive(thread_id) - - async def thread_unarchive(self, thread_id: str) -> AsyncThread: - await self._ensure_initialized() - unarchived = await self._client.thread_unarchive(thread_id) - return AsyncThread(self, unarchived.thread.id) - # END GENERATED: AsyncCodex.flat_methods - - async def models(self, *, include_hidden: bool = False) -> ModelListResponse: - await self._ensure_initialized() - return await self._client.model_list(include_hidden=include_hidden) - - -@dataclass(slots=True) -class Thread: - _client: AppServerClient - id: str - - def run( - self, - input: RunInput, - *, - approval_policy: AskForApproval | None = None, - approvals_reviewer: ApprovalsReviewer | None = None, - cwd: str | None = None, - effort: ReasoningEffort | None = None, - model: str | None = None, - output_schema: JsonObject | None = None, - personality: Personality | None = None, - sandbox_policy: SandboxPolicy | None = None, - service_tier: ServiceTier | None = None, - summary: ReasoningSummary | None = None, - ) -> RunResult: - turn = self.turn( - _normalize_run_input(input), - approval_policy=approval_policy, - approvals_reviewer=approvals_reviewer, - cwd=cwd, - effort=effort, - model=model, - output_schema=output_schema, - personality=personality, - sandbox_policy=sandbox_policy, - service_tier=service_tier, - summary=summary, - ) - stream = turn.stream() - try: - return _collect_run_result(stream, turn_id=turn.id) - finally: - stream.close() - - # BEGIN GENERATED: Thread.flat_methods - def turn( - self, - input: Input, - *, - approval_policy: AskForApproval | None = None, - approvals_reviewer: ApprovalsReviewer | None = None, - cwd: str | None = None, - effort: ReasoningEffort | None = None, - model: str | None = None, - output_schema: JsonObject | None = None, - personality: Personality | None = None, - sandbox_policy: SandboxPolicy | None = None, - service_tier: ServiceTier | None = None, - summary: ReasoningSummary | None = None, - ) -> TurnHandle: - wire_input = _to_wire_input(input) - params = TurnStartParams( - thread_id=self.id, - input=wire_input, - approval_policy=approval_policy, - approvals_reviewer=approvals_reviewer, - cwd=cwd, - effort=effort, - model=model, - output_schema=output_schema, - personality=personality, - sandbox_policy=sandbox_policy, - service_tier=service_tier, - summary=summary, - ) - turn = self._client.turn_start(self.id, wire_input, params=params) - return TurnHandle(self._client, self.id, turn.turn.id) - # END GENERATED: Thread.flat_methods - - def read(self, *, include_turns: bool = False) -> ThreadReadResponse: - return self._client.thread_read(self.id, include_turns=include_turns) - - def set_name(self, name: str) -> ThreadSetNameResponse: - return self._client.thread_set_name(self.id, name) - - def compact(self) -> ThreadCompactStartResponse: - return self._client.thread_compact(self.id) - - -@dataclass(slots=True) -class AsyncThread: - _codex: AsyncCodex - id: str - - async def run( - self, - input: RunInput, - *, - approval_policy: AskForApproval | None = None, - approvals_reviewer: ApprovalsReviewer | None = None, - cwd: str | None = None, - effort: ReasoningEffort | None = None, - model: str | None = None, - output_schema: JsonObject | None = None, - personality: Personality | None = None, - sandbox_policy: SandboxPolicy | None = None, - service_tier: ServiceTier | None = None, - summary: ReasoningSummary | None = None, - ) -> RunResult: - turn = await self.turn( - _normalize_run_input(input), - approval_policy=approval_policy, - approvals_reviewer=approvals_reviewer, - cwd=cwd, - effort=effort, - model=model, - output_schema=output_schema, - personality=personality, - sandbox_policy=sandbox_policy, - service_tier=service_tier, - summary=summary, - ) - stream = turn.stream() - try: - return await _collect_async_run_result(stream, turn_id=turn.id) - finally: - await stream.aclose() - - # BEGIN GENERATED: AsyncThread.flat_methods - async def turn( - self, - input: Input, - *, - approval_policy: AskForApproval | None = None, - approvals_reviewer: ApprovalsReviewer | None = None, - cwd: str | None = None, - effort: ReasoningEffort | None = None, - model: str | None = None, - output_schema: JsonObject | None = None, - personality: Personality | None = None, - sandbox_policy: SandboxPolicy | None = None, - service_tier: ServiceTier | None = None, - summary: ReasoningSummary | None = None, - ) -> AsyncTurnHandle: - await self._codex._ensure_initialized() - wire_input = _to_wire_input(input) - params = TurnStartParams( - thread_id=self.id, - input=wire_input, - approval_policy=approval_policy, - approvals_reviewer=approvals_reviewer, - cwd=cwd, - effort=effort, - model=model, - output_schema=output_schema, - personality=personality, - sandbox_policy=sandbox_policy, - service_tier=service_tier, - summary=summary, - ) - turn = await self._codex._client.turn_start( - self.id, - wire_input, - params=params, - ) - return AsyncTurnHandle(self._codex, self.id, turn.turn.id) - # END GENERATED: AsyncThread.flat_methods - - async def read(self, *, include_turns: bool = False) -> ThreadReadResponse: - await self._codex._ensure_initialized() - return await self._codex._client.thread_read( - self.id, include_turns=include_turns - ) - - async def set_name(self, name: str) -> ThreadSetNameResponse: - await self._codex._ensure_initialized() - return await self._codex._client.thread_set_name(self.id, name) - - async def compact(self) -> ThreadCompactStartResponse: - await self._codex._ensure_initialized() - return await self._codex._client.thread_compact(self.id) - - -@dataclass(slots=True) -class TurnHandle: - _client: AppServerClient - thread_id: str - id: str - - def steer(self, input: Input) -> TurnSteerResponse: - return self._client.turn_steer(self.thread_id, self.id, _to_wire_input(input)) - - def interrupt(self) -> TurnInterruptResponse: - return self._client.turn_interrupt(self.thread_id, self.id) - - def stream(self) -> Iterator[Notification]: - # TODO: replace this client-wide experimental guard with per-turn event demux. - self._client.acquire_turn_consumer(self.id) - try: - while True: - event = self._client.next_notification() - yield event - if ( - event.method == "turn/completed" - and isinstance(event.payload, TurnCompletedNotification) - and event.payload.turn.id == self.id - ): - break - finally: - self._client.release_turn_consumer(self.id) - - def run(self) -> AppServerTurn: - completed: TurnCompletedNotification | None = None - stream = self.stream() - try: - for event in stream: - payload = event.payload - if ( - isinstance(payload, TurnCompletedNotification) - and payload.turn.id == self.id - ): - completed = payload - finally: - stream.close() - - if completed is None: - raise RuntimeError("turn completed event not received") - return completed.turn - - -@dataclass(slots=True) -class AsyncTurnHandle: - _codex: AsyncCodex - thread_id: str - id: str - - async def steer(self, input: Input) -> TurnSteerResponse: - await self._codex._ensure_initialized() - return await self._codex._client.turn_steer( - self.thread_id, - self.id, - _to_wire_input(input), - ) - - async def interrupt(self) -> TurnInterruptResponse: - await self._codex._ensure_initialized() - return await self._codex._client.turn_interrupt(self.thread_id, self.id) - - async def stream(self) -> AsyncIterator[Notification]: - await self._codex._ensure_initialized() - # TODO: replace this client-wide experimental guard with per-turn event demux. - self._codex._client.acquire_turn_consumer(self.id) - try: - while True: - event = await self._codex._client.next_notification() - yield event - if ( - event.method == "turn/completed" - and isinstance(event.payload, TurnCompletedNotification) - and event.payload.turn.id == self.id - ): - break - finally: - self._codex._client.release_turn_consumer(self.id) - - async def run(self) -> AppServerTurn: - completed: TurnCompletedNotification | None = None - stream = self.stream() - try: - async for event in stream: - payload = event.payload - if ( - isinstance(payload, TurnCompletedNotification) - and payload.turn.id == self.id - ): - completed = payload - finally: - await stream.aclose() - - if completed is None: - raise RuntimeError("turn completed event not received") - return completed.turn diff --git a/vendor/codex/sdk/python/src/codex_app_server/async_client.py b/vendor/codex/sdk/python/src/codex_app_server/async_client.py deleted file mode 100644 index 6ca0c42a..00000000 --- a/vendor/codex/sdk/python/src/codex_app_server/async_client.py +++ /dev/null @@ -1,208 +0,0 @@ -from __future__ import annotations - -import asyncio -from collections.abc import Iterator -from typing import AsyncIterator, Callable, Iterable, ParamSpec, TypeVar - -from pydantic import BaseModel - -from .client import AppServerClient, AppServerConfig -from .generated.v2_all import ( - AgentMessageDeltaNotification, - ModelListResponse, - ThreadArchiveResponse, - ThreadCompactStartResponse, - ThreadForkParams as V2ThreadForkParams, - ThreadForkResponse, - ThreadListParams as V2ThreadListParams, - ThreadListResponse, - ThreadReadResponse, - ThreadResumeParams as V2ThreadResumeParams, - ThreadResumeResponse, - ThreadSetNameResponse, - ThreadStartParams as V2ThreadStartParams, - ThreadStartResponse, - ThreadUnarchiveResponse, - TurnCompletedNotification, - TurnInterruptResponse, - TurnStartParams as V2TurnStartParams, - TurnStartResponse, - TurnSteerResponse, -) -from .models import InitializeResponse, JsonObject, Notification - -ModelT = TypeVar("ModelT", bound=BaseModel) -ParamsT = ParamSpec("ParamsT") -ReturnT = TypeVar("ReturnT") - - -class AsyncAppServerClient: - """Async wrapper around AppServerClient using thread offloading.""" - - def __init__(self, config: AppServerConfig | None = None) -> None: - self._sync = AppServerClient(config=config) - # Single stdio transport cannot be read safely from multiple threads. - self._transport_lock = asyncio.Lock() - - async def __aenter__(self) -> "AsyncAppServerClient": - await self.start() - return self - - async def __aexit__(self, _exc_type, _exc, _tb) -> None: - await self.close() - - async def _call_sync( - self, - fn: Callable[ParamsT, ReturnT], - /, - *args: ParamsT.args, - **kwargs: ParamsT.kwargs, - ) -> ReturnT: - async with self._transport_lock: - return await asyncio.to_thread(fn, *args, **kwargs) - - @staticmethod - def _next_from_iterator( - iterator: Iterator[AgentMessageDeltaNotification], - ) -> tuple[bool, AgentMessageDeltaNotification | None]: - try: - return True, next(iterator) - except StopIteration: - return False, None - - async def start(self) -> None: - await self._call_sync(self._sync.start) - - async def close(self) -> None: - await self._call_sync(self._sync.close) - - async def initialize(self) -> InitializeResponse: - return await self._call_sync(self._sync.initialize) - - def acquire_turn_consumer(self, turn_id: str) -> None: - self._sync.acquire_turn_consumer(turn_id) - - def release_turn_consumer(self, turn_id: str) -> None: - self._sync.release_turn_consumer(turn_id) - - async def request( - self, - method: str, - params: JsonObject | None, - *, - response_model: type[ModelT], - ) -> ModelT: - return await self._call_sync( - self._sync.request, - method, - params, - response_model=response_model, - ) - - async def thread_start(self, params: V2ThreadStartParams | JsonObject | None = None) -> ThreadStartResponse: - return await self._call_sync(self._sync.thread_start, params) - - async def thread_resume( - self, - thread_id: str, - params: V2ThreadResumeParams | JsonObject | None = None, - ) -> ThreadResumeResponse: - return await self._call_sync(self._sync.thread_resume, thread_id, params) - - async def thread_list(self, params: V2ThreadListParams | JsonObject | None = None) -> ThreadListResponse: - return await self._call_sync(self._sync.thread_list, params) - - async def thread_read(self, thread_id: str, include_turns: bool = False) -> ThreadReadResponse: - return await self._call_sync(self._sync.thread_read, thread_id, include_turns) - - async def thread_fork( - self, - thread_id: str, - params: V2ThreadForkParams | JsonObject | None = None, - ) -> ThreadForkResponse: - return await self._call_sync(self._sync.thread_fork, thread_id, params) - - async def thread_archive(self, thread_id: str) -> ThreadArchiveResponse: - return await self._call_sync(self._sync.thread_archive, thread_id) - - async def thread_unarchive(self, thread_id: str) -> ThreadUnarchiveResponse: - return await self._call_sync(self._sync.thread_unarchive, thread_id) - - async def thread_set_name(self, thread_id: str, name: str) -> ThreadSetNameResponse: - return await self._call_sync(self._sync.thread_set_name, thread_id, name) - - async def thread_compact(self, thread_id: str) -> ThreadCompactStartResponse: - return await self._call_sync(self._sync.thread_compact, thread_id) - - async def turn_start( - self, - thread_id: str, - input_items: list[JsonObject] | JsonObject | str, - params: V2TurnStartParams | JsonObject | None = None, - ) -> TurnStartResponse: - return await self._call_sync(self._sync.turn_start, thread_id, input_items, params) - - async def turn_interrupt(self, thread_id: str, turn_id: str) -> TurnInterruptResponse: - return await self._call_sync(self._sync.turn_interrupt, thread_id, turn_id) - - async def turn_steer( - self, - thread_id: str, - expected_turn_id: str, - input_items: list[JsonObject] | JsonObject | str, - ) -> TurnSteerResponse: - return await self._call_sync( - self._sync.turn_steer, - thread_id, - expected_turn_id, - input_items, - ) - - async def model_list(self, include_hidden: bool = False) -> ModelListResponse: - return await self._call_sync(self._sync.model_list, include_hidden) - - async def request_with_retry_on_overload( - self, - method: str, - params: JsonObject | None, - *, - response_model: type[ModelT], - max_attempts: int = 3, - initial_delay_s: float = 0.25, - max_delay_s: float = 2.0, - ) -> ModelT: - return await self._call_sync( - self._sync.request_with_retry_on_overload, - method, - params, - response_model=response_model, - max_attempts=max_attempts, - initial_delay_s=initial_delay_s, - max_delay_s=max_delay_s, - ) - - async def next_notification(self) -> Notification: - return await self._call_sync(self._sync.next_notification) - - async def wait_for_turn_completed(self, turn_id: str) -> TurnCompletedNotification: - return await self._call_sync(self._sync.wait_for_turn_completed, turn_id) - - async def stream_until_methods(self, methods: Iterable[str] | str) -> list[Notification]: - return await self._call_sync(self._sync.stream_until_methods, methods) - - async def stream_text( - self, - thread_id: str, - text: str, - params: V2TurnStartParams | JsonObject | None = None, - ) -> AsyncIterator[AgentMessageDeltaNotification]: - async with self._transport_lock: - iterator = self._sync.stream_text(thread_id, text, params) - while True: - has_value, chunk = await asyncio.to_thread( - self._next_from_iterator, - iterator, - ) - if not has_value: - break - yield chunk diff --git a/vendor/codex/sdk/python/src/codex_app_server/client.py b/vendor/codex/sdk/python/src/codex_app_server/client.py deleted file mode 100644 index db7cf77c..00000000 --- a/vendor/codex/sdk/python/src/codex_app_server/client.py +++ /dev/null @@ -1,541 +0,0 @@ -from __future__ import annotations - -import json -import os -import subprocess -import threading -import uuid -from collections import deque -from dataclasses import dataclass -from pathlib import Path -from typing import Callable, Iterable, Iterator, TypeVar - -from pydantic import BaseModel - -from .errors import AppServerError, TransportClosedError, map_jsonrpc_error -from .generated.notification_registry import NOTIFICATION_MODELS -from .generated.v2_all import ( - AgentMessageDeltaNotification, - ModelListResponse, - ThreadArchiveResponse, - ThreadCompactStartResponse, - ThreadForkParams as V2ThreadForkParams, - ThreadForkResponse, - ThreadListParams as V2ThreadListParams, - ThreadListResponse, - ThreadReadResponse, - ThreadResumeParams as V2ThreadResumeParams, - ThreadResumeResponse, - ThreadSetNameResponse, - ThreadStartParams as V2ThreadStartParams, - ThreadStartResponse, - ThreadUnarchiveResponse, - TurnCompletedNotification, - TurnInterruptResponse, - TurnStartParams as V2TurnStartParams, - TurnStartResponse, - TurnSteerResponse, -) -from .models import ( - InitializeResponse, - JsonObject, - JsonValue, - Notification, - UnknownNotification, -) -from .retry import retry_on_overload - -ModelT = TypeVar("ModelT", bound=BaseModel) -ApprovalHandler = Callable[[str, JsonObject | None], JsonObject] -RUNTIME_PKG_NAME = "openai-codex-cli-bin" - - -def _params_dict( - params: ( - V2ThreadStartParams - | V2ThreadResumeParams - | V2ThreadListParams - | V2ThreadForkParams - | V2TurnStartParams - | JsonObject - | None - ), -) -> JsonObject: - if params is None: - return {} - if hasattr(params, "model_dump"): - dumped = params.model_dump( - by_alias=True, - exclude_none=True, - mode="json", - ) - if not isinstance(dumped, dict): - raise TypeError("Expected model_dump() to return dict") - return dumped - if isinstance(params, dict): - return params - raise TypeError(f"Expected generated params model or dict, got {type(params).__name__}") - - -def _installed_codex_path() -> Path: - try: - from codex_cli_bin import bundled_codex_path - except ImportError as exc: - raise FileNotFoundError( - "Unable to locate the pinned Codex runtime. Install the published SDK build " - f"with its {RUNTIME_PKG_NAME} dependency, or set AppServerConfig.codex_bin " - "explicitly." - ) from exc - - return bundled_codex_path() - - -@dataclass(frozen=True) -class CodexBinResolverOps: - installed_codex_path: Callable[[], Path] - path_exists: Callable[[Path], bool] - - -def _default_codex_bin_resolver_ops() -> CodexBinResolverOps: - return CodexBinResolverOps( - installed_codex_path=_installed_codex_path, - path_exists=lambda path: path.exists(), - ) - - -def resolve_codex_bin(config: "AppServerConfig", ops: CodexBinResolverOps) -> Path: - if config.codex_bin is not None: - codex_bin = Path(config.codex_bin) - if not ops.path_exists(codex_bin): - raise FileNotFoundError( - f"Codex binary not found at {codex_bin}. Set AppServerConfig.codex_bin " - "to a valid binary path." - ) - return codex_bin - - return ops.installed_codex_path() - - -def _resolve_codex_bin(config: "AppServerConfig") -> Path: - return resolve_codex_bin(config, _default_codex_bin_resolver_ops()) - - -@dataclass(slots=True) -class AppServerConfig: - codex_bin: str | None = None - launch_args_override: tuple[str, ...] | None = None - config_overrides: tuple[str, ...] = () - cwd: str | None = None - env: dict[str, str] | None = None - client_name: str = "codex_python_sdk" - client_title: str = "Codex Python SDK" - client_version: str = "0.2.0" - experimental_api: bool = True - - -class AppServerClient: - """Synchronous typed JSON-RPC client for `codex app-server` over stdio.""" - - def __init__( - self, - config: AppServerConfig | None = None, - approval_handler: ApprovalHandler | None = None, - ) -> None: - self.config = config or AppServerConfig() - self._approval_handler = approval_handler or self._default_approval_handler - self._proc: subprocess.Popen[str] | None = None - self._lock = threading.Lock() - self._turn_consumer_lock = threading.Lock() - self._active_turn_consumer: str | None = None - self._pending_notifications: deque[Notification] = deque() - self._stderr_lines: deque[str] = deque(maxlen=400) - self._stderr_thread: threading.Thread | None = None - - def __enter__(self) -> "AppServerClient": - self.start() - return self - - def __exit__(self, _exc_type, _exc, _tb) -> None: - self.close() - - def start(self) -> None: - if self._proc is not None: - return - - if self.config.launch_args_override is not None: - args = list(self.config.launch_args_override) - else: - codex_bin = _resolve_codex_bin(self.config) - args = [str(codex_bin)] - for kv in self.config.config_overrides: - args.extend(["--config", kv]) - args.extend(["app-server", "--listen", "stdio://"]) - - env = os.environ.copy() - if self.config.env: - env.update(self.config.env) - - self._proc = subprocess.Popen( - args, - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - encoding="utf-8", - cwd=self.config.cwd, - env=env, - bufsize=1, - ) - - self._start_stderr_drain_thread() - - def close(self) -> None: - if self._proc is None: - return - proc = self._proc - self._proc = None - self._active_turn_consumer = None - - if proc.stdin: - proc.stdin.close() - try: - proc.terminate() - proc.wait(timeout=2) - except Exception: - proc.kill() - - if self._stderr_thread and self._stderr_thread.is_alive(): - self._stderr_thread.join(timeout=0.5) - - def initialize(self) -> InitializeResponse: - result = self.request( - "initialize", - { - "clientInfo": { - "name": self.config.client_name, - "title": self.config.client_title, - "version": self.config.client_version, - }, - "capabilities": { - "experimentalApi": self.config.experimental_api, - }, - }, - response_model=InitializeResponse, - ) - self.notify("initialized", None) - return result - - def request( - self, - method: str, - params: JsonObject | None, - *, - response_model: type[ModelT], - ) -> ModelT: - result = self._request_raw(method, params) - if not isinstance(result, dict): - raise AppServerError(f"{method} response must be a JSON object") - return response_model.model_validate(result) - - def _request_raw(self, method: str, params: JsonObject | None = None) -> JsonValue: - request_id = str(uuid.uuid4()) - self._write_message({"id": request_id, "method": method, "params": params or {}}) - - while True: - msg = self._read_message() - - if "method" in msg and "id" in msg: - response = self._handle_server_request(msg) - self._write_message({"id": msg["id"], "result": response}) - continue - - if "method" in msg and "id" not in msg: - self._pending_notifications.append( - self._coerce_notification(msg["method"], msg.get("params")) - ) - continue - - if msg.get("id") != request_id: - continue - - if "error" in msg: - err = msg["error"] - if isinstance(err, dict): - raise map_jsonrpc_error( - int(err.get("code", -32000)), - str(err.get("message", "unknown")), - err.get("data"), - ) - raise AppServerError("Malformed JSON-RPC error response") - - return msg.get("result") - - def notify(self, method: str, params: JsonObject | None = None) -> None: - self._write_message({"method": method, "params": params or {}}) - - def next_notification(self) -> Notification: - if self._pending_notifications: - return self._pending_notifications.popleft() - - while True: - msg = self._read_message() - if "method" in msg and "id" in msg: - response = self._handle_server_request(msg) - self._write_message({"id": msg["id"], "result": response}) - continue - if "method" in msg and "id" not in msg: - return self._coerce_notification(msg["method"], msg.get("params")) - - def acquire_turn_consumer(self, turn_id: str) -> None: - with self._turn_consumer_lock: - if self._active_turn_consumer is not None: - raise RuntimeError( - "Concurrent turn consumers are not yet supported in the experimental SDK. " - f"Client is already streaming turn {self._active_turn_consumer!r}; " - f"cannot start turn {turn_id!r} until the active consumer finishes." - ) - self._active_turn_consumer = turn_id - - def release_turn_consumer(self, turn_id: str) -> None: - with self._turn_consumer_lock: - if self._active_turn_consumer == turn_id: - self._active_turn_consumer = None - - def thread_start(self, params: V2ThreadStartParams | JsonObject | None = None) -> ThreadStartResponse: - return self.request("thread/start", _params_dict(params), response_model=ThreadStartResponse) - - def thread_resume( - self, - thread_id: str, - params: V2ThreadResumeParams | JsonObject | None = None, - ) -> ThreadResumeResponse: - payload = {"threadId": thread_id, **_params_dict(params)} - return self.request("thread/resume", payload, response_model=ThreadResumeResponse) - - def thread_list(self, params: V2ThreadListParams | JsonObject | None = None) -> ThreadListResponse: - return self.request("thread/list", _params_dict(params), response_model=ThreadListResponse) - - def thread_read(self, thread_id: str, include_turns: bool = False) -> ThreadReadResponse: - return self.request( - "thread/read", - {"threadId": thread_id, "includeTurns": include_turns}, - response_model=ThreadReadResponse, - ) - - def thread_fork( - self, - thread_id: str, - params: V2ThreadForkParams | JsonObject | None = None, - ) -> ThreadForkResponse: - payload = {"threadId": thread_id, **_params_dict(params)} - return self.request("thread/fork", payload, response_model=ThreadForkResponse) - - def thread_archive(self, thread_id: str) -> ThreadArchiveResponse: - return self.request("thread/archive", {"threadId": thread_id}, response_model=ThreadArchiveResponse) - - def thread_unarchive(self, thread_id: str) -> ThreadUnarchiveResponse: - return self.request("thread/unarchive", {"threadId": thread_id}, response_model=ThreadUnarchiveResponse) - - def thread_set_name(self, thread_id: str, name: str) -> ThreadSetNameResponse: - return self.request( - "thread/name/set", - {"threadId": thread_id, "name": name}, - response_model=ThreadSetNameResponse, - ) - - def thread_compact(self, thread_id: str) -> ThreadCompactStartResponse: - return self.request( - "thread/compact/start", - {"threadId": thread_id}, - response_model=ThreadCompactStartResponse, - ) - - def turn_start( - self, - thread_id: str, - input_items: list[JsonObject] | JsonObject | str, - params: V2TurnStartParams | JsonObject | None = None, - ) -> TurnStartResponse: - payload = { - **_params_dict(params), - "threadId": thread_id, - "input": self._normalize_input_items(input_items), - } - return self.request("turn/start", payload, response_model=TurnStartResponse) - - def turn_interrupt(self, thread_id: str, turn_id: str) -> TurnInterruptResponse: - return self.request( - "turn/interrupt", - {"threadId": thread_id, "turnId": turn_id}, - response_model=TurnInterruptResponse, - ) - - def turn_steer( - self, - thread_id: str, - expected_turn_id: str, - input_items: list[JsonObject] | JsonObject | str, - ) -> TurnSteerResponse: - return self.request( - "turn/steer", - { - "threadId": thread_id, - "expectedTurnId": expected_turn_id, - "input": self._normalize_input_items(input_items), - }, - response_model=TurnSteerResponse, - ) - - def model_list(self, include_hidden: bool = False) -> ModelListResponse: - return self.request( - "model/list", - {"includeHidden": include_hidden}, - response_model=ModelListResponse, - ) - - def request_with_retry_on_overload( - self, - method: str, - params: JsonObject | None, - *, - response_model: type[ModelT], - max_attempts: int = 3, - initial_delay_s: float = 0.25, - max_delay_s: float = 2.0, - ) -> ModelT: - return retry_on_overload( - lambda: self.request(method, params, response_model=response_model), - max_attempts=max_attempts, - initial_delay_s=initial_delay_s, - max_delay_s=max_delay_s, - ) - - def wait_for_turn_completed(self, turn_id: str) -> TurnCompletedNotification: - while True: - notification = self.next_notification() - if ( - notification.method == "turn/completed" - and isinstance(notification.payload, TurnCompletedNotification) - and notification.payload.turn.id == turn_id - ): - return notification.payload - - def stream_until_methods(self, methods: Iterable[str] | str) -> list[Notification]: - target_methods = {methods} if isinstance(methods, str) else set(methods) - out: list[Notification] = [] - while True: - notification = self.next_notification() - out.append(notification) - if notification.method in target_methods: - return out - - def stream_text( - self, - thread_id: str, - text: str, - params: V2TurnStartParams | JsonObject | None = None, - ) -> Iterator[AgentMessageDeltaNotification]: - started = self.turn_start(thread_id, text, params=params) - turn_id = started.turn.id - while True: - notification = self.next_notification() - if ( - notification.method == "item/agentMessage/delta" - and isinstance(notification.payload, AgentMessageDeltaNotification) - and notification.payload.turn_id == turn_id - ): - yield notification.payload - continue - if ( - notification.method == "turn/completed" - and isinstance(notification.payload, TurnCompletedNotification) - and notification.payload.turn.id == turn_id - ): - break - - def _coerce_notification(self, method: str, params: object) -> Notification: - params_dict = params if isinstance(params, dict) else {} - - model = NOTIFICATION_MODELS.get(method) - if model is None: - return Notification(method=method, payload=UnknownNotification(params=params_dict)) - - try: - payload = model.model_validate(params_dict) - except Exception: # noqa: BLE001 - return Notification(method=method, payload=UnknownNotification(params=params_dict)) - return Notification(method=method, payload=payload) - - def _normalize_input_items( - self, - input_items: list[JsonObject] | JsonObject | str, - ) -> list[JsonObject]: - if isinstance(input_items, str): - return [{"type": "text", "text": input_items}] - if isinstance(input_items, dict): - return [input_items] - return input_items - - def _default_approval_handler(self, method: str, params: JsonObject | None) -> JsonObject: - if method == "item/commandExecution/requestApproval": - return {"decision": "accept"} - if method == "item/fileChange/requestApproval": - return {"decision": "accept"} - return {} - - def _start_stderr_drain_thread(self) -> None: - if self._proc is None or self._proc.stderr is None: - return - - def _drain() -> None: - stderr = self._proc.stderr - if stderr is None: - return - for line in stderr: - self._stderr_lines.append(line.rstrip("\n")) - - self._stderr_thread = threading.Thread(target=_drain, daemon=True) - self._stderr_thread.start() - - def _stderr_tail(self, limit: int = 40) -> str: - return "\n".join(list(self._stderr_lines)[-limit:]) - - def _handle_server_request(self, msg: dict[str, JsonValue]) -> JsonObject: - method = msg["method"] - params = msg.get("params") - if not isinstance(method, str): - return {} - return self._approval_handler( - method, - params if isinstance(params, dict) else None, - ) - - def _write_message(self, payload: JsonObject) -> None: - if self._proc is None or self._proc.stdin is None: - raise TransportClosedError("app-server is not running") - with self._lock: - self._proc.stdin.write(json.dumps(payload) + "\n") - self._proc.stdin.flush() - - def _read_message(self) -> dict[str, JsonValue]: - if self._proc is None or self._proc.stdout is None: - raise TransportClosedError("app-server is not running") - - line = self._proc.stdout.readline() - if not line: - raise TransportClosedError( - f"app-server closed stdout. stderr_tail={self._stderr_tail()[:2000]}" - ) - - try: - message = json.loads(line) - except json.JSONDecodeError as exc: - raise AppServerError(f"Invalid JSON-RPC line: {line!r}") from exc - - if not isinstance(message, dict): - raise AppServerError(f"Invalid JSON-RPC payload: {message!r}") - return message - - -def default_codex_home() -> str: - return str(Path.home() / ".codex") diff --git a/vendor/codex/sdk/python/src/codex_app_server/errors.py b/vendor/codex/sdk/python/src/codex_app_server/errors.py deleted file mode 100644 index 24972e4f..00000000 --- a/vendor/codex/sdk/python/src/codex_app_server/errors.py +++ /dev/null @@ -1,125 +0,0 @@ -from __future__ import annotations - -from typing import Any - - -class AppServerError(Exception): - """Base exception for SDK errors.""" - - -class JsonRpcError(AppServerError): - """Raw JSON-RPC error wrapper from the server.""" - - def __init__(self, code: int, message: str, data: Any = None): - super().__init__(f"JSON-RPC error {code}: {message}") - self.code = code - self.message = message - self.data = data - - -class TransportClosedError(AppServerError): - """Raised when the app-server transport closes unexpectedly.""" - - -class AppServerRpcError(JsonRpcError): - """Base typed error for JSON-RPC failures.""" - - -class ParseError(AppServerRpcError): - pass - - -class InvalidRequestError(AppServerRpcError): - pass - - -class MethodNotFoundError(AppServerRpcError): - pass - - -class InvalidParamsError(AppServerRpcError): - pass - - -class InternalRpcError(AppServerRpcError): - pass - - -class ServerBusyError(AppServerRpcError): - """Server is overloaded / unavailable and caller should retry.""" - - -class RetryLimitExceededError(ServerBusyError): - """Server exhausted internal retry budget for a retryable operation.""" - - -def _contains_retry_limit_text(message: str) -> bool: - lowered = message.lower() - return "retry limit" in lowered or "too many failed attempts" in lowered - - -def _is_server_overloaded(data: Any) -> bool: - if data is None: - return False - - if isinstance(data, str): - return data.lower() == "server_overloaded" - - if isinstance(data, dict): - direct = ( - data.get("codex_error_info") - or data.get("codexErrorInfo") - or data.get("errorInfo") - ) - if isinstance(direct, str) and direct.lower() == "server_overloaded": - return True - if isinstance(direct, dict): - for value in direct.values(): - if isinstance(value, str) and value.lower() == "server_overloaded": - return True - for value in data.values(): - if _is_server_overloaded(value): - return True - - if isinstance(data, list): - return any(_is_server_overloaded(value) for value in data) - - return False - - -def map_jsonrpc_error(code: int, message: str, data: Any = None) -> JsonRpcError: - """Map a raw JSON-RPC error into a richer SDK exception class.""" - - if code == -32700: - return ParseError(code, message, data) - if code == -32600: - return InvalidRequestError(code, message, data) - if code == -32601: - return MethodNotFoundError(code, message, data) - if code == -32602: - return InvalidParamsError(code, message, data) - if code == -32603: - return InternalRpcError(code, message, data) - - if -32099 <= code <= -32000: - if _is_server_overloaded(data): - if _contains_retry_limit_text(message): - return RetryLimitExceededError(code, message, data) - return ServerBusyError(code, message, data) - if _contains_retry_limit_text(message): - return RetryLimitExceededError(code, message, data) - return AppServerRpcError(code, message, data) - - return JsonRpcError(code, message, data) - - -def is_retryable_error(exc: BaseException) -> bool: - """True if the exception is a transient overload-style error.""" - - if isinstance(exc, ServerBusyError): - return True - - if isinstance(exc, JsonRpcError): - return _is_server_overloaded(exc.data) - - return False diff --git a/vendor/codex/sdk/python/src/codex_app_server/generated/__init__.py b/vendor/codex/sdk/python/src/codex_app_server/generated/__init__.py deleted file mode 100644 index d7b3f674..00000000 --- a/vendor/codex/sdk/python/src/codex_app_server/generated/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Auto-generated Python types derived from the app-server schemas.""" diff --git a/vendor/codex/sdk/python/src/codex_app_server/generated/notification_registry.py b/vendor/codex/sdk/python/src/codex_app_server/generated/notification_registry.py deleted file mode 100644 index ab6f87f1..00000000 --- a/vendor/codex/sdk/python/src/codex_app_server/generated/notification_registry.py +++ /dev/null @@ -1,122 +0,0 @@ -# Auto-generated by scripts/update_sdk_artifacts.py -# DO NOT EDIT MANUALLY. - -from __future__ import annotations - -from pydantic import BaseModel - -from .v2_all import AccountLoginCompletedNotification -from .v2_all import AccountRateLimitsUpdatedNotification -from .v2_all import AccountUpdatedNotification -from .v2_all import AgentMessageDeltaNotification -from .v2_all import AppListUpdatedNotification -from .v2_all import CommandExecOutputDeltaNotification -from .v2_all import CommandExecutionOutputDeltaNotification -from .v2_all import ConfigWarningNotification -from .v2_all import ContextCompactedNotification -from .v2_all import DeprecationNoticeNotification -from .v2_all import ErrorNotification -from .v2_all import ExternalAgentConfigImportCompletedNotification -from .v2_all import FileChangeOutputDeltaNotification -from .v2_all import FileChangePatchUpdatedNotification -from .v2_all import FsChangedNotification -from .v2_all import FuzzyFileSearchSessionCompletedNotification -from .v2_all import FuzzyFileSearchSessionUpdatedNotification -from .v2_all import HookCompletedNotification -from .v2_all import HookStartedNotification -from .v2_all import ItemCompletedNotification -from .v2_all import ItemGuardianApprovalReviewCompletedNotification -from .v2_all import ItemGuardianApprovalReviewStartedNotification -from .v2_all import ItemStartedNotification -from .v2_all import McpServerOauthLoginCompletedNotification -from .v2_all import McpServerStatusUpdatedNotification -from .v2_all import McpToolCallProgressNotification -from .v2_all import ModelReroutedNotification -from .v2_all import PlanDeltaNotification -from .v2_all import ReasoningSummaryPartAddedNotification -from .v2_all import ReasoningSummaryTextDeltaNotification -from .v2_all import ReasoningTextDeltaNotification -from .v2_all import ServerRequestResolvedNotification -from .v2_all import SkillsChangedNotification -from .v2_all import TerminalInteractionNotification -from .v2_all import ThreadArchivedNotification -from .v2_all import ThreadClosedNotification -from .v2_all import ThreadNameUpdatedNotification -from .v2_all import ThreadRealtimeClosedNotification -from .v2_all import ThreadRealtimeErrorNotification -from .v2_all import ThreadRealtimeItemAddedNotification -from .v2_all import ThreadRealtimeOutputAudioDeltaNotification -from .v2_all import ThreadRealtimeSdpNotification -from .v2_all import ThreadRealtimeStartedNotification -from .v2_all import ThreadRealtimeTranscriptDeltaNotification -from .v2_all import ThreadRealtimeTranscriptDoneNotification -from .v2_all import ThreadStartedNotification -from .v2_all import ThreadStatusChangedNotification -from .v2_all import ThreadTokenUsageUpdatedNotification -from .v2_all import ThreadUnarchivedNotification -from .v2_all import TurnCompletedNotification -from .v2_all import TurnDiffUpdatedNotification -from .v2_all import TurnPlanUpdatedNotification -from .v2_all import TurnStartedNotification -from .v2_all import WarningNotification -from .v2_all import WindowsSandboxSetupCompletedNotification -from .v2_all import WindowsWorldWritableWarningNotification - -NOTIFICATION_MODELS: dict[str, type[BaseModel]] = { - "account/login/completed": AccountLoginCompletedNotification, - "account/rateLimits/updated": AccountRateLimitsUpdatedNotification, - "account/updated": AccountUpdatedNotification, - "app/list/updated": AppListUpdatedNotification, - "command/exec/outputDelta": CommandExecOutputDeltaNotification, - "configWarning": ConfigWarningNotification, - "deprecationNotice": DeprecationNoticeNotification, - "error": ErrorNotification, - "externalAgentConfig/import/completed": ExternalAgentConfigImportCompletedNotification, - "fs/changed": FsChangedNotification, - "fuzzyFileSearch/sessionCompleted": FuzzyFileSearchSessionCompletedNotification, - "fuzzyFileSearch/sessionUpdated": FuzzyFileSearchSessionUpdatedNotification, - "hook/completed": HookCompletedNotification, - "hook/started": HookStartedNotification, - "item/agentMessage/delta": AgentMessageDeltaNotification, - "item/autoApprovalReview/completed": ItemGuardianApprovalReviewCompletedNotification, - "item/autoApprovalReview/started": ItemGuardianApprovalReviewStartedNotification, - "item/commandExecution/outputDelta": CommandExecutionOutputDeltaNotification, - "item/commandExecution/terminalInteraction": TerminalInteractionNotification, - "item/completed": ItemCompletedNotification, - "item/fileChange/outputDelta": FileChangeOutputDeltaNotification, - "item/fileChange/patchUpdated": FileChangePatchUpdatedNotification, - "item/mcpToolCall/progress": McpToolCallProgressNotification, - "item/plan/delta": PlanDeltaNotification, - "item/reasoning/summaryPartAdded": ReasoningSummaryPartAddedNotification, - "item/reasoning/summaryTextDelta": ReasoningSummaryTextDeltaNotification, - "item/reasoning/textDelta": ReasoningTextDeltaNotification, - "item/started": ItemStartedNotification, - "mcpServer/oauthLogin/completed": McpServerOauthLoginCompletedNotification, - "mcpServer/startupStatus/updated": McpServerStatusUpdatedNotification, - "model/rerouted": ModelReroutedNotification, - "serverRequest/resolved": ServerRequestResolvedNotification, - "skills/changed": SkillsChangedNotification, - "thread/archived": ThreadArchivedNotification, - "thread/closed": ThreadClosedNotification, - "thread/compacted": ContextCompactedNotification, - "thread/name/updated": ThreadNameUpdatedNotification, - "thread/realtime/closed": ThreadRealtimeClosedNotification, - "thread/realtime/error": ThreadRealtimeErrorNotification, - "thread/realtime/itemAdded": ThreadRealtimeItemAddedNotification, - "thread/realtime/outputAudio/delta": ThreadRealtimeOutputAudioDeltaNotification, - "thread/realtime/sdp": ThreadRealtimeSdpNotification, - "thread/realtime/started": ThreadRealtimeStartedNotification, - "thread/realtime/transcript/delta": ThreadRealtimeTranscriptDeltaNotification, - "thread/realtime/transcript/done": ThreadRealtimeTranscriptDoneNotification, - "thread/started": ThreadStartedNotification, - "thread/status/changed": ThreadStatusChangedNotification, - "thread/tokenUsage/updated": ThreadTokenUsageUpdatedNotification, - "thread/unarchived": ThreadUnarchivedNotification, - "turn/completed": TurnCompletedNotification, - "turn/diff/updated": TurnDiffUpdatedNotification, - "turn/plan/updated": TurnPlanUpdatedNotification, - "turn/started": TurnStartedNotification, - "warning": WarningNotification, - "windows/worldWritableWarning": WindowsWorldWritableWarningNotification, - "windowsSandbox/setupCompleted": WindowsSandboxSetupCompletedNotification, -} diff --git a/vendor/codex/sdk/python/src/codex_app_server/generated/v2_all.py b/vendor/codex/sdk/python/src/codex_app_server/generated/v2_all.py deleted file mode 100644 index c75b3e89..00000000 --- a/vendor/codex/sdk/python/src/codex_app_server/generated/v2_all.py +++ /dev/null @@ -1,7764 +0,0 @@ -# generated by datamodel-codegen: -# filename: codex_app_server_protocol.v2.schemas.json - -from __future__ import annotations -from pydantic import BaseModel, ConfigDict, Field, RootModel -from typing import Annotated, Any, Literal -from enum import Enum - - -class CodexAppServerProtocolV2(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class AbsolutePathBuf(RootModel[str]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: Annotated[ - str, - Field( - description="A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute." - ), - ] - - -class ApiKeyAccount(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[Literal["apiKey"], Field(title="ApiKeyAccountType")] - - -class AccountLoginCompletedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - error: str | None = None - login_id: Annotated[str | None, Field(alias="loginId")] = None - success: bool - - -class AddCreditsNudgeCreditType(Enum): - credits = "credits" - usage_limit = "usage_limit" - - -class AddCreditsNudgeEmailStatus(Enum): - sent = "sent" - cooldown_active = "cooldown_active" - - -class AdditionalNetworkPermissions(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - enabled: bool | None = None - - -class AgentMessageDeltaNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - delta: str - item_id: Annotated[str, Field(alias="itemId")] - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class AgentPath(RootModel[str]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: str - - -class AnalyticsConfig(BaseModel): - model_config = ConfigDict( - extra="allow", - populate_by_name=True, - ) - enabled: bool | None = None - - -class AppBranding(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - category: str | None = None - developer: str | None = None - is_discoverable_app: Annotated[bool, Field(alias="isDiscoverableApp")] - privacy_policy: Annotated[str | None, Field(alias="privacyPolicy")] = None - terms_of_service: Annotated[str | None, Field(alias="termsOfService")] = None - website: str | None = None - - -class AppReview(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - status: str - - -class AppScreenshot(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - file_id: Annotated[str | None, Field(alias="fileId")] = None - url: str | None = None - user_prompt: Annotated[str, Field(alias="userPrompt")] - - -class AppSummary(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - description: str | None = None - id: str - install_url: Annotated[str | None, Field(alias="installUrl")] = None - name: str - needs_auth: Annotated[bool, Field(alias="needsAuth")] - - -class AppToolApproval(Enum): - auto = "auto" - prompt = "prompt" - approve = "approve" - - -class AppToolConfig(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - approval_mode: AppToolApproval | None = None - enabled: bool | None = None - - -class AppToolsConfig(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class ApprovalsReviewer(Enum): - user = "user" - guardian_subagent = "guardian_subagent" - - -class AppsDefaultConfig(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - destructive_enabled: bool | None = True - enabled: bool | None = True - open_world_enabled: bool | None = True - - -class AppsListParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cursor: Annotated[ - str | None, - Field(description="Opaque pagination cursor returned by a previous call."), - ] = None - force_refetch: Annotated[ - bool | None, - Field( - alias="forceRefetch", - description="When true, bypass app caches and fetch the latest data from sources.", - ), - ] = None - limit: Annotated[ - int | None, - Field( - description="Optional page size; defaults to a reasonable server-side value.", - ge=0, - ), - ] = None - thread_id: Annotated[ - str | None, - Field( - alias="threadId", - description="Optional thread id used to evaluate app feature gating from that thread's config.", - ), - ] = None - - -class AskForApprovalValue(Enum): - untrusted = "untrusted" - on_failure = "on-failure" - on_request = "on-request" - never = "never" - - -class Granular(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - mcp_elicitations: bool - request_permissions: bool | None = False - rules: bool - sandbox_approval: bool - skill_approval: bool | None = False - - -class GranularAskForApproval(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - granular: Granular - - -class AskForApproval(RootModel[AskForApprovalValue | GranularAskForApproval]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: AskForApprovalValue | GranularAskForApproval - - -class AuthMode(Enum): - apikey = "apikey" - chatgpt = "chatgpt" - chatgpt_auth_tokens = "chatgptAuthTokens" - - -class AutoReviewDecisionSource(RootModel[Literal["agent"]]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: Annotated[ - Literal["agent"], - Field( - description="[UNSTABLE] Source that produced a terminal approval auto-review decision." - ), - ] - - -class ByteRange(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - end: Annotated[int, Field(ge=0)] - start: Annotated[int, Field(ge=0)] - - -class CancelLoginAccountParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - login_id: Annotated[str, Field(alias="loginId")] - - -class CancelLoginAccountStatus(Enum): - canceled = "canceled" - not_found = "notFound" - - -class ClientInfo(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - name: str - title: str | None = None - version: str - - -class CodexErrorInfoValue(Enum): - context_window_exceeded = "contextWindowExceeded" - usage_limit_exceeded = "usageLimitExceeded" - server_overloaded = "serverOverloaded" - internal_server_error = "internalServerError" - unauthorized = "unauthorized" - bad_request = "badRequest" - thread_rollback_failed = "threadRollbackFailed" - sandbox_error = "sandboxError" - other = "other" - - -class HttpConnectionFailed(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - http_status_code: Annotated[int | None, Field(alias="httpStatusCode", ge=0)] = None - - -class HttpConnectionFailedCodexErrorInfo(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - http_connection_failed: Annotated[ - HttpConnectionFailed, Field(alias="httpConnectionFailed") - ] - - -class ResponseStreamConnectionFailed(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - http_status_code: Annotated[int | None, Field(alias="httpStatusCode", ge=0)] = None - - -class ResponseStreamConnectionFailedCodexErrorInfo(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - response_stream_connection_failed: Annotated[ - ResponseStreamConnectionFailed, Field(alias="responseStreamConnectionFailed") - ] - - -class ResponseStreamDisconnected(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - http_status_code: Annotated[int | None, Field(alias="httpStatusCode", ge=0)] = None - - -class ResponseStreamDisconnectedCodexErrorInfo(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - response_stream_disconnected: Annotated[ - ResponseStreamDisconnected, Field(alias="responseStreamDisconnected") - ] - - -class ResponseTooManyFailedAttempts(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - http_status_code: Annotated[int | None, Field(alias="httpStatusCode", ge=0)] = None - - -class ResponseTooManyFailedAttemptsCodexErrorInfo(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - response_too_many_failed_attempts: Annotated[ - ResponseTooManyFailedAttempts, Field(alias="responseTooManyFailedAttempts") - ] - - -class CollabAgentStatus(Enum): - pending_init = "pendingInit" - running = "running" - interrupted = "interrupted" - completed = "completed" - errored = "errored" - shutdown = "shutdown" - not_found = "notFound" - - -class CollabAgentTool(Enum): - spawn_agent = "spawnAgent" - send_input = "sendInput" - resume_agent = "resumeAgent" - wait = "wait" - close_agent = "closeAgent" - - -class CollabAgentToolCallStatus(Enum): - in_progress = "inProgress" - completed = "completed" - failed = "failed" - - -class ReadCommandAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - command: str - name: str - path: AbsolutePathBuf - type: Annotated[Literal["read"], Field(title="ReadCommandActionType")] - - -class ListFilesCommandAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - command: str - path: str | None = None - type: Annotated[Literal["listFiles"], Field(title="ListFilesCommandActionType")] - - -class SearchCommandAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - command: str - path: str | None = None - query: str | None = None - type: Annotated[Literal["search"], Field(title="SearchCommandActionType")] - - -class UnknownCommandAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - command: str - type: Annotated[Literal["unknown"], Field(title="UnknownCommandActionType")] - - -class CommandAction( - RootModel[ - ReadCommandAction - | ListFilesCommandAction - | SearchCommandAction - | UnknownCommandAction - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ( - ReadCommandAction - | ListFilesCommandAction - | SearchCommandAction - | UnknownCommandAction - ) - - -class CommandExecOutputStream(Enum): - stdout = "stdout" - stderr = "stderr" - - -class CommandExecResizeResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class CommandExecResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - exit_code: Annotated[int, Field(alias="exitCode", description="Process exit code.")] - stderr: Annotated[ - str, - Field( - description="Buffered stderr capture.\n\nEmpty when stderr was streamed via `command/exec/outputDelta`." - ), - ] - stdout: Annotated[ - str, - Field( - description="Buffered stdout capture.\n\nEmpty when stdout was streamed via `command/exec/outputDelta`." - ), - ] - - -class CommandExecTerminalSize(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cols: Annotated[int, Field(description="Terminal width in character cells.", ge=0)] - rows: Annotated[int, Field(description="Terminal height in character cells.", ge=0)] - - -class CommandExecTerminateParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - process_id: Annotated[ - str, - Field( - alias="processId", - description="Client-supplied, connection-scoped `processId` from the original `command/exec` request.", - ), - ] - - -class CommandExecTerminateResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class CommandExecWriteParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - close_stdin: Annotated[ - bool | None, - Field( - alias="closeStdin", - description="Close stdin after writing `deltaBase64`, if present.", - ), - ] = None - delta_base64: Annotated[ - str | None, - Field( - alias="deltaBase64", - description="Optional base64-encoded stdin bytes to write.", - ), - ] = None - process_id: Annotated[ - str, - Field( - alias="processId", - description="Client-supplied, connection-scoped `processId` from the original `command/exec` request.", - ), - ] - - -class CommandExecWriteResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class CommandExecutionOutputDeltaNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - delta: str - item_id: Annotated[str, Field(alias="itemId")] - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class CommandExecutionSource(Enum): - agent = "agent" - user_shell = "userShell" - unified_exec_startup = "unifiedExecStartup" - unified_exec_interaction = "unifiedExecInteraction" - - -class CommandExecutionStatus(Enum): - in_progress = "inProgress" - completed = "completed" - failed = "failed" - declined = "declined" - - -class MdmConfigLayerSource(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - domain: str - key: str - type: Annotated[Literal["mdm"], Field(title="MdmConfigLayerSourceType")] - - -class SystemConfigLayerSource(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - file: Annotated[ - AbsolutePathBuf, - Field( - description="This is the path to the system config.toml file, though it is not guaranteed to exist." - ), - ] - type: Annotated[Literal["system"], Field(title="SystemConfigLayerSourceType")] - - -class UserConfigLayerSource(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - file: Annotated[ - AbsolutePathBuf, - Field( - description="This is the path to the user's config.toml file, though it is not guaranteed to exist." - ), - ] - type: Annotated[Literal["user"], Field(title="UserConfigLayerSourceType")] - - -class ProjectConfigLayerSource(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - dot_codex_folder: Annotated[AbsolutePathBuf, Field(alias="dotCodexFolder")] - type: Annotated[Literal["project"], Field(title="ProjectConfigLayerSourceType")] - - -class SessionFlagsConfigLayerSource(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[ - Literal["sessionFlags"], Field(title="SessionFlagsConfigLayerSourceType") - ] - - -class LegacyManagedConfigTomlFromFileConfigLayerSource(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - file: AbsolutePathBuf - type: Annotated[ - Literal["legacyManagedConfigTomlFromFile"], - Field(title="LegacyManagedConfigTomlFromFileConfigLayerSourceType"), - ] - - -class LegacyManagedConfigTomlFromMdmConfigLayerSource(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[ - Literal["legacyManagedConfigTomlFromMdm"], - Field(title="LegacyManagedConfigTomlFromMdmConfigLayerSourceType"), - ] - - -class ConfigLayerSource( - RootModel[ - MdmConfigLayerSource - | SystemConfigLayerSource - | UserConfigLayerSource - | ProjectConfigLayerSource - | SessionFlagsConfigLayerSource - | LegacyManagedConfigTomlFromFileConfigLayerSource - | LegacyManagedConfigTomlFromMdmConfigLayerSource - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ( - MdmConfigLayerSource - | SystemConfigLayerSource - | UserConfigLayerSource - | ProjectConfigLayerSource - | SessionFlagsConfigLayerSource - | LegacyManagedConfigTomlFromFileConfigLayerSource - | LegacyManagedConfigTomlFromMdmConfigLayerSource - ) - - -class ConfigReadParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cwd: Annotated[ - str | None, - Field( - description="Optional working directory to resolve project config layers. If specified, return the effective config as seen from that directory (i.e., including any project layers between `cwd` and the project/repo root)." - ), - ] = None - include_layers: Annotated[bool | None, Field(alias="includeLayers")] = False - - -class InputTextContentItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - text: str - type: Annotated[Literal["input_text"], Field(title="InputTextContentItemType")] - - -class OutputTextContentItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - text: str - type: Annotated[Literal["output_text"], Field(title="OutputTextContentItemType")] - - -class ContextCompactedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class CreditsSnapshot(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - balance: str | None = None - has_credits: Annotated[bool, Field(alias="hasCredits")] - unlimited: bool - - -class DeprecationNoticeNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - details: Annotated[ - str | None, - Field( - description="Optional extra guidance, such as migration steps or rationale." - ), - ] = None - summary: Annotated[str, Field(description="Concise summary of what is deprecated.")] - - -class InputTextDynamicToolCallOutputContentItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - text: str - type: Annotated[ - Literal["inputText"], - Field(title="InputTextDynamicToolCallOutputContentItemType"), - ] - - -class InputImageDynamicToolCallOutputContentItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - image_url: Annotated[str, Field(alias="imageUrl")] - type: Annotated[ - Literal["inputImage"], - Field(title="InputImageDynamicToolCallOutputContentItemType"), - ] - - -class DynamicToolCallOutputContentItem( - RootModel[ - InputTextDynamicToolCallOutputContentItem - | InputImageDynamicToolCallOutputContentItem - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ( - InputTextDynamicToolCallOutputContentItem - | InputImageDynamicToolCallOutputContentItem - ) - - -class DynamicToolCallStatus(Enum): - in_progress = "inProgress" - completed = "completed" - failed = "failed" - - -class DynamicToolSpec(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - defer_loading: Annotated[bool | None, Field(alias="deferLoading")] = None - description: str - input_schema: Annotated[Any, Field(alias="inputSchema")] - name: str - namespace: str | None = None - - -class ExperimentalFeatureEnablementSetParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - enablement: Annotated[ - dict[str, bool], - Field( - description="Process-wide runtime feature enablement keyed by canonical feature name.\n\nOnly named features are updated. Omitted features are left unchanged. Send an empty map for a no-op." - ), - ] - - -class ExperimentalFeatureEnablementSetResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - enablement: Annotated[ - dict[str, bool], - Field(description="Feature enablement entries updated by this request."), - ] - - -class ExperimentalFeatureListParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cursor: Annotated[ - str | None, - Field(description="Opaque pagination cursor returned by a previous call."), - ] = None - limit: Annotated[ - int | None, - Field( - description="Optional page size; defaults to a reasonable server-side value.", - ge=0, - ), - ] = None - - -class ExperimentalFeatureStage(Enum): - beta = "beta" - under_development = "underDevelopment" - stable = "stable" - deprecated = "deprecated" - removed = "removed" - - -class ExternalAgentConfigDetectParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cwds: Annotated[ - list[str] | None, - Field( - description="Zero or more working directories to include for repo-scoped detection." - ), - ] = None - include_home: Annotated[ - bool | None, - Field( - alias="includeHome", - description="If true, include detection under the user's home (~/.claude, ~/.codex, etc.).", - ), - ] = None - - -class ExternalAgentConfigImportCompletedNotification(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class ExternalAgentConfigImportResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class ExternalAgentConfigMigrationItemType(Enum): - agents_md = "AGENTS_MD" - config = "CONFIG" - skills = "SKILLS" - plugins = "PLUGINS" - mcp_server_config = "MCP_SERVER_CONFIG" - - -class FeedbackUploadParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - classification: str - extra_log_files: Annotated[list[str] | None, Field(alias="extraLogFiles")] = None - include_logs: Annotated[bool, Field(alias="includeLogs")] - reason: str | None = None - tags: dict[str, Any] | None = None - thread_id: Annotated[str | None, Field(alias="threadId")] = None - - -class FeedbackUploadResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread_id: Annotated[str, Field(alias="threadId")] - - -class FileChangeOutputDeltaNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - delta: str - item_id: Annotated[str, Field(alias="itemId")] - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class FileSystemAccessMode(Enum): - read = "read" - write = "write" - none = "none" - - -class PathFileSystemPath(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - path: AbsolutePathBuf - type: Annotated[Literal["path"], Field(title="PathFileSystemPathType")] - - -class GlobPatternFileSystemPath(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - pattern: str - type: Annotated[ - Literal["glob_pattern"], Field(title="GlobPatternFileSystemPathType") - ] - - -class RootFileSystemSpecialPath(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - kind: Literal["root"] - - -class MinimalFileSystemSpecialPath(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - kind: Literal["minimal"] - - -class CurrentWorkingDirectoryFileSystemSpecialPath(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - kind: Literal["current_working_directory"] - - -class KindFileSystemSpecialPath(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - kind: Literal["project_roots"] - subpath: str | None = None - - -class TmpdirFileSystemSpecialPath(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - kind: Literal["tmpdir"] - - -class SlashTmpFileSystemSpecialPath(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - kind: Literal["slash_tmp"] - - -class FileSystemSpecialPath1(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - kind: Literal["unknown"] - path: str - subpath: str | None = None - - -class FileSystemSpecialPath( - RootModel[ - RootFileSystemSpecialPath - | MinimalFileSystemSpecialPath - | CurrentWorkingDirectoryFileSystemSpecialPath - | KindFileSystemSpecialPath - | TmpdirFileSystemSpecialPath - | SlashTmpFileSystemSpecialPath - | FileSystemSpecialPath1 - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ( - RootFileSystemSpecialPath - | MinimalFileSystemSpecialPath - | CurrentWorkingDirectoryFileSystemSpecialPath - | KindFileSystemSpecialPath - | TmpdirFileSystemSpecialPath - | SlashTmpFileSystemSpecialPath - | FileSystemSpecialPath1 - ) - - -class ForcedLoginMethod(Enum): - chatgpt = "chatgpt" - api = "api" - - -class FsChangedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - changed_paths: Annotated[ - list[AbsolutePathBuf], - Field( - alias="changedPaths", - description="File or directory paths associated with this event.", - ), - ] - watch_id: Annotated[ - str, - Field( - alias="watchId", - description="Watch identifier previously provided to `fs/watch`.", - ), - ] - - -class FsCopyParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - destination_path: Annotated[ - AbsolutePathBuf, - Field(alias="destinationPath", description="Absolute destination path."), - ] - recursive: Annotated[ - bool | None, - Field(description="Required for directory copies; ignored for file copies."), - ] = None - source_path: Annotated[ - AbsolutePathBuf, Field(alias="sourcePath", description="Absolute source path.") - ] - - -class FsCopyResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class FsCreateDirectoryParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - path: Annotated[ - AbsolutePathBuf, Field(description="Absolute directory path to create.") - ] - recursive: Annotated[ - bool | None, - Field( - description="Whether parent directories should also be created. Defaults to `true`." - ), - ] = None - - -class FsCreateDirectoryResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class FsGetMetadataParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - path: Annotated[AbsolutePathBuf, Field(description="Absolute path to inspect.")] - - -class FsGetMetadataResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - created_at_ms: Annotated[ - int, - Field( - alias="createdAtMs", - description="File creation time in Unix milliseconds when available, otherwise `0`.", - ), - ] - is_directory: Annotated[ - bool, - Field( - alias="isDirectory", description="Whether the path resolves to a directory." - ), - ] - is_file: Annotated[ - bool, - Field( - alias="isFile", description="Whether the path resolves to a regular file." - ), - ] - is_symlink: Annotated[ - bool, - Field( - alias="isSymlink", description="Whether the path itself is a symbolic link." - ), - ] - modified_at_ms: Annotated[ - int, - Field( - alias="modifiedAtMs", - description="File modification time in Unix milliseconds when available, otherwise `0`.", - ), - ] - - -class FsReadDirectoryEntry(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - file_name: Annotated[ - str, - Field( - alias="fileName", - description="Direct child entry name only, not an absolute or relative path.", - ), - ] - is_directory: Annotated[ - bool, - Field( - alias="isDirectory", - description="Whether this entry resolves to a directory.", - ), - ] - is_file: Annotated[ - bool, - Field( - alias="isFile", description="Whether this entry resolves to a regular file." - ), - ] - - -class FsReadDirectoryParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - path: Annotated[ - AbsolutePathBuf, Field(description="Absolute directory path to read.") - ] - - -class FsReadDirectoryResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - entries: Annotated[ - list[FsReadDirectoryEntry], - Field(description="Direct child entries in the requested directory."), - ] - - -class FsReadFileParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - path: Annotated[AbsolutePathBuf, Field(description="Absolute path to read.")] - - -class FsReadFileResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - data_base64: Annotated[ - str, Field(alias="dataBase64", description="File contents encoded as base64.") - ] - - -class FsRemoveParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - force: Annotated[ - bool | None, - Field( - description="Whether missing paths should be ignored. Defaults to `true`." - ), - ] = None - path: Annotated[AbsolutePathBuf, Field(description="Absolute path to remove.")] - recursive: Annotated[ - bool | None, - Field( - description="Whether directory removal should recurse. Defaults to `true`." - ), - ] = None - - -class FsRemoveResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class FsUnwatchParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - watch_id: Annotated[ - str, - Field( - alias="watchId", - description="Watch identifier previously provided to `fs/watch`.", - ), - ] - - -class FsUnwatchResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class FsWatchParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - path: Annotated[ - AbsolutePathBuf, Field(description="Absolute file or directory path to watch.") - ] - watch_id: Annotated[ - str, - Field( - alias="watchId", - description="Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.", - ), - ] - - -class FsWatchResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - path: Annotated[ - AbsolutePathBuf, - Field(description="Canonicalized path associated with the watch."), - ] - - -class FsWriteFileParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - data_base64: Annotated[ - str, Field(alias="dataBase64", description="File contents encoded as base64.") - ] - path: Annotated[AbsolutePathBuf, Field(description="Absolute path to write.")] - - -class FsWriteFileResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class InputTextFunctionCallOutputContentItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - text: str - type: Annotated[ - Literal["input_text"], Field(title="InputTextFunctionCallOutputContentItemType") - ] - - -class FuzzyFileSearchMatchType(Enum): - file = "file" - directory = "directory" - - -class FuzzyFileSearchParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cancellation_token: Annotated[str | None, Field(alias="cancellationToken")] = None - query: str - roots: list[str] - - -class Indice(RootModel[int]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: Annotated[int, Field(ge=0)] - - -class FuzzyFileSearchResult(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - file_name: str - indices: list[Indice] | None = None - match_type: FuzzyFileSearchMatchType - path: str - root: str - score: Annotated[int, Field(ge=0)] - - -class FuzzyFileSearchSessionCompletedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - session_id: Annotated[str, Field(alias="sessionId")] - - -class FuzzyFileSearchSessionUpdatedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - files: list[FuzzyFileSearchResult] - query: str - session_id: Annotated[str, Field(alias="sessionId")] - - -class GetAccountParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - refresh_token: Annotated[ - bool | None, - Field( - alias="refreshToken", - description="When `true`, requests a proactive token refresh before returning.\n\nIn managed auth mode this triggers the normal refresh-token flow. In external auth mode this flag is ignored. Clients should refresh tokens themselves and call `account/login/start` with `chatgptAuthTokens`.", - ), - ] = False - - -class GhostCommit(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: str - parent: str | None = None - preexisting_untracked_dirs: list[str] - preexisting_untracked_files: list[str] - - -class GitInfo(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - branch: str | None = None - origin_url: Annotated[str | None, Field(alias="originUrl")] = None - sha: str | None = None - - -class ApplyPatchGuardianApprovalReviewAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cwd: AbsolutePathBuf - files: list[AbsolutePathBuf] - type: Annotated[ - Literal["applyPatch"], Field(title="ApplyPatchGuardianApprovalReviewActionType") - ] - - -class McpToolCallGuardianApprovalReviewAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - connector_id: Annotated[str | None, Field(alias="connectorId")] = None - connector_name: Annotated[str | None, Field(alias="connectorName")] = None - server: str - tool_name: Annotated[str, Field(alias="toolName")] - tool_title: Annotated[str | None, Field(alias="toolTitle")] = None - type: Annotated[ - Literal["mcpToolCall"], - Field(title="McpToolCallGuardianApprovalReviewActionType"), - ] - - -class GuardianApprovalReviewStatus(Enum): - in_progress = "inProgress" - approved = "approved" - denied = "denied" - timed_out = "timedOut" - aborted = "aborted" - - -class GuardianCommandSource(Enum): - shell = "shell" - unified_exec = "unifiedExec" - - -class GuardianRiskLevel(Enum): - low = "low" - medium = "medium" - high = "high" - critical = "critical" - - -class GuardianUserAuthorization(Enum): - unknown = "unknown" - low = "low" - medium = "medium" - high = "high" - - -class HookEventName(Enum): - pre_tool_use = "preToolUse" - permission_request = "permissionRequest" - post_tool_use = "postToolUse" - session_start = "sessionStart" - user_prompt_submit = "userPromptSubmit" - stop = "stop" - - -class HookExecutionMode(Enum): - sync = "sync" - async_ = "async" - - -class HookHandlerType(Enum): - command = "command" - prompt = "prompt" - agent = "agent" - - -class HookOutputEntryKind(Enum): - warning = "warning" - stop = "stop" - feedback = "feedback" - context = "context" - error = "error" - - -class HookPromptFragment(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - hook_run_id: Annotated[str, Field(alias="hookRunId")] - text: str - - -class HookRunStatus(Enum): - running = "running" - completed = "completed" - failed = "failed" - blocked = "blocked" - stopped = "stopped" - - -class HookScope(Enum): - thread = "thread" - turn = "turn" - - -class HookSource(Enum): - system = "system" - user = "user" - project = "project" - mdm = "mdm" - session_flags = "sessionFlags" - legacy_managed_config_file = "legacyManagedConfigFile" - legacy_managed_config_mdm = "legacyManagedConfigMdm" - unknown = "unknown" - - -class ImageDetail(Enum): - auto = "auto" - low = "low" - high = "high" - original = "original" - - -class InitializeCapabilities(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - experimental_api: Annotated[ - bool | None, - Field( - alias="experimentalApi", - description="Opt into receiving experimental API methods and fields.", - ), - ] = False - opt_out_notification_methods: Annotated[ - list[str] | None, - Field( - alias="optOutNotificationMethods", - description="Exact notification method names that should be suppressed for this connection (for example `thread/started`).", - ), - ] = None - - -class InitializeParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - capabilities: InitializeCapabilities | None = None - client_info: Annotated[ClientInfo, Field(alias="clientInfo")] - - -class InputModality(Enum): - text = "text" - image = "image" - - -class ExecLocalShellAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - command: list[str] - env: dict[str, Any] | None = None - timeout_ms: Annotated[int | None, Field(ge=0)] = None - type: Annotated[Literal["exec"], Field(title="ExecLocalShellActionType")] - user: str | None = None - working_directory: str | None = None - - -class LocalShellAction(RootModel[ExecLocalShellAction]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ExecLocalShellAction - - -class LocalShellStatus(Enum): - completed = "completed" - in_progress = "in_progress" - incomplete = "incomplete" - - -class ApiKeyLoginAccountParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - api_key: Annotated[str, Field(alias="apiKey")] - type: Annotated[Literal["apiKey"], Field(title="ApiKeyv2::LoginAccountParamsType")] - - -class ChatgptLoginAccountParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[ - Literal["chatgpt"], Field(title="Chatgptv2::LoginAccountParamsType") - ] - - -class ChatgptDeviceCodeLoginAccountParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[ - Literal["chatgptDeviceCode"], - Field(title="ChatgptDeviceCodev2::LoginAccountParamsType"), - ] - - -class ChatgptAuthTokensLoginAccountParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - access_token: Annotated[ - str, - Field( - alias="accessToken", - description="Access token (JWT) supplied by the client. This token is used for backend API requests and email extraction.", - ), - ] - chatgpt_account_id: Annotated[ - str, - Field( - alias="chatgptAccountId", - description="Workspace/account identifier supplied by the client.", - ), - ] - chatgpt_plan_type: Annotated[ - str | None, - Field( - alias="chatgptPlanType", - description="Optional plan type supplied by the client.\n\nWhen `null`, Codex attempts to derive the plan type from access-token claims. If unavailable, the plan defaults to `unknown`.", - ), - ] = None - type: Annotated[ - Literal["chatgptAuthTokens"], - Field(title="ChatgptAuthTokensv2::LoginAccountParamsType"), - ] - - -class LoginAccountParams( - RootModel[ - ApiKeyLoginAccountParams - | ChatgptLoginAccountParams - | ChatgptDeviceCodeLoginAccountParams - | ChatgptAuthTokensLoginAccountParams - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: Annotated[ - ApiKeyLoginAccountParams - | ChatgptLoginAccountParams - | ChatgptDeviceCodeLoginAccountParams - | ChatgptAuthTokensLoginAccountParams, - Field(title="LoginAccountParams"), - ] - - -class ApiKeyLoginAccountResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[ - Literal["apiKey"], Field(title="ApiKeyv2::LoginAccountResponseType") - ] - - -class ChatgptLoginAccountResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - auth_url: Annotated[ - str, - Field( - alias="authUrl", - description="URL the client should open in a browser to initiate the OAuth flow.", - ), - ] - login_id: Annotated[str, Field(alias="loginId")] - type: Annotated[ - Literal["chatgpt"], Field(title="Chatgptv2::LoginAccountResponseType") - ] - - -class ChatgptDeviceCodeLoginAccountResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - login_id: Annotated[str, Field(alias="loginId")] - type: Annotated[ - Literal["chatgptDeviceCode"], - Field(title="ChatgptDeviceCodev2::LoginAccountResponseType"), - ] - user_code: Annotated[ - str, - Field( - alias="userCode", - description="One-time code the user must enter after signing in.", - ), - ] - verification_url: Annotated[ - str, - Field( - alias="verificationUrl", - description="URL the client should open in a browser to complete device code authorization.", - ), - ] - - -class ChatgptAuthTokensLoginAccountResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[ - Literal["chatgptAuthTokens"], - Field(title="ChatgptAuthTokensv2::LoginAccountResponseType"), - ] - - -class LoginAccountResponse( - RootModel[ - ApiKeyLoginAccountResponse - | ChatgptLoginAccountResponse - | ChatgptDeviceCodeLoginAccountResponse - | ChatgptAuthTokensLoginAccountResponse - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: Annotated[ - ApiKeyLoginAccountResponse - | ChatgptLoginAccountResponse - | ChatgptDeviceCodeLoginAccountResponse - | ChatgptAuthTokensLoginAccountResponse, - Field(title="LoginAccountResponse"), - ] - - -class LogoutAccountResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class MarketplaceAddParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - ref_name: Annotated[str | None, Field(alias="refName")] = None - source: str - sparse_paths: Annotated[list[str] | None, Field(alias="sparsePaths")] = None - - -class MarketplaceAddResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - already_added: Annotated[bool, Field(alias="alreadyAdded")] - installed_root: Annotated[AbsolutePathBuf, Field(alias="installedRoot")] - marketplace_name: Annotated[str, Field(alias="marketplaceName")] - - -class MarketplaceInterface(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - display_name: Annotated[str | None, Field(alias="displayName")] = None - - -class MarketplaceLoadErrorInfo(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - marketplace_path: Annotated[AbsolutePathBuf, Field(alias="marketplacePath")] - message: str - - -class MarketplaceRemoveParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - marketplace_name: Annotated[str, Field(alias="marketplaceName")] - - -class MarketplaceRemoveResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - installed_root: Annotated[AbsolutePathBuf | None, Field(alias="installedRoot")] = ( - None - ) - marketplace_name: Annotated[str, Field(alias="marketplaceName")] - - -class McpAuthStatus(Enum): - unsupported = "unsupported" - not_logged_in = "notLoggedIn" - bearer_token = "bearerToken" - o_auth = "oAuth" - - -class McpResourceReadParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - server: str - thread_id: Annotated[str | None, Field(alias="threadId")] = None - uri: str - - -class McpServerOauthLoginCompletedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - error: str | None = None - name: str - success: bool - - -class McpServerOauthLoginParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - name: str - scopes: list[str] | None = None - timeout_secs: Annotated[int | None, Field(alias="timeoutSecs")] = None - - -class McpServerOauthLoginResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - authorization_url: Annotated[str, Field(alias="authorizationUrl")] - - -class McpServerRefreshResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class McpServerStartupState(Enum): - starting = "starting" - ready = "ready" - failed = "failed" - cancelled = "cancelled" - - -class McpServerStatusDetail(Enum): - full = "full" - tools_and_auth_only = "toolsAndAuthOnly" - - -class McpServerStatusUpdatedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - error: str | None = None - name: str - status: McpServerStartupState - - -class McpServerToolCallParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - field_meta: Annotated[Any | None, Field(alias="_meta")] = None - arguments: Any | None = None - server: str - thread_id: Annotated[str, Field(alias="threadId")] - tool: str - - -class McpServerToolCallResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - field_meta: Annotated[Any | None, Field(alias="_meta")] = None - content: list - is_error: Annotated[bool | None, Field(alias="isError")] = None - structured_content: Annotated[Any | None, Field(alias="structuredContent")] = None - - -class McpToolCallError(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - message: str - - -class McpToolCallProgressNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - item_id: Annotated[str, Field(alias="itemId")] - message: str - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class McpToolCallResult(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - field_meta: Annotated[Any | None, Field(alias="_meta")] = None - content: list - structured_content: Annotated[Any | None, Field(alias="structuredContent")] = None - - -class McpToolCallStatus(Enum): - in_progress = "inProgress" - completed = "completed" - failed = "failed" - - -class MemoryCitationEntry(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - line_end: Annotated[int, Field(alias="lineEnd", ge=0)] - line_start: Annotated[int, Field(alias="lineStart", ge=0)] - note: str - path: str - - -class MergeStrategy(Enum): - replace = "replace" - upsert = "upsert" - - -class MessagePhase(Enum): - commentary = "commentary" - final_answer = "final_answer" - - -class ModeKind(Enum): - plan = "plan" - default = "default" - - -class ModelAvailabilityNux(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - message: str - - -class ModelListParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cursor: Annotated[ - str | None, - Field(description="Opaque pagination cursor returned by a previous call."), - ] = None - include_hidden: Annotated[ - bool | None, - Field( - alias="includeHidden", - description="When true, include models that are hidden from the default picker list.", - ), - ] = None - limit: Annotated[ - int | None, - Field( - description="Optional page size; defaults to a reasonable server-side value.", - ge=0, - ), - ] = None - - -class ModelRerouteReason(RootModel[Literal["highRiskCyberActivity"]]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: Literal["highRiskCyberActivity"] - - -class ModelReroutedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - from_model: Annotated[str, Field(alias="fromModel")] - reason: ModelRerouteReason - thread_id: Annotated[str, Field(alias="threadId")] - to_model: Annotated[str, Field(alias="toModel")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class ModelUpgradeInfo(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - migration_markdown: Annotated[str | None, Field(alias="migrationMarkdown")] = None - model: str - model_link: Annotated[str | None, Field(alias="modelLink")] = None - upgrade_copy: Annotated[str | None, Field(alias="upgradeCopy")] = None - - -class NetworkAccess(Enum): - restricted = "restricted" - enabled = "enabled" - - -class NetworkApprovalProtocol(Enum): - http = "http" - https = "https" - socks5_tcp = "socks5Tcp" - socks5_udp = "socks5Udp" - - -class NetworkDomainPermission(Enum): - allow = "allow" - deny = "deny" - - -class NetworkRequirements(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - allow_local_binding: Annotated[bool | None, Field(alias="allowLocalBinding")] = None - allow_unix_sockets: Annotated[ - list[str] | None, - Field( - alias="allowUnixSockets", - description="Legacy compatibility view derived from `unix_sockets`.", - ), - ] = None - allow_upstream_proxy: Annotated[bool | None, Field(alias="allowUpstreamProxy")] = ( - None - ) - allowed_domains: Annotated[ - list[str] | None, - Field( - alias="allowedDomains", - description="Legacy compatibility view derived from `domains`.", - ), - ] = None - dangerously_allow_all_unix_sockets: Annotated[ - bool | None, Field(alias="dangerouslyAllowAllUnixSockets") - ] = None - dangerously_allow_non_loopback_proxy: Annotated[ - bool | None, Field(alias="dangerouslyAllowNonLoopbackProxy") - ] = None - denied_domains: Annotated[ - list[str] | None, - Field( - alias="deniedDomains", - description="Legacy compatibility view derived from `domains`.", - ), - ] = None - domains: Annotated[ - dict[str, Any] | None, - Field( - description="Canonical network permission map for `experimental_network`." - ), - ] = None - enabled: bool | None = None - http_port: Annotated[int | None, Field(alias="httpPort", ge=0)] = None - managed_allowed_domains_only: Annotated[ - bool | None, - Field( - alias="managedAllowedDomainsOnly", - description="When true, only managed allowlist entries are respected while managed network enforcement is active.", - ), - ] = None - socks_port: Annotated[int | None, Field(alias="socksPort", ge=0)] = None - unix_sockets: Annotated[ - dict[str, Any] | None, - Field( - alias="unixSockets", - description="Canonical unix socket permission map for `experimental_network`.", - ), - ] = None - - -class NetworkUnixSocketPermission(Enum): - allow = "allow" - none = "none" - - -class NonSteerableTurnKind(Enum): - review = "review" - compact = "compact" - - -class PatchApplyStatus(Enum): - in_progress = "inProgress" - completed = "completed" - failed = "failed" - declined = "declined" - - -class AddPatchChangeKind(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[Literal["add"], Field(title="AddPatchChangeKindType")] - - -class DeletePatchChangeKind(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[Literal["delete"], Field(title="DeletePatchChangeKindType")] - - -class UpdatePatchChangeKind(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - move_path: str | None = None - type: Annotated[Literal["update"], Field(title="UpdatePatchChangeKindType")] - - -class PatchChangeKind( - RootModel[AddPatchChangeKind | DeletePatchChangeKind | UpdatePatchChangeKind] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: AddPatchChangeKind | DeletePatchChangeKind | UpdatePatchChangeKind - - -class Personality(Enum): - none = "none" - friendly = "friendly" - pragmatic = "pragmatic" - - -class PlanDeltaNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - delta: str - item_id: Annotated[str, Field(alias="itemId")] - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class PlanType(Enum): - free = "free" - go = "go" - plus = "plus" - pro = "pro" - prolite = "prolite" - team = "team" - self_serve_business_usage_based = "self_serve_business_usage_based" - business = "business" - enterprise_cbp_usage_based = "enterprise_cbp_usage_based" - enterprise = "enterprise" - edu = "edu" - unknown = "unknown" - - -class PluginAuthPolicy(Enum): - on_install = "ON_INSTALL" - on_use = "ON_USE" - - -class PluginInstallParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - marketplace_path: Annotated[ - AbsolutePathBuf | None, Field(alias="marketplacePath") - ] = None - plugin_name: Annotated[str, Field(alias="pluginName")] - remote_marketplace_name: Annotated[ - str | None, Field(alias="remoteMarketplaceName") - ] = None - - -class PluginInstallPolicy(Enum): - not_available = "NOT_AVAILABLE" - available = "AVAILABLE" - installed_by_default = "INSTALLED_BY_DEFAULT" - - -class PluginInstallResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - apps_needing_auth: Annotated[list[AppSummary], Field(alias="appsNeedingAuth")] - auth_policy: Annotated[PluginAuthPolicy, Field(alias="authPolicy")] - - -class PluginInterface(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - brand_color: Annotated[str | None, Field(alias="brandColor")] = None - capabilities: list[str] - category: str | None = None - composer_icon: Annotated[ - AbsolutePathBuf | None, - Field( - alias="composerIcon", - description="Local composer icon path, resolved from the installed plugin package.", - ), - ] = None - composer_icon_url: Annotated[ - str | None, - Field( - alias="composerIconUrl", - description="Remote composer icon URL from the plugin catalog.", - ), - ] = None - default_prompt: Annotated[ - list[str] | None, - Field( - alias="defaultPrompt", - description="Starter prompts for the plugin. Capped at 3 entries with a maximum of 128 characters per entry.", - ), - ] = None - developer_name: Annotated[str | None, Field(alias="developerName")] = None - display_name: Annotated[str | None, Field(alias="displayName")] = None - logo: Annotated[ - AbsolutePathBuf | None, - Field( - description="Local logo path, resolved from the installed plugin package." - ), - ] = None - logo_url: Annotated[ - str | None, - Field(alias="logoUrl", description="Remote logo URL from the plugin catalog."), - ] = None - long_description: Annotated[str | None, Field(alias="longDescription")] = None - privacy_policy_url: Annotated[str | None, Field(alias="privacyPolicyUrl")] = None - screenshot_urls: Annotated[ - list[str], - Field( - alias="screenshotUrls", - description="Remote screenshot URLs from the plugin catalog.", - ), - ] - screenshots: Annotated[ - list[AbsolutePathBuf], - Field( - description="Local screenshot paths, resolved from the installed plugin package." - ), - ] - short_description: Annotated[str | None, Field(alias="shortDescription")] = None - terms_of_service_url: Annotated[str | None, Field(alias="termsOfServiceUrl")] = None - website_url: Annotated[str | None, Field(alias="websiteUrl")] = None - - -class PluginListParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cwds: Annotated[ - list[AbsolutePathBuf] | None, - Field( - description="Optional working directories used to discover repo marketplaces. When omitted, only home-scoped marketplaces and the official curated marketplace are considered." - ), - ] = None - - -class PluginReadParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - marketplace_path: Annotated[ - AbsolutePathBuf | None, Field(alias="marketplacePath") - ] = None - plugin_name: Annotated[str, Field(alias="pluginName")] - remote_marketplace_name: Annotated[ - str | None, Field(alias="remoteMarketplaceName") - ] = None - - -class LocalPluginSource(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - path: AbsolutePathBuf - type: Annotated[Literal["local"], Field(title="LocalPluginSourceType")] - - -class GitPluginSource(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - path: str | None = None - ref_name: Annotated[str | None, Field(alias="refName")] = None - sha: str | None = None - type: Annotated[Literal["git"], Field(title="GitPluginSourceType")] - url: str - - -class RemotePluginSource(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[Literal["remote"], Field(title="RemotePluginSourceType")] - - -class PluginSource(RootModel[LocalPluginSource | GitPluginSource | RemotePluginSource]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: LocalPluginSource | GitPluginSource | RemotePluginSource - - -class PluginSummary(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - auth_policy: Annotated[PluginAuthPolicy, Field(alias="authPolicy")] - enabled: bool - id: str - install_policy: Annotated[PluginInstallPolicy, Field(alias="installPolicy")] - installed: bool - interface: PluginInterface | None = None - name: str - source: PluginSource - - -class PluginUninstallParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - plugin_id: Annotated[str, Field(alias="pluginId")] - - -class PluginUninstallResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class PluginsMigration(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - marketplace_name: Annotated[str, Field(alias="marketplaceName")] - plugin_names: Annotated[list[str], Field(alias="pluginNames")] - - -class RateLimitReachedType(Enum): - rate_limit_reached = "rate_limit_reached" - workspace_owner_credits_depleted = "workspace_owner_credits_depleted" - workspace_member_credits_depleted = "workspace_member_credits_depleted" - workspace_owner_usage_limit_reached = "workspace_owner_usage_limit_reached" - workspace_member_usage_limit_reached = "workspace_member_usage_limit_reached" - - -class RateLimitWindow(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - resets_at: Annotated[int | None, Field(alias="resetsAt")] = None - used_percent: Annotated[int, Field(alias="usedPercent")] - window_duration_mins: Annotated[int | None, Field(alias="windowDurationMins")] = ( - None - ) - - -class RestrictedReadOnlyAccess(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - include_platform_defaults: Annotated[ - bool | None, Field(alias="includePlatformDefaults") - ] = True - readable_roots: Annotated[ - list[AbsolutePathBuf] | None, Field(alias="readableRoots") - ] = [] - type: Annotated[Literal["restricted"], Field(title="RestrictedReadOnlyAccessType")] - - -class FullAccessReadOnlyAccess(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[Literal["fullAccess"], Field(title="FullAccessReadOnlyAccessType")] - - -class ReadOnlyAccess(RootModel[RestrictedReadOnlyAccess | FullAccessReadOnlyAccess]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: RestrictedReadOnlyAccess | FullAccessReadOnlyAccess - - -class RealtimeConversationVersion(Enum): - v1 = "v1" - v2 = "v2" - - -class RealtimeOutputModality(Enum): - text = "text" - audio = "audio" - - -class RealtimeVoice(Enum): - alloy = "alloy" - arbor = "arbor" - ash = "ash" - ballad = "ballad" - breeze = "breeze" - cedar = "cedar" - coral = "coral" - cove = "cove" - echo = "echo" - ember = "ember" - juniper = "juniper" - maple = "maple" - marin = "marin" - sage = "sage" - shimmer = "shimmer" - sol = "sol" - spruce = "spruce" - vale = "vale" - verse = "verse" - - -class RealtimeVoicesList(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - default_v1: Annotated[RealtimeVoice, Field(alias="defaultV1")] - default_v2: Annotated[RealtimeVoice, Field(alias="defaultV2")] - v1: list[RealtimeVoice] - v2: list[RealtimeVoice] - - -class ReasoningEffort(Enum): - none = "none" - minimal = "minimal" - low = "low" - medium = "medium" - high = "high" - xhigh = "xhigh" - - -class ReasoningEffortOption(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - description: str - reasoning_effort: Annotated[ReasoningEffort, Field(alias="reasoningEffort")] - - -class ReasoningTextReasoningItemContent(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - text: str - type: Annotated[ - Literal["reasoning_text"], Field(title="ReasoningTextReasoningItemContentType") - ] - - -class TextReasoningItemContent(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - text: str - type: Annotated[Literal["text"], Field(title="TextReasoningItemContentType")] - - -class ReasoningItemContent( - RootModel[ReasoningTextReasoningItemContent | TextReasoningItemContent] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ReasoningTextReasoningItemContent | TextReasoningItemContent - - -class SummaryTextReasoningItemReasoningSummary(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - text: str - type: Annotated[ - Literal["summary_text"], - Field(title="SummaryTextReasoningItemReasoningSummaryType"), - ] - - -class ReasoningItemReasoningSummary( - RootModel[SummaryTextReasoningItemReasoningSummary] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: SummaryTextReasoningItemReasoningSummary - - -class ReasoningSummaryValue(Enum): - auto = "auto" - concise = "concise" - detailed = "detailed" - - -class ReasoningSummary(RootModel[ReasoningSummaryValue | Literal["none"]]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: Annotated[ - ReasoningSummaryValue | Literal["none"], - Field( - description="A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries" - ), - ] - - -class ReasoningSummaryPartAddedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - item_id: Annotated[str, Field(alias="itemId")] - summary_index: Annotated[int, Field(alias="summaryIndex")] - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class ReasoningSummaryTextDeltaNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - delta: str - item_id: Annotated[str, Field(alias="itemId")] - summary_index: Annotated[int, Field(alias="summaryIndex")] - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class ReasoningTextDeltaNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - content_index: Annotated[int, Field(alias="contentIndex")] - delta: str - item_id: Annotated[str, Field(alias="itemId")] - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class RequestId(RootModel[str | int]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: str | int - - -class ResidencyRequirement(RootModel[Literal["us"]]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: Literal["us"] - - -class Resource(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - field_meta: Annotated[Any | None, Field(alias="_meta")] = None - annotations: Any | None = None - description: str | None = None - icons: list | None = None - mime_type: Annotated[str | None, Field(alias="mimeType")] = None - name: str - size: int | None = None - title: str | None = None - uri: str - - -class ResourceContent1(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - field_meta: Annotated[Any | None, Field(alias="_meta")] = None - mime_type: Annotated[str | None, Field(alias="mimeType")] = None - text: str - uri: Annotated[str, Field(description="The URI of this resource.")] - - -class ResourceContent2(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - field_meta: Annotated[Any | None, Field(alias="_meta")] = None - blob: str - mime_type: Annotated[str | None, Field(alias="mimeType")] = None - uri: Annotated[str, Field(description="The URI of this resource.")] - - -class ResourceContent(RootModel[ResourceContent1 | ResourceContent2]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: Annotated[ - ResourceContent1 | ResourceContent2, - Field( - description="Contents returned when reading a resource from an MCP server." - ), - ] - - -class ResourceTemplate(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - annotations: Any | None = None - description: str | None = None - mime_type: Annotated[str | None, Field(alias="mimeType")] = None - name: str - title: str | None = None - uri_template: Annotated[str, Field(alias="uriTemplate")] - - -class ReasoningResponseItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - content: list[ReasoningItemContent] | None = None - encrypted_content: str | None = None - summary: list[ReasoningItemReasoningSummary] - type: Annotated[Literal["reasoning"], Field(title="ReasoningResponseItemType")] - - -class LocalShellCallResponseItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - action: LocalShellAction - call_id: Annotated[ - str | None, Field(description="Set when using the Responses API.") - ] = None - id: Annotated[ - str | None, - Field( - description="Legacy id field retained for compatibility with older payloads." - ), - ] = None - status: LocalShellStatus - type: Annotated[ - Literal["local_shell_call"], Field(title="LocalShellCallResponseItemType") - ] - - -class FunctionCallResponseItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - arguments: str - call_id: str - id: str | None = None - name: str - namespace: str | None = None - type: Annotated[ - Literal["function_call"], Field(title="FunctionCallResponseItemType") - ] - - -class ToolSearchCallResponseItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - arguments: Any - call_id: str | None = None - execution: str - id: str | None = None - status: str | None = None - type: Annotated[ - Literal["tool_search_call"], Field(title="ToolSearchCallResponseItemType") - ] - - -class CustomToolCallResponseItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - call_id: str - id: str | None = None - input: str - name: str - status: str | None = None - type: Annotated[ - Literal["custom_tool_call"], Field(title="CustomToolCallResponseItemType") - ] - - -class ToolSearchOutputResponseItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - call_id: str | None = None - execution: str - status: str - tools: list - type: Annotated[ - Literal["tool_search_output"], Field(title="ToolSearchOutputResponseItemType") - ] - - -class ImageGenerationCallResponseItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: str - result: str - revised_prompt: str | None = None - status: str - type: Annotated[ - Literal["image_generation_call"], - Field(title="ImageGenerationCallResponseItemType"), - ] - - -class GhostSnapshotResponseItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - ghost_commit: GhostCommit - type: Annotated[ - Literal["ghost_snapshot"], Field(title="GhostSnapshotResponseItemType") - ] - - -class CompactionResponseItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - encrypted_content: str - type: Annotated[Literal["compaction"], Field(title="CompactionResponseItemType")] - - -class OtherResponseItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[Literal["other"], Field(title="OtherResponseItemType")] - - -class SearchResponsesApiWebSearchAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - queries: list[str] | None = None - query: str | None = None - type: Annotated[ - Literal["search"], Field(title="SearchResponsesApiWebSearchActionType") - ] - - -class OpenPageResponsesApiWebSearchAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[ - Literal["open_page"], Field(title="OpenPageResponsesApiWebSearchActionType") - ] - url: str | None = None - - -class FindInPageResponsesApiWebSearchAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - pattern: str | None = None - type: Annotated[ - Literal["find_in_page"], - Field(title="FindInPageResponsesApiWebSearchActionType"), - ] - url: str | None = None - - -class OtherResponsesApiWebSearchAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[ - Literal["other"], Field(title="OtherResponsesApiWebSearchActionType") - ] - - -class ResponsesApiWebSearchAction( - RootModel[ - SearchResponsesApiWebSearchAction - | OpenPageResponsesApiWebSearchAction - | FindInPageResponsesApiWebSearchAction - | OtherResponsesApiWebSearchAction - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ( - SearchResponsesApiWebSearchAction - | OpenPageResponsesApiWebSearchAction - | FindInPageResponsesApiWebSearchAction - | OtherResponsesApiWebSearchAction - ) - - -class ReviewDelivery(Enum): - inline = "inline" - detached = "detached" - - -class UncommittedChangesReviewTarget(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[ - Literal["uncommittedChanges"], Field(title="UncommittedChangesReviewTargetType") - ] - - -class BaseBranchReviewTarget(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - branch: str - type: Annotated[Literal["baseBranch"], Field(title="BaseBranchReviewTargetType")] - - -class CommitReviewTarget(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - sha: str - title: Annotated[ - str | None, - Field( - description="Optional human-readable label (e.g., commit subject) for UIs." - ), - ] = None - type: Annotated[Literal["commit"], Field(title="CommitReviewTargetType")] - - -class CustomReviewTarget(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - instructions: str - type: Annotated[Literal["custom"], Field(title="CustomReviewTargetType")] - - -class ReviewTarget( - RootModel[ - UncommittedChangesReviewTarget - | BaseBranchReviewTarget - | CommitReviewTarget - | CustomReviewTarget - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ( - UncommittedChangesReviewTarget - | BaseBranchReviewTarget - | CommitReviewTarget - | CustomReviewTarget - ) - - -class SandboxMode(Enum): - read_only = "read-only" - workspace_write = "workspace-write" - danger_full_access = "danger-full-access" - - -class DangerFullAccessSandboxPolicy(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[ - Literal["dangerFullAccess"], Field(title="DangerFullAccessSandboxPolicyType") - ] - - -class ReadOnlySandboxPolicy(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - access: Annotated[ReadOnlyAccess | None, Field()] = {"type": "fullAccess"} - network_access: Annotated[bool | None, Field(alias="networkAccess")] = False - type: Annotated[Literal["readOnly"], Field(title="ReadOnlySandboxPolicyType")] - - -class ExternalSandboxSandboxPolicy(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - network_access: Annotated[NetworkAccess | None, Field(alias="networkAccess")] = ( - "restricted" - ) - type: Annotated[ - Literal["externalSandbox"], Field(title="ExternalSandboxSandboxPolicyType") - ] - - -class WorkspaceWriteSandboxPolicy(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - exclude_slash_tmp: Annotated[bool | None, Field(alias="excludeSlashTmp")] = False - exclude_tmpdir_env_var: Annotated[ - bool | None, Field(alias="excludeTmpdirEnvVar") - ] = False - network_access: Annotated[bool | None, Field(alias="networkAccess")] = False - read_only_access: Annotated[ - ReadOnlyAccess | None, Field(alias="readOnlyAccess") - ] = {"type": "fullAccess"} - type: Annotated[ - Literal["workspaceWrite"], Field(title="WorkspaceWriteSandboxPolicyType") - ] - writable_roots: Annotated[ - list[AbsolutePathBuf] | None, Field(alias="writableRoots") - ] = [] - - -class SandboxPolicy( - RootModel[ - DangerFullAccessSandboxPolicy - | ReadOnlySandboxPolicy - | ExternalSandboxSandboxPolicy - | WorkspaceWriteSandboxPolicy - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ( - DangerFullAccessSandboxPolicy - | ReadOnlySandboxPolicy - | ExternalSandboxSandboxPolicy - | WorkspaceWriteSandboxPolicy - ) - - -class SandboxWorkspaceWrite(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - exclude_slash_tmp: bool | None = False - exclude_tmpdir_env_var: bool | None = False - network_access: bool | None = False - writable_roots: list[str] | None = [] - - -class SendAddCreditsNudgeEmailParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - credit_type: Annotated[AddCreditsNudgeCreditType, Field(alias="creditType")] - - -class SendAddCreditsNudgeEmailResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - status: AddCreditsNudgeEmailStatus - - -class ItemAgentMessageDeltaServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["item/agentMessage/delta"], - Field(title="Item/agentMessage/deltaNotificationMethod"), - ] - params: AgentMessageDeltaNotification - - -class ItemPlanDeltaServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["item/plan/delta"], Field(title="Item/plan/deltaNotificationMethod") - ] - params: PlanDeltaNotification - - -class ItemCommandExecutionOutputDeltaServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["item/commandExecution/outputDelta"], - Field(title="Item/commandExecution/outputDeltaNotificationMethod"), - ] - params: CommandExecutionOutputDeltaNotification - - -class ItemFileChangeOutputDeltaServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["item/fileChange/outputDelta"], - Field(title="Item/fileChange/outputDeltaNotificationMethod"), - ] - params: FileChangeOutputDeltaNotification - - -class ItemMcpToolCallProgressServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["item/mcpToolCall/progress"], - Field(title="Item/mcpToolCall/progressNotificationMethod"), - ] - params: McpToolCallProgressNotification - - -class McpServerOauthLoginCompletedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["mcpServer/oauthLogin/completed"], - Field(title="McpServer/oauthLogin/completedNotificationMethod"), - ] - params: McpServerOauthLoginCompletedNotification - - -class McpServerStartupStatusUpdatedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["mcpServer/startupStatus/updated"], - Field(title="McpServer/startupStatus/updatedNotificationMethod"), - ] - params: McpServerStatusUpdatedNotification - - -class ExternalAgentConfigImportCompletedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["externalAgentConfig/import/completed"], - Field(title="ExternalAgentConfig/import/completedNotificationMethod"), - ] - params: ExternalAgentConfigImportCompletedNotification - - -class FsChangedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["fs/changed"], Field(title="Fs/changedNotificationMethod") - ] - params: FsChangedNotification - - -class ItemReasoningSummaryTextDeltaServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["item/reasoning/summaryTextDelta"], - Field(title="Item/reasoning/summaryTextDeltaNotificationMethod"), - ] - params: ReasoningSummaryTextDeltaNotification - - -class ItemReasoningSummaryPartAddedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["item/reasoning/summaryPartAdded"], - Field(title="Item/reasoning/summaryPartAddedNotificationMethod"), - ] - params: ReasoningSummaryPartAddedNotification - - -class ItemReasoningTextDeltaServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["item/reasoning/textDelta"], - Field(title="Item/reasoning/textDeltaNotificationMethod"), - ] - params: ReasoningTextDeltaNotification - - -class ThreadCompactedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/compacted"], Field(title="Thread/compactedNotificationMethod") - ] - params: ContextCompactedNotification - - -class ModelReroutedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["model/rerouted"], Field(title="Model/reroutedNotificationMethod") - ] - params: ModelReroutedNotification - - -class DeprecationNoticeServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["deprecationNotice"], Field(title="DeprecationNoticeNotificationMethod") - ] - params: DeprecationNoticeNotification - - -class FuzzyFileSearchSessionUpdatedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["fuzzyFileSearch/sessionUpdated"], - Field(title="FuzzyFileSearch/sessionUpdatedNotificationMethod"), - ] - params: FuzzyFileSearchSessionUpdatedNotification - - -class FuzzyFileSearchSessionCompletedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["fuzzyFileSearch/sessionCompleted"], - Field(title="FuzzyFileSearch/sessionCompletedNotificationMethod"), - ] - params: FuzzyFileSearchSessionCompletedNotification - - -class AccountLoginCompletedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["account/login/completed"], - Field(title="Account/login/completedNotificationMethod"), - ] - params: AccountLoginCompletedNotification - - -class ServerRequestResolvedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - request_id: Annotated[RequestId, Field(alias="requestId")] - thread_id: Annotated[str, Field(alias="threadId")] - - -class ServiceTier(Enum): - fast = "fast" - flex = "flex" - - -class SessionSourceValue(Enum): - cli = "cli" - vscode = "vscode" - exec = "exec" - app_server = "appServer" - unknown = "unknown" - - -class CustomSessionSource(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - custom: str - - -class Settings(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - developer_instructions: str | None = None - model: str - reasoning_effort: ReasoningEffort | None = None - - -class SkillErrorInfo(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - message: str - path: str - - -class SkillInterface(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - brand_color: Annotated[str | None, Field(alias="brandColor")] = None - default_prompt: Annotated[str | None, Field(alias="defaultPrompt")] = None - display_name: Annotated[str | None, Field(alias="displayName")] = None - icon_large: Annotated[AbsolutePathBuf | None, Field(alias="iconLarge")] = None - icon_small: Annotated[AbsolutePathBuf | None, Field(alias="iconSmall")] = None - short_description: Annotated[str | None, Field(alias="shortDescription")] = None - - -class SkillScope(Enum): - user = "user" - repo = "repo" - system = "system" - admin = "admin" - - -class SkillSummary(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - description: str - enabled: bool - interface: SkillInterface | None = None - name: str - path: AbsolutePathBuf - short_description: Annotated[str | None, Field(alias="shortDescription")] = None - - -class SkillToolDependency(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - command: str | None = None - description: str | None = None - transport: str | None = None - type: str - url: str | None = None - value: str - - -class SkillsChangedNotification(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class SkillsConfigWriteParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - enabled: bool - name: Annotated[str | None, Field(description="Name-based selector.")] = None - path: Annotated[ - AbsolutePathBuf | None, Field(description="Path-based selector.") - ] = None - - -class SkillsConfigWriteResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - effective_enabled: Annotated[bool, Field(alias="effectiveEnabled")] - - -class SkillsListExtraRootsForCwd(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cwd: str - extra_user_roots: Annotated[list[str], Field(alias="extraUserRoots")] - - -class SkillsListParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cwds: Annotated[ - list[str] | None, - Field( - description="When empty, defaults to the current session working directory." - ), - ] = None - force_reload: Annotated[ - bool | None, - Field( - alias="forceReload", - description="When true, bypass the skills cache and re-scan skills from disk.", - ), - ] = None - per_cwd_extra_user_roots: Annotated[ - list[SkillsListExtraRootsForCwd] | None, - Field( - alias="perCwdExtraUserRoots", - description="Optional per-cwd extra roots to scan as user-scoped skills.", - ), - ] = None - - -class SortDirection(Enum): - asc = "asc" - desc = "desc" - - -class SubAgentSourceValue(Enum): - review = "review" - compact = "compact" - memory_consolidation = "memory_consolidation" - - -class OtherSubAgentSource(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - other: str - - -class TerminalInteractionNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - item_id: Annotated[str, Field(alias="itemId")] - process_id: Annotated[str, Field(alias="processId")] - stdin: str - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class TextElement(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - byte_range: Annotated[ - ByteRange, - Field( - alias="byteRange", - description="Byte range in the parent `text` buffer that this element occupies.", - ), - ] - placeholder: Annotated[ - str | None, - Field( - description="Optional human-readable placeholder for the element, displayed in the UI." - ), - ] = None - - -class TextPosition(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - column: Annotated[ - int, - Field(description="1-based column number (in Unicode scalar values).", ge=0), - ] - line: Annotated[int, Field(description="1-based line number.", ge=0)] - - -class TextRange(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - end: TextPosition - start: TextPosition - - -class ThreadActiveFlag(Enum): - waiting_on_approval = "waitingOnApproval" - waiting_on_user_input = "waitingOnUserInput" - - -class ThreadArchiveParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadArchiveResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class ThreadArchivedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadClosedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadCompactStartParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadCompactStartResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class ThreadForkParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - approval_policy: Annotated[AskForApproval | None, Field(alias="approvalPolicy")] = ( - None - ) - approvals_reviewer: Annotated[ - ApprovalsReviewer | None, - Field( - alias="approvalsReviewer", - description="Override where approval requests are routed for review on this thread and subsequent turns.", - ), - ] = None - base_instructions: Annotated[str | None, Field(alias="baseInstructions")] = None - config: dict[str, Any] | None = None - cwd: str | None = None - developer_instructions: Annotated[ - str | None, Field(alias="developerInstructions") - ] = None - ephemeral: bool | None = None - model: Annotated[ - str | None, - Field(description="Configuration overrides for the forked thread, if any."), - ] = None - model_provider: Annotated[str | None, Field(alias="modelProvider")] = None - sandbox: SandboxMode | None = None - service_tier: Annotated[ServiceTier | None, Field(alias="serviceTier")] = None - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadId(RootModel[str]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: str - - -class ThreadInjectItemsParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - items: Annotated[ - list, - Field( - description="Raw Responses API items to append to the thread's model-visible history." - ), - ] - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadInjectItemsResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class HookPromptThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - fragments: list[HookPromptFragment] - id: str - type: Annotated[Literal["hookPrompt"], Field(title="HookPromptThreadItemType")] - - -class PlanThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: str - text: str - type: Annotated[Literal["plan"], Field(title="PlanThreadItemType")] - - -class ReasoningThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - content: list[str] | None = [] - id: str - summary: list[str] | None = [] - type: Annotated[Literal["reasoning"], Field(title="ReasoningThreadItemType")] - - -class CommandExecutionThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - aggregated_output: Annotated[ - str | None, - Field( - alias="aggregatedOutput", - description="The command's output, aggregated from stdout and stderr.", - ), - ] = None - command: Annotated[str, Field(description="The command to be executed.")] - command_actions: Annotated[ - list[CommandAction], - Field( - alias="commandActions", - description="A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", - ), - ] - cwd: Annotated[ - AbsolutePathBuf, Field(description="The command's working directory.") - ] - duration_ms: Annotated[ - int | None, - Field( - alias="durationMs", - description="The duration of the command execution in milliseconds.", - ), - ] = None - exit_code: Annotated[ - int | None, Field(alias="exitCode", description="The command's exit code.") - ] = None - id: str - process_id: Annotated[ - str | None, - Field( - alias="processId", - description="Identifier for the underlying PTY process (when available).", - ), - ] = None - source: CommandExecutionSource | None = "agent" - status: CommandExecutionStatus - type: Annotated[ - Literal["commandExecution"], Field(title="CommandExecutionThreadItemType") - ] - - -class McpToolCallThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - arguments: Any - duration_ms: Annotated[ - int | None, - Field( - alias="durationMs", - description="The duration of the MCP tool call in milliseconds.", - ), - ] = None - error: McpToolCallError | None = None - id: str - mcp_app_resource_uri: Annotated[str | None, Field(alias="mcpAppResourceUri")] = None - result: McpToolCallResult | None = None - server: str - status: McpToolCallStatus - tool: str - type: Annotated[Literal["mcpToolCall"], Field(title="McpToolCallThreadItemType")] - - -class DynamicToolCallThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - arguments: Any - content_items: Annotated[ - list[DynamicToolCallOutputContentItem] | None, Field(alias="contentItems") - ] = None - duration_ms: Annotated[ - int | None, - Field( - alias="durationMs", - description="The duration of the dynamic tool call in milliseconds.", - ), - ] = None - id: str - namespace: str | None = None - status: DynamicToolCallStatus - success: bool | None = None - tool: str - type: Annotated[ - Literal["dynamicToolCall"], Field(title="DynamicToolCallThreadItemType") - ] - - -class ImageViewThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: str - path: AbsolutePathBuf - type: Annotated[Literal["imageView"], Field(title="ImageViewThreadItemType")] - - -class ImageGenerationThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: str - result: str - revised_prompt: Annotated[str | None, Field(alias="revisedPrompt")] = None - saved_path: Annotated[AbsolutePathBuf | None, Field(alias="savedPath")] = None - status: str - type: Annotated[ - Literal["imageGeneration"], Field(title="ImageGenerationThreadItemType") - ] - - -class EnteredReviewModeThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: str - review: str - type: Annotated[ - Literal["enteredReviewMode"], Field(title="EnteredReviewModeThreadItemType") - ] - - -class ExitedReviewModeThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: str - review: str - type: Annotated[ - Literal["exitedReviewMode"], Field(title="ExitedReviewModeThreadItemType") - ] - - -class ContextCompactionThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: str - type: Annotated[ - Literal["contextCompaction"], Field(title="ContextCompactionThreadItemType") - ] - - -class ThreadLoadedListParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cursor: Annotated[ - str | None, - Field(description="Opaque pagination cursor returned by a previous call."), - ] = None - limit: Annotated[ - int | None, Field(description="Optional page size; defaults to no limit.", ge=0) - ] = None - - -class ThreadLoadedListResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - data: Annotated[ - list[str], - Field(description="Thread ids for sessions currently loaded in memory."), - ] - next_cursor: Annotated[ - str | None, - Field( - alias="nextCursor", - description="Opaque cursor to pass to the next call to continue after the last item. if None, there are no more items to return.", - ), - ] = None - - -class ThreadMemoryMode(Enum): - enabled = "enabled" - disabled = "disabled" - - -class ThreadMetadataGitInfoUpdateParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - branch: Annotated[ - str | None, - Field( - description="Omit to leave the stored branch unchanged, set to `null` to clear it, or provide a non-empty string to replace it." - ), - ] = None - origin_url: Annotated[ - str | None, - Field( - alias="originUrl", - description="Omit to leave the stored origin URL unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", - ), - ] = None - sha: Annotated[ - str | None, - Field( - description="Omit to leave the stored commit unchanged, set to `null` to clear it, or provide a non-empty string to replace it." - ), - ] = None - - -class ThreadMetadataUpdateParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - git_info: Annotated[ - ThreadMetadataGitInfoUpdateParams | None, - Field( - alias="gitInfo", - description="Patch the stored Git metadata for this thread. Omit a field to leave it unchanged, set it to `null` to clear it, or provide a string to replace the stored value.", - ), - ] = None - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadNameUpdatedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread_id: Annotated[str, Field(alias="threadId")] - thread_name: Annotated[str | None, Field(alias="threadName")] = None - - -class ThreadReadParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - include_turns: Annotated[ - bool | None, - Field( - alias="includeTurns", - description="When true, include turns and their items from rollout history.", - ), - ] = False - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadRealtimeAudioChunk(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - data: str - item_id: Annotated[str | None, Field(alias="itemId")] = None - num_channels: Annotated[int, Field(alias="numChannels", ge=0)] - sample_rate: Annotated[int, Field(alias="sampleRate", ge=0)] - samples_per_channel: Annotated[ - int | None, Field(alias="samplesPerChannel", ge=0) - ] = None - - -class ThreadRealtimeClosedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - reason: str | None = None - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadRealtimeErrorNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - message: str - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadRealtimeItemAddedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - item: Any - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadRealtimeOutputAudioDeltaNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - audio: ThreadRealtimeAudioChunk - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadRealtimeSdpNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - sdp: str - thread_id: Annotated[str, Field(alias="threadId")] - - -class WebsocketThreadRealtimeStartTransport(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[ - Literal["websocket"], Field(title="WebsocketThreadRealtimeStartTransportType") - ] - - -class WebrtcThreadRealtimeStartTransport(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - sdp: Annotated[ - str, - Field( - description="SDP offer generated by a WebRTC RTCPeerConnection after configuring audio and the realtime events data channel." - ), - ] - type: Annotated[ - Literal["webrtc"], Field(title="WebrtcThreadRealtimeStartTransportType") - ] - - -class ThreadRealtimeStartTransport( - RootModel[ - WebsocketThreadRealtimeStartTransport | WebrtcThreadRealtimeStartTransport - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: Annotated[ - WebsocketThreadRealtimeStartTransport | WebrtcThreadRealtimeStartTransport, - Field(description="EXPERIMENTAL - transport used by thread realtime."), - ] - - -class ThreadRealtimeStartedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - session_id: Annotated[str | None, Field(alias="sessionId")] = None - thread_id: Annotated[str, Field(alias="threadId")] - version: RealtimeConversationVersion - - -class ThreadRealtimeTranscriptDeltaNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - delta: Annotated[ - str, Field(description="Live transcript delta from the realtime event.") - ] - role: str - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadRealtimeTranscriptDoneNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - role: str - text: Annotated[ - str, Field(description="Final complete text for the transcript part.") - ] - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadResumeParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - approval_policy: Annotated[AskForApproval | None, Field(alias="approvalPolicy")] = ( - None - ) - approvals_reviewer: Annotated[ - ApprovalsReviewer | None, - Field( - alias="approvalsReviewer", - description="Override where approval requests are routed for review on this thread and subsequent turns.", - ), - ] = None - base_instructions: Annotated[str | None, Field(alias="baseInstructions")] = None - config: dict[str, Any] | None = None - cwd: str | None = None - developer_instructions: Annotated[ - str | None, Field(alias="developerInstructions") - ] = None - model: Annotated[ - str | None, - Field(description="Configuration overrides for the resumed thread, if any."), - ] = None - model_provider: Annotated[str | None, Field(alias="modelProvider")] = None - personality: Personality | None = None - sandbox: SandboxMode | None = None - service_tier: Annotated[ServiceTier | None, Field(alias="serviceTier")] = None - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadRollbackParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - num_turns: Annotated[ - int, - Field( - alias="numTurns", - description="The number of turns to drop from the end of the thread. Must be >= 1.\n\nThis only modifies the thread's history and does not revert local file changes that have been made by the agent. Clients are responsible for reverting these changes.", - ge=0, - ), - ] - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadSetNameParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - name: str - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadSetNameResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class ThreadShellCommandParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - command: Annotated[ - str, - Field( - description="Shell command string evaluated by the thread's configured shell. Unlike `command/exec`, this intentionally preserves shell syntax such as pipes, redirects, and quoting. This runs unsandboxed with full access rather than inheriting the thread sandbox policy." - ), - ] - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadShellCommandResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class ThreadSortKey(Enum): - created_at = "created_at" - updated_at = "updated_at" - - -class ThreadSourceKind(Enum): - cli = "cli" - vscode = "vscode" - exec = "exec" - app_server = "appServer" - sub_agent = "subAgent" - sub_agent_review = "subAgentReview" - sub_agent_compact = "subAgentCompact" - sub_agent_thread_spawn = "subAgentThreadSpawn" - sub_agent_other = "subAgentOther" - unknown = "unknown" - - -class ThreadStartSource(Enum): - startup = "startup" - clear = "clear" - - -class NotLoadedThreadStatus(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[Literal["notLoaded"], Field(title="NotLoadedThreadStatusType")] - - -class IdleThreadStatus(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[Literal["idle"], Field(title="IdleThreadStatusType")] - - -class SystemErrorThreadStatus(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[Literal["systemError"], Field(title="SystemErrorThreadStatusType")] - - -class ActiveThreadStatus(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - active_flags: Annotated[list[ThreadActiveFlag], Field(alias="activeFlags")] - type: Annotated[Literal["active"], Field(title="ActiveThreadStatusType")] - - -class ThreadStatus( - RootModel[ - NotLoadedThreadStatus - | IdleThreadStatus - | SystemErrorThreadStatus - | ActiveThreadStatus - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ( - NotLoadedThreadStatus - | IdleThreadStatus - | SystemErrorThreadStatus - | ActiveThreadStatus - ) - - -class ThreadStatusChangedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - status: ThreadStatus - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadTurnsListParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cursor: Annotated[ - str | None, - Field( - description="Opaque cursor to pass to the next call to continue after the last turn." - ), - ] = None - limit: Annotated[ - int | None, Field(description="Optional turn page size.", ge=0) - ] = None - sort_direction: Annotated[ - SortDirection | None, - Field( - alias="sortDirection", - description="Optional turn pagination direction; defaults to descending.", - ), - ] = None - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadUnarchiveParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadUnarchivedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadUnsubscribeParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadUnsubscribeStatus(Enum): - not_loaded = "notLoaded" - not_subscribed = "notSubscribed" - unsubscribed = "unsubscribed" - - -class TokenUsageBreakdown(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cached_input_tokens: Annotated[int, Field(alias="cachedInputTokens")] - input_tokens: Annotated[int, Field(alias="inputTokens")] - output_tokens: Annotated[int, Field(alias="outputTokens")] - reasoning_output_tokens: Annotated[int, Field(alias="reasoningOutputTokens")] - total_tokens: Annotated[int, Field(alias="totalTokens")] - - -class Tool(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - field_meta: Annotated[Any | None, Field(alias="_meta")] = None - annotations: Any | None = None - description: str | None = None - icons: list | None = None - input_schema: Annotated[Any, Field(alias="inputSchema")] - name: str - output_schema: Annotated[Any | None, Field(alias="outputSchema")] = None - title: str | None = None - - -class TurnDiffUpdatedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - diff: str - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class TurnInterruptParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class TurnInterruptResponse(BaseModel): - pass - model_config = ConfigDict( - populate_by_name=True, - ) - - -class TurnPlanStepStatus(Enum): - pending = "pending" - in_progress = "inProgress" - completed = "completed" - - -class TurnStatus(Enum): - completed = "completed" - interrupted = "interrupted" - failed = "failed" - in_progress = "inProgress" - - -class TurnSteerResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - turn_id: Annotated[str, Field(alias="turnId")] - - -class TextUserInput(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - text: str - text_elements: Annotated[ - list[TextElement] | None, - Field( - description="UI-defined spans within `text` used to render or persist special elements." - ), - ] = [] - type: Annotated[Literal["text"], Field(title="TextUserInputType")] - - -class ImageUserInput(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[Literal["image"], Field(title="ImageUserInputType")] - url: str - - -class LocalImageUserInput(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - path: str - type: Annotated[Literal["localImage"], Field(title="LocalImageUserInputType")] - - -class SkillUserInput(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - name: str - path: str - type: Annotated[Literal["skill"], Field(title="SkillUserInputType")] - - -class MentionUserInput(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - name: str - path: str - type: Annotated[Literal["mention"], Field(title="MentionUserInputType")] - - -class UserInput( - RootModel[ - TextUserInput - | ImageUserInput - | LocalImageUserInput - | SkillUserInput - | MentionUserInput - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ( - TextUserInput - | ImageUserInput - | LocalImageUserInput - | SkillUserInput - | MentionUserInput - ) - - -class Verbosity(Enum): - low = "low" - medium = "medium" - high = "high" - - -class WarningNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - message: Annotated[str, Field(description="Concise warning message for the user.")] - thread_id: Annotated[ - str | None, - Field( - alias="threadId", - description="Optional thread target when the warning applies to a specific thread.", - ), - ] = None - - -class SearchWebSearchAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - queries: list[str] | None = None - query: str | None = None - type: Annotated[Literal["search"], Field(title="SearchWebSearchActionType")] - - -class OpenPageWebSearchAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[Literal["openPage"], Field(title="OpenPageWebSearchActionType")] - url: str | None = None - - -class FindInPageWebSearchAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - pattern: str | None = None - type: Annotated[Literal["findInPage"], Field(title="FindInPageWebSearchActionType")] - url: str | None = None - - -class OtherWebSearchAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[Literal["other"], Field(title="OtherWebSearchActionType")] - - -class WebSearchAction( - RootModel[ - SearchWebSearchAction - | OpenPageWebSearchAction - | FindInPageWebSearchAction - | OtherWebSearchAction - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ( - SearchWebSearchAction - | OpenPageWebSearchAction - | FindInPageWebSearchAction - | OtherWebSearchAction - ) - - -class WebSearchContextSize(Enum): - low = "low" - medium = "medium" - high = "high" - - -class WebSearchLocation(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - city: str | None = None - country: str | None = None - region: str | None = None - timezone: str | None = None - - -class WebSearchMode(Enum): - disabled = "disabled" - cached = "cached" - live = "live" - - -class WebSearchToolConfig(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - allowed_domains: list[str] | None = None - context_size: WebSearchContextSize | None = None - location: WebSearchLocation | None = None - - -class WindowsSandboxSetupMode(Enum): - elevated = "elevated" - unelevated = "unelevated" - - -class WindowsSandboxSetupStartParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cwd: AbsolutePathBuf | None = None - mode: WindowsSandboxSetupMode - - -class WindowsSandboxSetupStartResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - started: bool - - -class WindowsWorldWritableWarningNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - extra_count: Annotated[int, Field(alias="extraCount", ge=0)] - failed_scan: Annotated[bool, Field(alias="failedScan")] - sample_paths: Annotated[list[str], Field(alias="samplePaths")] - - -class WriteStatus(Enum): - ok = "ok" - ok_overridden = "okOverridden" - - -class ChatgptAccount(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - email: str - plan_type: Annotated[PlanType, Field(alias="planType")] - type: Annotated[Literal["chatgpt"], Field(title="ChatgptAccountType")] - - -class Account(RootModel[ApiKeyAccount | ChatgptAccount]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ApiKeyAccount | ChatgptAccount - - -class AccountUpdatedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - auth_mode: Annotated[AuthMode | None, Field(alias="authMode")] = None - plan_type: Annotated[PlanType | None, Field(alias="planType")] = None - - -class AppConfig(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - default_tools_approval_mode: AppToolApproval | None = None - default_tools_enabled: bool | None = None - destructive_enabled: bool | None = None - enabled: bool | None = True - open_world_enabled: bool | None = None - tools: AppToolsConfig | None = None - - -class AppMetadata(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - categories: list[str] | None = None - developer: str | None = None - first_party_requires_install: Annotated[ - bool | None, Field(alias="firstPartyRequiresInstall") - ] = None - first_party_type: Annotated[str | None, Field(alias="firstPartyType")] = None - review: AppReview | None = None - screenshots: list[AppScreenshot] | None = None - seo_description: Annotated[str | None, Field(alias="seoDescription")] = None - show_in_composer_when_unlinked: Annotated[ - bool | None, Field(alias="showInComposerWhenUnlinked") - ] = None - sub_categories: Annotated[list[str] | None, Field(alias="subCategories")] = None - version: str | None = None - version_id: Annotated[str | None, Field(alias="versionId")] = None - version_notes: Annotated[str | None, Field(alias="versionNotes")] = None - - -class AppsConfig(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - field_default: Annotated[AppsDefaultConfig | None, Field(alias="_default")] = None - - -class CancelLoginAccountResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - status: CancelLoginAccountStatus - - -class InitializeRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["initialize"], Field(title="InitializeRequestMethod")] - params: InitializeParams - - -class ThreadResumeRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["thread/resume"], Field(title="Thread/resumeRequestMethod") - ] - params: ThreadResumeParams - - -class ThreadForkRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["thread/fork"], Field(title="Thread/forkRequestMethod")] - params: ThreadForkParams - - -class ThreadArchiveRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["thread/archive"], Field(title="Thread/archiveRequestMethod") - ] - params: ThreadArchiveParams - - -class ThreadUnsubscribeRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["thread/unsubscribe"], Field(title="Thread/unsubscribeRequestMethod") - ] - params: ThreadUnsubscribeParams - - -class ThreadNameSetRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["thread/name/set"], Field(title="Thread/name/setRequestMethod") - ] - params: ThreadSetNameParams - - -class ThreadMetadataUpdateRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["thread/metadata/update"], - Field(title="Thread/metadata/updateRequestMethod"), - ] - params: ThreadMetadataUpdateParams - - -class ThreadUnarchiveRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["thread/unarchive"], Field(title="Thread/unarchiveRequestMethod") - ] - params: ThreadUnarchiveParams - - -class ThreadCompactStartRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["thread/compact/start"], - Field(title="Thread/compact/startRequestMethod"), - ] - params: ThreadCompactStartParams - - -class ThreadShellCommandRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["thread/shellCommand"], Field(title="Thread/shellCommandRequestMethod") - ] - params: ThreadShellCommandParams - - -class ThreadRollbackRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["thread/rollback"], Field(title="Thread/rollbackRequestMethod") - ] - params: ThreadRollbackParams - - -class ThreadLoadedListRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["thread/loaded/list"], Field(title="Thread/loaded/listRequestMethod") - ] - params: ThreadLoadedListParams - - -class ThreadReadRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["thread/read"], Field(title="Thread/readRequestMethod")] - params: ThreadReadParams - - -class ThreadTurnsListRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["thread/turns/list"], Field(title="Thread/turns/listRequestMethod") - ] - params: ThreadTurnsListParams - - -class ThreadInjectItemsRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["thread/inject_items"], Field(title="Thread/injectItemsRequestMethod") - ] - params: ThreadInjectItemsParams - - -class SkillsListRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["skills/list"], Field(title="Skills/listRequestMethod")] - params: SkillsListParams - - -class MarketplaceAddRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["marketplace/add"], Field(title="Marketplace/addRequestMethod") - ] - params: MarketplaceAddParams - - -class MarketplaceRemoveRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["marketplace/remove"], Field(title="Marketplace/removeRequestMethod") - ] - params: MarketplaceRemoveParams - - -class PluginListRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["plugin/list"], Field(title="Plugin/listRequestMethod")] - params: PluginListParams - - -class PluginReadRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["plugin/read"], Field(title="Plugin/readRequestMethod")] - params: PluginReadParams - - -class AppListRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["app/list"], Field(title="App/listRequestMethod")] - params: AppsListParams - - -class FsReadFileRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["fs/readFile"], Field(title="Fs/readFileRequestMethod")] - params: FsReadFileParams - - -class FsWriteFileRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["fs/writeFile"], Field(title="Fs/writeFileRequestMethod")] - params: FsWriteFileParams - - -class FsCreateDirectoryRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["fs/createDirectory"], Field(title="Fs/createDirectoryRequestMethod") - ] - params: FsCreateDirectoryParams - - -class FsGetMetadataRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["fs/getMetadata"], Field(title="Fs/getMetadataRequestMethod") - ] - params: FsGetMetadataParams - - -class FsReadDirectoryRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["fs/readDirectory"], Field(title="Fs/readDirectoryRequestMethod") - ] - params: FsReadDirectoryParams - - -class FsRemoveRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["fs/remove"], Field(title="Fs/removeRequestMethod")] - params: FsRemoveParams - - -class FsCopyRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["fs/copy"], Field(title="Fs/copyRequestMethod")] - params: FsCopyParams - - -class FsWatchRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["fs/watch"], Field(title="Fs/watchRequestMethod")] - params: FsWatchParams - - -class FsUnwatchRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["fs/unwatch"], Field(title="Fs/unwatchRequestMethod")] - params: FsUnwatchParams - - -class SkillsConfigWriteRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["skills/config/write"], Field(title="Skills/config/writeRequestMethod") - ] - params: SkillsConfigWriteParams - - -class PluginInstallRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["plugin/install"], Field(title="Plugin/installRequestMethod") - ] - params: PluginInstallParams - - -class PluginUninstallRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["plugin/uninstall"], Field(title="Plugin/uninstallRequestMethod") - ] - params: PluginUninstallParams - - -class TurnInterruptRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["turn/interrupt"], Field(title="Turn/interruptRequestMethod") - ] - params: TurnInterruptParams - - -class ModelListRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["model/list"], Field(title="Model/listRequestMethod")] - params: ModelListParams - - -class ExperimentalFeatureListRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["experimentalFeature/list"], - Field(title="ExperimentalFeature/listRequestMethod"), - ] - params: ExperimentalFeatureListParams - - -class ExperimentalFeatureEnablementSetRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["experimentalFeature/enablement/set"], - Field(title="ExperimentalFeature/enablement/setRequestMethod"), - ] - params: ExperimentalFeatureEnablementSetParams - - -class McpServerOauthLoginRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["mcpServer/oauth/login"], - Field(title="McpServer/oauth/loginRequestMethod"), - ] - params: McpServerOauthLoginParams - - -class ConfigMcpServerReloadRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["config/mcpServer/reload"], - Field(title="Config/mcpServer/reloadRequestMethod"), - ] - params: None = None - - -class McpServerResourceReadRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["mcpServer/resource/read"], - Field(title="McpServer/resource/readRequestMethod"), - ] - params: McpResourceReadParams - - -class McpServerToolCallRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["mcpServer/tool/call"], Field(title="McpServer/tool/callRequestMethod") - ] - params: McpServerToolCallParams - - -class WindowsSandboxSetupStartRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["windowsSandbox/setupStart"], - Field(title="WindowsSandbox/setupStartRequestMethod"), - ] - params: WindowsSandboxSetupStartParams - - -class AccountLoginStartRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["account/login/start"], Field(title="Account/login/startRequestMethod") - ] - params: LoginAccountParams - - -class AccountLoginCancelRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["account/login/cancel"], - Field(title="Account/login/cancelRequestMethod"), - ] - params: CancelLoginAccountParams - - -class AccountLogoutRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["account/logout"], Field(title="Account/logoutRequestMethod") - ] - params: None = None - - -class AccountRateLimitsReadRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["account/rateLimits/read"], - Field(title="Account/rateLimits/readRequestMethod"), - ] - params: None = None - - -class AccountSendAddCreditsNudgeEmailRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["account/sendAddCreditsNudgeEmail"], - Field(title="Account/sendAddCreditsNudgeEmailRequestMethod"), - ] - params: SendAddCreditsNudgeEmailParams - - -class FeedbackUploadRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["feedback/upload"], Field(title="Feedback/uploadRequestMethod") - ] - params: FeedbackUploadParams - - -class CommandExecWriteRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["command/exec/write"], Field(title="Command/exec/writeRequestMethod") - ] - params: CommandExecWriteParams - - -class CommandExecTerminateRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["command/exec/terminate"], - Field(title="Command/exec/terminateRequestMethod"), - ] - params: CommandExecTerminateParams - - -class ConfigReadRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["config/read"], Field(title="Config/readRequestMethod")] - params: ConfigReadParams - - -class ExternalAgentConfigDetectRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["externalAgentConfig/detect"], - Field(title="ExternalAgentConfig/detectRequestMethod"), - ] - params: ExternalAgentConfigDetectParams - - -class ConfigRequirementsReadRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["configRequirements/read"], - Field(title="ConfigRequirements/readRequestMethod"), - ] - params: None = None - - -class AccountReadRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["account/read"], Field(title="Account/readRequestMethod")] - params: GetAccountParams - - -class FuzzyFileSearchRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["fuzzyFileSearch"], Field(title="FuzzyFileSearchRequestMethod") - ] - params: FuzzyFileSearchParams - - -class ActiveTurnNotSteerable(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - turn_kind: Annotated[NonSteerableTurnKind, Field(alias="turnKind")] - - -class ActiveTurnNotSteerableCodexErrorInfo(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - active_turn_not_steerable: Annotated[ - ActiveTurnNotSteerable, Field(alias="activeTurnNotSteerable") - ] - - -class CodexErrorInfo( - RootModel[ - CodexErrorInfoValue - | HttpConnectionFailedCodexErrorInfo - | ResponseStreamConnectionFailedCodexErrorInfo - | ResponseStreamDisconnectedCodexErrorInfo - | ResponseTooManyFailedAttemptsCodexErrorInfo - | ActiveTurnNotSteerableCodexErrorInfo - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: Annotated[ - CodexErrorInfoValue - | HttpConnectionFailedCodexErrorInfo - | ResponseStreamConnectionFailedCodexErrorInfo - | ResponseStreamDisconnectedCodexErrorInfo - | ResponseTooManyFailedAttemptsCodexErrorInfo - | ActiveTurnNotSteerableCodexErrorInfo, - Field( - description="This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant." - ), - ] - - -class CollabAgentState(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - message: str | None = None - status: CollabAgentStatus - - -class CollaborationMode(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - mode: ModeKind - settings: Settings - - -class CollaborationModeMask(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - mode: ModeKind | None = None - model: str | None = None - name: str - reasoning_effort: ReasoningEffort | None = None - - -class CommandExecOutputDeltaNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cap_reached: Annotated[ - bool, - Field( - alias="capReached", - description="`true` on the final streamed chunk for a stream when `outputBytesCap` truncated later output on that stream.", - ), - ] - delta_base64: Annotated[ - str, Field(alias="deltaBase64", description="Base64-encoded output bytes.") - ] - process_id: Annotated[ - str, - Field( - alias="processId", - description="Client-supplied, connection-scoped `processId` from the original `command/exec` request.", - ), - ] - stream: Annotated[ - CommandExecOutputStream, Field(description="Output stream for this chunk.") - ] - - -class CommandExecParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - command: Annotated[ - list[str], Field(description="Command argv vector. Empty arrays are rejected.") - ] - cwd: Annotated[ - str | None, - Field(description="Optional working directory. Defaults to the server cwd."), - ] = None - disable_output_cap: Annotated[ - bool | None, - Field( - alias="disableOutputCap", - description="Disable stdout/stderr capture truncation for this request.\n\nCannot be combined with `outputBytesCap`.", - ), - ] = None - disable_timeout: Annotated[ - bool | None, - Field( - alias="disableTimeout", - description="Disable the timeout entirely for this request.\n\nCannot be combined with `timeoutMs`.", - ), - ] = None - env: Annotated[ - dict[str, Any] | None, - Field( - description="Optional environment overrides merged into the server-computed environment.\n\nMatching names override inherited values. Set a key to `null` to unset an inherited variable." - ), - ] = None - output_bytes_cap: Annotated[ - int | None, - Field( - alias="outputBytesCap", - description="Optional per-stream stdout/stderr capture cap in bytes.\n\nWhen omitted, the server default applies. Cannot be combined with `disableOutputCap`.", - ge=0, - ), - ] = None - process_id: Annotated[ - str | None, - Field( - alias="processId", - description="Optional client-supplied, connection-scoped process id.\n\nRequired for `tty`, `streamStdin`, `streamStdoutStderr`, and follow-up `command/exec/write`, `command/exec/resize`, and `command/exec/terminate` calls. When omitted, buffered execution gets an internal id that is not exposed to the client.", - ), - ] = None - sandbox_policy: Annotated[ - SandboxPolicy | None, - Field( - alias="sandboxPolicy", - description="Optional sandbox policy for this command.\n\nUses the same shape as thread/turn execution sandbox configuration and defaults to the user's configured policy when omitted.", - ), - ] = None - size: Annotated[ - CommandExecTerminalSize | None, - Field( - description="Optional initial PTY size in character cells. Only valid when `tty` is true." - ), - ] = None - stream_stdin: Annotated[ - bool | None, - Field( - alias="streamStdin", - description="Allow follow-up `command/exec/write` requests to write stdin bytes.\n\nRequires a client-supplied `processId`.", - ), - ] = None - stream_stdout_stderr: Annotated[ - bool | None, - Field( - alias="streamStdoutStderr", - description="Stream stdout/stderr via `command/exec/outputDelta` notifications.\n\nStreamed bytes are not duplicated into the final response and require a client-supplied `processId`.", - ), - ] = None - timeout_ms: Annotated[ - int | None, - Field( - alias="timeoutMs", - description="Optional timeout in milliseconds.\n\nWhen omitted, the server default applies. Cannot be combined with `disableTimeout`.", - ), - ] = None - tty: Annotated[ - bool | None, - Field( - description="Enable PTY mode.\n\nThis implies `streamStdin` and `streamStdoutStderr`." - ), - ] = None - - -class CommandExecResizeParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - process_id: Annotated[ - str, - Field( - alias="processId", - description="Client-supplied, connection-scoped `processId` from the original `command/exec` request.", - ), - ] - size: Annotated[ - CommandExecTerminalSize, Field(description="New PTY size in character cells.") - ] - - -class ConfigEdit(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - key_path: Annotated[str, Field(alias="keyPath")] - merge_strategy: Annotated[MergeStrategy, Field(alias="mergeStrategy")] - value: Any - - -class ConfigLayer(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - config: Any - disabled_reason: Annotated[str | None, Field(alias="disabledReason")] = None - name: ConfigLayerSource - version: str - - -class ConfigLayerMetadata(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - name: ConfigLayerSource - version: str - - -class ConfigRequirements(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - allowed_approval_policies: Annotated[ - list[AskForApproval] | None, Field(alias="allowedApprovalPolicies") - ] = None - allowed_sandbox_modes: Annotated[ - list[SandboxMode] | None, Field(alias="allowedSandboxModes") - ] = None - allowed_web_search_modes: Annotated[ - list[WebSearchMode] | None, Field(alias="allowedWebSearchModes") - ] = None - enforce_residency: Annotated[ - ResidencyRequirement | None, Field(alias="enforceResidency") - ] = None - feature_requirements: Annotated[ - dict[str, Any] | None, Field(alias="featureRequirements") - ] = None - - -class ConfigRequirementsReadResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - requirements: Annotated[ - ConfigRequirements | None, - Field( - description="Null if no requirements are configured (e.g. no requirements.toml/MDM entries)." - ), - ] = None - - -class ConfigValueWriteParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - expected_version: Annotated[str | None, Field(alias="expectedVersion")] = None - file_path: Annotated[ - str | None, - Field( - alias="filePath", - description="Path to the config file to write; defaults to the user's `config.toml` when omitted.", - ), - ] = None - key_path: Annotated[str, Field(alias="keyPath")] - merge_strategy: Annotated[MergeStrategy, Field(alias="mergeStrategy")] - value: Any - - -class ConfigWarningNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - details: Annotated[ - str | None, Field(description="Optional extra guidance or error details.") - ] = None - path: Annotated[ - str | None, - Field( - description="Optional path to the config file that triggered the warning." - ), - ] = None - range: Annotated[ - TextRange | None, - Field( - description="Optional range for the error location inside the config file." - ), - ] = None - summary: Annotated[str, Field(description="Concise summary of the warning.")] - - -class InputImageContentItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - detail: ImageDetail | None = None - image_url: str - type: Annotated[Literal["input_image"], Field(title="InputImageContentItemType")] - - -class ContentItem( - RootModel[InputTextContentItem | InputImageContentItem | OutputTextContentItem] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: InputTextContentItem | InputImageContentItem | OutputTextContentItem - - -class ExperimentalFeature(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - announcement: Annotated[ - str | None, - Field( - description="Announcement copy shown to users when the feature is introduced. Null when this feature is not in beta." - ), - ] = None - default_enabled: Annotated[ - bool, - Field( - alias="defaultEnabled", - description="Whether this feature is enabled by default.", - ), - ] - description: Annotated[ - str | None, - Field( - description="Short summary describing what the feature does. Null when this feature is not in beta." - ), - ] = None - display_name: Annotated[ - str | None, - Field( - alias="displayName", - description="User-facing display name shown in the experimental features UI. Null when this feature is not in beta.", - ), - ] = None - enabled: Annotated[ - bool, - Field( - description="Whether this feature is currently enabled in the loaded config." - ), - ] - name: Annotated[ - str, Field(description="Stable key used in config.toml and CLI flag toggles.") - ] - stage: Annotated[ - ExperimentalFeatureStage, - Field(description="Lifecycle stage of this feature flag."), - ] - - -class ExperimentalFeatureListResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - data: list[ExperimentalFeature] - next_cursor: Annotated[ - str | None, - Field( - alias="nextCursor", - description="Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", - ), - ] = None - - -class SpecialFileSystemPath(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[Literal["special"], Field(title="SpecialFileSystemPathType")] - value: FileSystemSpecialPath - - -class FileSystemPath( - RootModel[PathFileSystemPath | GlobPatternFileSystemPath | SpecialFileSystemPath] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: PathFileSystemPath | GlobPatternFileSystemPath | SpecialFileSystemPath - - -class FileSystemSandboxEntry(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - access: FileSystemAccessMode - path: FileSystemPath - - -class FileUpdateChange(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - diff: str - kind: PatchChangeKind - path: str - - -class InputImageFunctionCallOutputContentItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - detail: ImageDetail | None = None - image_url: str - type: Annotated[ - Literal["input_image"], - Field(title="InputImageFunctionCallOutputContentItemType"), - ] - - -class FunctionCallOutputContentItem( - RootModel[ - InputTextFunctionCallOutputContentItem | InputImageFunctionCallOutputContentItem - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: Annotated[ - InputTextFunctionCallOutputContentItem - | InputImageFunctionCallOutputContentItem, - Field( - description="Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs." - ), - ] - - -class GetAccountResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - account: Account | None = None - requires_openai_auth: Annotated[bool, Field(alias="requiresOpenaiAuth")] - - -class GuardianApprovalReview(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - rationale: str | None = None - risk_level: Annotated[GuardianRiskLevel | None, Field(alias="riskLevel")] = None - status: GuardianApprovalReviewStatus - user_authorization: Annotated[ - GuardianUserAuthorization | None, Field(alias="userAuthorization") - ] = None - - -class CommandGuardianApprovalReviewAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - command: str - cwd: AbsolutePathBuf - source: GuardianCommandSource - type: Annotated[ - Literal["command"], Field(title="CommandGuardianApprovalReviewActionType") - ] - - -class ExecveGuardianApprovalReviewAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - argv: list[str] - cwd: AbsolutePathBuf - program: str - source: GuardianCommandSource - type: Annotated[ - Literal["execve"], Field(title="ExecveGuardianApprovalReviewActionType") - ] - - -class NetworkAccessGuardianApprovalReviewAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - host: str - port: Annotated[int, Field(ge=0)] - protocol: NetworkApprovalProtocol - target: str - type: Annotated[ - Literal["networkAccess"], - Field(title="NetworkAccessGuardianApprovalReviewActionType"), - ] - - -class HookOutputEntry(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - kind: HookOutputEntryKind - text: str - - -class HookRunSummary(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - completed_at: Annotated[int | None, Field(alias="completedAt")] = None - display_order: Annotated[int, Field(alias="displayOrder")] - duration_ms: Annotated[int | None, Field(alias="durationMs")] = None - entries: list[HookOutputEntry] - event_name: Annotated[HookEventName, Field(alias="eventName")] - execution_mode: Annotated[HookExecutionMode, Field(alias="executionMode")] - handler_type: Annotated[HookHandlerType, Field(alias="handlerType")] - id: str - scope: HookScope - source: HookSource | None = "unknown" - source_path: Annotated[AbsolutePathBuf, Field(alias="sourcePath")] - started_at: Annotated[int, Field(alias="startedAt")] - status: HookRunStatus - status_message: Annotated[str | None, Field(alias="statusMessage")] = None - - -class HookStartedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - run: HookRunSummary - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str | None, Field(alias="turnId")] = None - - -class ListMcpServerStatusParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cursor: Annotated[ - str | None, - Field(description="Opaque pagination cursor returned by a previous call."), - ] = None - detail: Annotated[ - McpServerStatusDetail | None, - Field( - description="Controls how much MCP inventory data to fetch for each server. Defaults to `Full` when omitted." - ), - ] = None - limit: Annotated[ - int | None, - Field( - description="Optional page size; defaults to a server-defined value.", ge=0 - ), - ] = None - - -class McpResourceReadResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - contents: list[ResourceContent] - - -class McpServerStatus(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - auth_status: Annotated[McpAuthStatus, Field(alias="authStatus")] - name: str - resource_templates: Annotated[ - list[ResourceTemplate], Field(alias="resourceTemplates") - ] - resources: list[Resource] - tools: dict[str, Tool] - - -class MemoryCitation(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - entries: list[MemoryCitationEntry] - thread_ids: Annotated[list[str], Field(alias="threadIds")] - - -class MigrationDetails(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - plugins: list[PluginsMigration] - - -class Model(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - additional_speed_tiers: Annotated[ - list[str] | None, Field(alias="additionalSpeedTiers") - ] = [] - availability_nux: Annotated[ - ModelAvailabilityNux | None, Field(alias="availabilityNux") - ] = None - default_reasoning_effort: Annotated[ - ReasoningEffort, Field(alias="defaultReasoningEffort") - ] - description: str - display_name: Annotated[str, Field(alias="displayName")] - hidden: bool - id: str - input_modalities: Annotated[ - list[InputModality] | None, Field(alias="inputModalities") - ] = ["text", "image"] - is_default: Annotated[bool, Field(alias="isDefault")] - model: str - supported_reasoning_efforts: Annotated[ - list[ReasoningEffortOption], Field(alias="supportedReasoningEfforts") - ] - supports_personality: Annotated[bool | None, Field(alias="supportsPersonality")] = ( - False - ) - upgrade: str | None = None - upgrade_info: Annotated[ModelUpgradeInfo | None, Field(alias="upgradeInfo")] = None - - -class ModelListResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - data: list[Model] - next_cursor: Annotated[ - str | None, - Field( - alias="nextCursor", - description="Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", - ), - ] = None - - -class OverriddenMetadata(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - effective_value: Annotated[Any, Field(alias="effectiveValue")] - message: str - overriding_layer: Annotated[ConfigLayerMetadata, Field(alias="overridingLayer")] - - -class PluginDetail(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - apps: list[AppSummary] - description: str | None = None - marketplace_name: Annotated[str, Field(alias="marketplaceName")] - marketplace_path: Annotated[AbsolutePathBuf, Field(alias="marketplacePath")] - mcp_servers: Annotated[list[str], Field(alias="mcpServers")] - skills: list[SkillSummary] - summary: PluginSummary - - -class PluginMarketplaceEntry(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - interface: MarketplaceInterface | None = None - name: str - path: Annotated[ - AbsolutePathBuf | None, - Field( - description="Local marketplace file path when the marketplace is backed by a local file. Remote-only catalog marketplaces do not have a local path." - ), - ] = None - plugins: list[PluginSummary] - - -class PluginReadResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - plugin: PluginDetail - - -class RateLimitSnapshot(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - credits: CreditsSnapshot | None = None - limit_id: Annotated[str | None, Field(alias="limitId")] = None - limit_name: Annotated[str | None, Field(alias="limitName")] = None - plan_type: Annotated[PlanType | None, Field(alias="planType")] = None - primary: RateLimitWindow | None = None - rate_limit_reached_type: Annotated[ - RateLimitReachedType | None, Field(alias="rateLimitReachedType") - ] = None - secondary: RateLimitWindow | None = None - - -class MessageResponseItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - content: list[ContentItem] - end_turn: bool | None = None - id: str | None = None - phase: MessagePhase | None = None - role: str - type: Annotated[Literal["message"], Field(title="MessageResponseItemType")] - - -class WebSearchCallResponseItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - action: ResponsesApiWebSearchAction | None = None - id: str | None = None - status: str | None = None - type: Annotated[ - Literal["web_search_call"], Field(title="WebSearchCallResponseItemType") - ] - - -class ReviewStartParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - delivery: Annotated[ - ReviewDelivery | None, - Field( - description="Where to run the review: inline (default) on the current thread or detached on a new thread (returned in `reviewThreadId`)." - ), - ] = None - target: ReviewTarget - thread_id: Annotated[str, Field(alias="threadId")] - - -class ThreadStatusChangedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/status/changed"], - Field(title="Thread/status/changedNotificationMethod"), - ] - params: ThreadStatusChangedNotification - - -class ThreadArchivedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/archived"], Field(title="Thread/archivedNotificationMethod") - ] - params: ThreadArchivedNotification - - -class ThreadUnarchivedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/unarchived"], Field(title="Thread/unarchivedNotificationMethod") - ] - params: ThreadUnarchivedNotification - - -class ThreadClosedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/closed"], Field(title="Thread/closedNotificationMethod") - ] - params: ThreadClosedNotification - - -class SkillsChangedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["skills/changed"], Field(title="Skills/changedNotificationMethod") - ] - params: SkillsChangedNotification - - -class ThreadNameUpdatedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/name/updated"], - Field(title="Thread/name/updatedNotificationMethod"), - ] - params: ThreadNameUpdatedNotification - - -class HookStartedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["hook/started"], Field(title="Hook/startedNotificationMethod") - ] - params: HookStartedNotification - - -class TurnDiffUpdatedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["turn/diff/updated"], Field(title="Turn/diff/updatedNotificationMethod") - ] - params: TurnDiffUpdatedNotification - - -class CommandExecOutputDeltaServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["command/exec/outputDelta"], - Field(title="Command/exec/outputDeltaNotificationMethod"), - ] - params: CommandExecOutputDeltaNotification - - -class ItemCommandExecutionTerminalInteractionServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["item/commandExecution/terminalInteraction"], - Field(title="Item/commandExecution/terminalInteractionNotificationMethod"), - ] - params: TerminalInteractionNotification - - -class ServerRequestResolvedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["serverRequest/resolved"], - Field(title="ServerRequest/resolvedNotificationMethod"), - ] - params: ServerRequestResolvedNotification - - -class AccountUpdatedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["account/updated"], Field(title="Account/updatedNotificationMethod") - ] - params: AccountUpdatedNotification - - -class WarningServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[Literal["warning"], Field(title="WarningNotificationMethod")] - params: WarningNotification - - -class ConfigWarningServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["configWarning"], Field(title="ConfigWarningNotificationMethod") - ] - params: ConfigWarningNotification - - -class ThreadRealtimeStartedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/realtime/started"], - Field(title="Thread/realtime/startedNotificationMethod"), - ] - params: ThreadRealtimeStartedNotification - - -class ThreadRealtimeItemAddedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/realtime/itemAdded"], - Field(title="Thread/realtime/itemAddedNotificationMethod"), - ] - params: ThreadRealtimeItemAddedNotification - - -class ThreadRealtimeTranscriptDeltaServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/realtime/transcript/delta"], - Field(title="Thread/realtime/transcript/deltaNotificationMethod"), - ] - params: ThreadRealtimeTranscriptDeltaNotification - - -class ThreadRealtimeTranscriptDoneServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/realtime/transcript/done"], - Field(title="Thread/realtime/transcript/doneNotificationMethod"), - ] - params: ThreadRealtimeTranscriptDoneNotification - - -class ThreadRealtimeOutputAudioDeltaServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/realtime/outputAudio/delta"], - Field(title="Thread/realtime/outputAudio/deltaNotificationMethod"), - ] - params: ThreadRealtimeOutputAudioDeltaNotification - - -class ThreadRealtimeSdpServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/realtime/sdp"], - Field(title="Thread/realtime/sdpNotificationMethod"), - ] - params: ThreadRealtimeSdpNotification - - -class ThreadRealtimeErrorServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/realtime/error"], - Field(title="Thread/realtime/errorNotificationMethod"), - ] - params: ThreadRealtimeErrorNotification - - -class ThreadRealtimeClosedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/realtime/closed"], - Field(title="Thread/realtime/closedNotificationMethod"), - ] - params: ThreadRealtimeClosedNotification - - -class WindowsWorldWritableWarningServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["windows/worldWritableWarning"], - Field(title="Windows/worldWritableWarningNotificationMethod"), - ] - params: WindowsWorldWritableWarningNotification - - -class SkillDependencies(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - tools: list[SkillToolDependency] - - -class SkillMetadata(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - dependencies: SkillDependencies | None = None - description: str - enabled: bool - interface: SkillInterface | None = None - name: str - path: AbsolutePathBuf - scope: SkillScope - short_description: Annotated[ - str | None, - Field( - alias="shortDescription", - description="Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.", - ), - ] = None - - -class SkillsListEntry(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cwd: str - errors: list[SkillErrorInfo] - skills: list[SkillMetadata] - - -class SkillsListResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - data: list[SkillsListEntry] - - -class ThreadSpawn(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - agent_nickname: str | None = None - agent_path: AgentPath | None = None - agent_role: str | None = None - depth: int - parent_thread_id: ThreadId - - -class ThreadSpawnSubAgentSource(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - thread_spawn: ThreadSpawn - - -class SubAgentSource( - RootModel[SubAgentSourceValue | ThreadSpawnSubAgentSource | OtherSubAgentSource] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: SubAgentSourceValue | ThreadSpawnSubAgentSource | OtherSubAgentSource - - -class UserMessageThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - content: list[UserInput] - id: str - type: Annotated[Literal["userMessage"], Field(title="UserMessageThreadItemType")] - - -class AgentMessageThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: str - memory_citation: Annotated[MemoryCitation | None, Field(alias="memoryCitation")] = ( - None - ) - phase: MessagePhase | None = None - text: str - type: Annotated[Literal["agentMessage"], Field(title="AgentMessageThreadItemType")] - - -class FileChangeThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - changes: list[FileUpdateChange] - id: str - status: PatchApplyStatus - type: Annotated[Literal["fileChange"], Field(title="FileChangeThreadItemType")] - - -class CollabAgentToolCallThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - agents_states: Annotated[ - dict[str, CollabAgentState], - Field( - alias="agentsStates", - description="Last known status of the target agents, when available.", - ), - ] - id: Annotated[ - str, Field(description="Unique identifier for this collab tool call.") - ] - model: Annotated[ - str | None, - Field(description="Model requested for the spawned agent, when applicable."), - ] = None - prompt: Annotated[ - str | None, - Field( - description="Prompt text sent as part of the collab tool call, when available." - ), - ] = None - reasoning_effort: Annotated[ - ReasoningEffort | None, - Field( - alias="reasoningEffort", - description="Reasoning effort requested for the spawned agent, when applicable.", - ), - ] = None - receiver_thread_ids: Annotated[ - list[str], - Field( - alias="receiverThreadIds", - description="Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", - ), - ] - sender_thread_id: Annotated[ - str, - Field( - alias="senderThreadId", - description="Thread ID of the agent issuing the collab request.", - ), - ] - status: Annotated[ - CollabAgentToolCallStatus, - Field(description="Current status of the collab tool call."), - ] - tool: Annotated[ - CollabAgentTool, Field(description="Name of the collab tool that was invoked.") - ] - type: Annotated[ - Literal["collabAgentToolCall"], Field(title="CollabAgentToolCallThreadItemType") - ] - - -class WebSearchThreadItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - action: WebSearchAction | None = None - id: str - query: str - type: Annotated[Literal["webSearch"], Field(title="WebSearchThreadItemType")] - - -class ThreadItem( - RootModel[ - UserMessageThreadItem - | HookPromptThreadItem - | AgentMessageThreadItem - | PlanThreadItem - | ReasoningThreadItem - | CommandExecutionThreadItem - | FileChangeThreadItem - | McpToolCallThreadItem - | DynamicToolCallThreadItem - | CollabAgentToolCallThreadItem - | WebSearchThreadItem - | ImageViewThreadItem - | ImageGenerationThreadItem - | EnteredReviewModeThreadItem - | ExitedReviewModeThreadItem - | ContextCompactionThreadItem - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ( - UserMessageThreadItem - | HookPromptThreadItem - | AgentMessageThreadItem - | PlanThreadItem - | ReasoningThreadItem - | CommandExecutionThreadItem - | FileChangeThreadItem - | McpToolCallThreadItem - | DynamicToolCallThreadItem - | CollabAgentToolCallThreadItem - | WebSearchThreadItem - | ImageViewThreadItem - | ImageGenerationThreadItem - | EnteredReviewModeThreadItem - | ExitedReviewModeThreadItem - | ContextCompactionThreadItem - ) - - -class ThreadListParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - archived: Annotated[ - bool | None, - Field( - description="Optional archived filter; when set to true, only archived threads are returned. If false or null, only non-archived threads are returned." - ), - ] = None - cursor: Annotated[ - str | None, - Field(description="Opaque pagination cursor returned by a previous call."), - ] = None - cwd: Annotated[ - str | None, - Field( - description="Optional cwd filter; when set, only threads whose session cwd exactly matches this path are returned." - ), - ] = None - limit: Annotated[ - int | None, - Field( - description="Optional page size; defaults to a reasonable server-side value.", - ge=0, - ), - ] = None - model_providers: Annotated[ - list[str] | None, - Field( - alias="modelProviders", - description="Optional provider filter; when set, only sessions recorded under these providers are returned. When present but empty, includes all providers.", - ), - ] = None - search_term: Annotated[ - str | None, - Field( - alias="searchTerm", - description="Optional substring filter for the extracted thread title.", - ), - ] = None - sort_direction: Annotated[ - SortDirection | None, - Field( - alias="sortDirection", - description="Optional sort direction; defaults to descending (newest first).", - ), - ] = None - sort_key: Annotated[ - ThreadSortKey | None, - Field( - alias="sortKey", description="Optional sort key; defaults to created_at." - ), - ] = None - source_kinds: Annotated[ - list[ThreadSourceKind] | None, - Field( - alias="sourceKinds", - description="Optional source filter; when set, only sessions from these source kinds are returned. When omitted or empty, defaults to interactive sources.", - ), - ] = None - - -class ThreadStartParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - approval_policy: Annotated[AskForApproval | None, Field(alias="approvalPolicy")] = ( - None - ) - approvals_reviewer: Annotated[ - ApprovalsReviewer | None, - Field( - alias="approvalsReviewer", - description="Override where approval requests are routed for review on this thread and subsequent turns.", - ), - ] = None - base_instructions: Annotated[str | None, Field(alias="baseInstructions")] = None - config: dict[str, Any] | None = None - cwd: str | None = None - developer_instructions: Annotated[ - str | None, Field(alias="developerInstructions") - ] = None - ephemeral: bool | None = None - model: str | None = None - model_provider: Annotated[str | None, Field(alias="modelProvider")] = None - personality: Personality | None = None - sandbox: SandboxMode | None = None - service_name: Annotated[str | None, Field(alias="serviceName")] = None - service_tier: Annotated[ServiceTier | None, Field(alias="serviceTier")] = None - session_start_source: Annotated[ - ThreadStartSource | None, Field(alias="sessionStartSource") - ] = None - - -class ThreadTokenUsage(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - last: TokenUsageBreakdown - model_context_window: Annotated[int | None, Field(alias="modelContextWindow")] = ( - None - ) - total: TokenUsageBreakdown - - -class ThreadTokenUsageUpdatedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread_id: Annotated[str, Field(alias="threadId")] - token_usage: Annotated[ThreadTokenUsage, Field(alias="tokenUsage")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class ThreadUnsubscribeResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - status: ThreadUnsubscribeStatus - - -class ToolsV2(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - view_image: bool | None = None - web_search: WebSearchToolConfig | None = None - - -class TurnError(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - additional_details: Annotated[str | None, Field(alias="additionalDetails")] = None - codex_error_info: Annotated[ - CodexErrorInfo | None, Field(alias="codexErrorInfo") - ] = None - message: str - - -class TurnPlanStep(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - status: TurnPlanStepStatus - step: str - - -class TurnPlanUpdatedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - explanation: str | None = None - plan: list[TurnPlanStep] - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class TurnStartParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - approval_policy: Annotated[ - AskForApproval | None, - Field( - alias="approvalPolicy", - description="Override the approval policy for this turn and subsequent turns.", - ), - ] = None - approvals_reviewer: Annotated[ - ApprovalsReviewer | None, - Field( - alias="approvalsReviewer", - description="Override where approval requests are routed for review on this turn and subsequent turns.", - ), - ] = None - cwd: Annotated[ - str | None, - Field( - description="Override the working directory for this turn and subsequent turns." - ), - ] = None - effort: Annotated[ - ReasoningEffort | None, - Field( - description="Override the reasoning effort for this turn and subsequent turns." - ), - ] = None - input: list[UserInput] - model: Annotated[ - str | None, - Field(description="Override the model for this turn and subsequent turns."), - ] = None - output_schema: Annotated[ - Any | None, - Field( - alias="outputSchema", - description="Optional JSON Schema used to constrain the final assistant message for this turn.", - ), - ] = None - personality: Annotated[ - Personality | None, - Field( - description="Override the personality for this turn and subsequent turns." - ), - ] = None - sandbox_policy: Annotated[ - SandboxPolicy | None, - Field( - alias="sandboxPolicy", - description="Override the sandbox policy for this turn and subsequent turns.", - ), - ] = None - service_tier: Annotated[ - ServiceTier | None, - Field( - alias="serviceTier", - description="Override the service tier for this turn and subsequent turns.", - ), - ] = None - summary: Annotated[ - ReasoningSummary | None, - Field( - description="Override the reasoning summary for this turn and subsequent turns." - ), - ] = None - thread_id: Annotated[str, Field(alias="threadId")] - - -class TurnSteerParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - expected_turn_id: Annotated[ - str, - Field( - alias="expectedTurnId", - description="Required active turn id precondition. The request fails when it does not match the currently active turn.", - ), - ] - input: list[UserInput] - thread_id: Annotated[str, Field(alias="threadId")] - - -class WindowsSandboxSetupCompletedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - error: str | None = None - mode: WindowsSandboxSetupMode - success: bool - - -class AccountRateLimitsUpdatedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - rate_limits: Annotated[RateLimitSnapshot, Field(alias="rateLimits")] - - -class AdditionalFileSystemPermissions(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - entries: list[FileSystemSandboxEntry] | None = None - glob_scan_max_depth: Annotated[ - int | None, Field(alias="globScanMaxDepth", ge=1) - ] = None - read: list[AbsolutePathBuf] | None = None - write: list[AbsolutePathBuf] | None = None - - -class AppInfo(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - app_metadata: Annotated[AppMetadata | None, Field(alias="appMetadata")] = None - branding: AppBranding | None = None - description: str | None = None - distribution_channel: Annotated[str | None, Field(alias="distributionChannel")] = ( - None - ) - id: str - install_url: Annotated[str | None, Field(alias="installUrl")] = None - is_accessible: Annotated[bool | None, Field(alias="isAccessible")] = False - is_enabled: Annotated[ - bool | None, - Field( - alias="isEnabled", - description="Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```", - ), - ] = True - labels: dict[str, Any] | None = None - logo_url: Annotated[str | None, Field(alias="logoUrl")] = None - logo_url_dark: Annotated[str | None, Field(alias="logoUrlDark")] = None - name: str - plugin_display_names: Annotated[ - list[str] | None, Field(alias="pluginDisplayNames") - ] = [] - - -class AppListUpdatedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - data: list[AppInfo] - - -class AppsListResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - data: list[AppInfo] - next_cursor: Annotated[ - str | None, - Field( - alias="nextCursor", - description="Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", - ), - ] = None - - -class ThreadStartRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["thread/start"], Field(title="Thread/startRequestMethod")] - params: ThreadStartParams - - -class ThreadListRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["thread/list"], Field(title="Thread/listRequestMethod")] - params: ThreadListParams - - -class TurnStartRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["turn/start"], Field(title="Turn/startRequestMethod")] - params: TurnStartParams - - -class TurnSteerRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["turn/steer"], Field(title="Turn/steerRequestMethod")] - params: TurnSteerParams - - -class ReviewStartRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["review/start"], Field(title="Review/startRequestMethod")] - params: ReviewStartParams - - -class McpServerStatusListRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["mcpServerStatus/list"], - Field(title="McpServerStatus/listRequestMethod"), - ] - params: ListMcpServerStatusParams - - -class CommandExecRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[Literal["command/exec"], Field(title="Command/execRequestMethod")] - params: CommandExecParams - - -class CommandExecResizeRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["command/exec/resize"], Field(title="Command/exec/resizeRequestMethod") - ] - params: CommandExecResizeParams - - -class ConfigValueWriteRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["config/value/write"], Field(title="Config/value/writeRequestMethod") - ] - params: ConfigValueWriteParams - - -class ConfigBatchWriteParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - edits: list[ConfigEdit] - expected_version: Annotated[str | None, Field(alias="expectedVersion")] = None - file_path: Annotated[ - str | None, - Field( - alias="filePath", - description="Path to the config file to write; defaults to the user's `config.toml` when omitted.", - ), - ] = None - reload_user_config: Annotated[ - bool | None, - Field( - alias="reloadUserConfig", - description="When true, hot-reload the updated user config into all loaded threads after writing.", - ), - ] = None - - -class ConfigWriteResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - file_path: Annotated[ - AbsolutePathBuf, - Field( - alias="filePath", - description="Canonical path to the config file that was written.", - ), - ] - overridden_metadata: Annotated[ - OverriddenMetadata | None, Field(alias="overriddenMetadata") - ] = None - status: WriteStatus - version: str - - -class ErrorNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - error: TurnError - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - will_retry: Annotated[bool, Field(alias="willRetry")] - - -class ExternalAgentConfigMigrationItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - cwd: Annotated[ - str | None, - Field( - description="Null or empty means home-scoped migration; non-empty means repo-scoped migration." - ), - ] = None - description: str - details: MigrationDetails | None = None - item_type: Annotated[ExternalAgentConfigMigrationItemType, Field(alias="itemType")] - - -class FileChangePatchUpdatedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - changes: list[FileUpdateChange] - item_id: Annotated[str, Field(alias="itemId")] - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class FunctionCallOutputBody(RootModel[str | list[FunctionCallOutputContentItem]]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: str | list[FunctionCallOutputContentItem] - - -class GetAccountRateLimitsResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - rate_limits: Annotated[ - RateLimitSnapshot, - Field( - alias="rateLimits", - description="Backward-compatible single-bucket view; mirrors the historical payload.", - ), - ] - rate_limits_by_limit_id: Annotated[ - dict[str, Any] | None, - Field( - alias="rateLimitsByLimitId", - description="Multi-bucket view keyed by metered `limit_id` (for example, `codex`).", - ), - ] = None - - -class HookCompletedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - run: HookRunSummary - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str | None, Field(alias="turnId")] = None - - -class ItemCompletedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - item: ThreadItem - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class ItemStartedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - item: ThreadItem - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class ListMcpServerStatusResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - data: list[McpServerStatus] - next_cursor: Annotated[ - str | None, - Field( - alias="nextCursor", - description="Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", - ), - ] = None - - -class PluginListResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - featured_plugin_ids: Annotated[ - list[str] | None, Field(alias="featuredPluginIds") - ] = [] - marketplace_load_errors: Annotated[ - list[MarketplaceLoadErrorInfo] | None, Field(alias="marketplaceLoadErrors") - ] = [] - marketplaces: list[PluginMarketplaceEntry] - - -class ProfileV2(BaseModel): - model_config = ConfigDict( - extra="allow", - populate_by_name=True, - ) - approval_policy: AskForApproval | None = None - approvals_reviewer: Annotated[ - ApprovalsReviewer | None, - Field( - description="[UNSTABLE] Optional profile-level override for where approval requests are routed for review. If omitted, the enclosing config default is used." - ), - ] = None - chatgpt_base_url: str | None = None - model: str | None = None - model_provider: str | None = None - model_reasoning_effort: ReasoningEffort | None = None - model_reasoning_summary: ReasoningSummary | None = None - model_verbosity: Verbosity | None = None - service_tier: ServiceTier | None = None - tools: ToolsV2 | None = None - web_search: WebSearchMode | None = None - - -class RequestPermissionProfile(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - file_system: Annotated[ - AdditionalFileSystemPermissions | None, Field(alias="fileSystem") - ] = None - network: AdditionalNetworkPermissions | None = None - - -class FunctionCallOutputResponseItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - call_id: str - output: FunctionCallOutputBody - type: Annotated[ - Literal["function_call_output"], - Field(title="FunctionCallOutputResponseItemType"), - ] - - -class CustomToolCallOutputResponseItem(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - call_id: str - name: str | None = None - output: FunctionCallOutputBody - type: Annotated[ - Literal["custom_tool_call_output"], - Field(title="CustomToolCallOutputResponseItemType"), - ] - - -class ResponseItem( - RootModel[ - MessageResponseItem - | ReasoningResponseItem - | LocalShellCallResponseItem - | FunctionCallResponseItem - | ToolSearchCallResponseItem - | FunctionCallOutputResponseItem - | CustomToolCallResponseItem - | CustomToolCallOutputResponseItem - | ToolSearchOutputResponseItem - | WebSearchCallResponseItem - | ImageGenerationCallResponseItem - | GhostSnapshotResponseItem - | CompactionResponseItem - | OtherResponseItem - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ( - MessageResponseItem - | ReasoningResponseItem - | LocalShellCallResponseItem - | FunctionCallResponseItem - | ToolSearchCallResponseItem - | FunctionCallOutputResponseItem - | CustomToolCallResponseItem - | CustomToolCallOutputResponseItem - | ToolSearchOutputResponseItem - | WebSearchCallResponseItem - | ImageGenerationCallResponseItem - | GhostSnapshotResponseItem - | CompactionResponseItem - | OtherResponseItem - ) - - -class ErrorServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[Literal["error"], Field(title="ErrorNotificationMethod")] - params: ErrorNotification - - -class ThreadTokenUsageUpdatedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/tokenUsage/updated"], - Field(title="Thread/tokenUsage/updatedNotificationMethod"), - ] - params: ThreadTokenUsageUpdatedNotification - - -class HookCompletedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["hook/completed"], Field(title="Hook/completedNotificationMethod") - ] - params: HookCompletedNotification - - -class TurnPlanUpdatedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["turn/plan/updated"], Field(title="Turn/plan/updatedNotificationMethod") - ] - params: TurnPlanUpdatedNotification - - -class ItemStartedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["item/started"], Field(title="Item/startedNotificationMethod") - ] - params: ItemStartedNotification - - -class ItemCompletedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["item/completed"], Field(title="Item/completedNotificationMethod") - ] - params: ItemCompletedNotification - - -class ItemFileChangePatchUpdatedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["item/fileChange/patchUpdated"], - Field(title="Item/fileChange/patchUpdatedNotificationMethod"), - ] - params: FileChangePatchUpdatedNotification - - -class AccountRateLimitsUpdatedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["account/rateLimits/updated"], - Field(title="Account/rateLimits/updatedNotificationMethod"), - ] - params: AccountRateLimitsUpdatedNotification - - -class AppListUpdatedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["app/list/updated"], Field(title="App/list/updatedNotificationMethod") - ] - params: AppListUpdatedNotification - - -class WindowsSandboxSetupCompletedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["windowsSandbox/setupCompleted"], - Field(title="WindowsSandbox/setupCompletedNotificationMethod"), - ] - params: WindowsSandboxSetupCompletedNotification - - -class SubAgentSessionSource(BaseModel): - model_config = ConfigDict( - extra="forbid", - populate_by_name=True, - ) - sub_agent: Annotated[SubAgentSource, Field(alias="subAgent")] - - -class SessionSource( - RootModel[SessionSourceValue | CustomSessionSource | SubAgentSessionSource] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: SessionSourceValue | CustomSessionSource | SubAgentSessionSource - - -class Turn(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - completed_at: Annotated[ - int | None, - Field( - alias="completedAt", - description="Unix timestamp (in seconds) when the turn completed.", - ), - ] = None - duration_ms: Annotated[ - int | None, - Field( - alias="durationMs", - description="Duration between turn start and completion in milliseconds, if known.", - ), - ] = None - error: Annotated[ - TurnError | None, - Field(description="Only populated when the Turn's status is failed."), - ] = None - id: str - items: Annotated[ - list[ThreadItem], - Field( - description="Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list." - ), - ] - started_at: Annotated[ - int | None, - Field( - alias="startedAt", - description="Unix timestamp (in seconds) when the turn started.", - ), - ] = None - status: TurnStatus - - -class TurnCompletedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread_id: Annotated[str, Field(alias="threadId")] - turn: Turn - - -class TurnStartResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - turn: Turn - - -class TurnStartedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread_id: Annotated[str, Field(alias="threadId")] - turn: Turn - - -class ConfigBatchWriteRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["config/batchWrite"], Field(title="Config/batchWriteRequestMethod") - ] - params: ConfigBatchWriteParams - - -class Config(BaseModel): - model_config = ConfigDict( - extra="allow", - populate_by_name=True, - ) - analytics: AnalyticsConfig | None = None - approval_policy: AskForApproval | None = None - approvals_reviewer: Annotated[ - ApprovalsReviewer | None, - Field( - description="[UNSTABLE] Optional default for where approval requests are routed for review." - ), - ] = None - compact_prompt: str | None = None - developer_instructions: str | None = None - forced_chatgpt_workspace_id: str | None = None - forced_login_method: ForcedLoginMethod | None = None - instructions: str | None = None - model: str | None = None - model_auto_compact_token_limit: int | None = None - model_context_window: int | None = None - model_provider: str | None = None - model_reasoning_effort: ReasoningEffort | None = None - model_reasoning_summary: ReasoningSummary | None = None - model_verbosity: Verbosity | None = None - profile: str | None = None - profiles: dict[str, ProfileV2] | None = {} - review_model: str | None = None - sandbox_mode: SandboxMode | None = None - sandbox_workspace_write: SandboxWorkspaceWrite | None = None - service_tier: ServiceTier | None = None - tools: ToolsV2 | None = None - web_search: WebSearchMode | None = None - - -class ConfigReadResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - config: Config - layers: list[ConfigLayer] | None = None - origins: dict[str, ConfigLayerMetadata] - - -class ExternalAgentConfigDetectResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - items: list[ExternalAgentConfigMigrationItem] - - -class ExternalAgentConfigImportParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - migration_items: Annotated[ - list[ExternalAgentConfigMigrationItem], Field(alias="migrationItems") - ] - - -class RequestPermissionsGuardianApprovalReviewAction(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - permissions: RequestPermissionProfile - reason: str | None = None - type: Annotated[ - Literal["requestPermissions"], - Field(title="RequestPermissionsGuardianApprovalReviewActionType"), - ] - - -class GuardianApprovalReviewAction( - RootModel[ - CommandGuardianApprovalReviewAction - | ExecveGuardianApprovalReviewAction - | ApplyPatchGuardianApprovalReviewAction - | NetworkAccessGuardianApprovalReviewAction - | McpToolCallGuardianApprovalReviewAction - | RequestPermissionsGuardianApprovalReviewAction - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ( - CommandGuardianApprovalReviewAction - | ExecveGuardianApprovalReviewAction - | ApplyPatchGuardianApprovalReviewAction - | NetworkAccessGuardianApprovalReviewAction - | McpToolCallGuardianApprovalReviewAction - | RequestPermissionsGuardianApprovalReviewAction - ) - - -class ItemGuardianApprovalReviewCompletedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - action: GuardianApprovalReviewAction - decision_source: Annotated[AutoReviewDecisionSource, Field(alias="decisionSource")] - review: GuardianApprovalReview - review_id: Annotated[ - str, Field(alias="reviewId", description="Stable identifier for this review.") - ] - target_item_id: Annotated[ - str | None, - Field( - alias="targetItemId", - description="Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", - ), - ] = None - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class ItemGuardianApprovalReviewStartedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - action: GuardianApprovalReviewAction - review: GuardianApprovalReview - review_id: Annotated[ - str, Field(alias="reviewId", description="Stable identifier for this review.") - ] - target_item_id: Annotated[ - str | None, - Field( - alias="targetItemId", - description="Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", - ), - ] = None - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class RawResponseItemCompletedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - item: ResponseItem - thread_id: Annotated[str, Field(alias="threadId")] - turn_id: Annotated[str, Field(alias="turnId")] - - -class ReviewStartResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - review_thread_id: Annotated[ - str, - Field( - alias="reviewThreadId", - description="Identifies the thread where the review runs.\n\nFor inline reviews, this is the original thread id. For detached reviews, this is the id of the new review thread.", - ), - ] - turn: Turn - - -class TurnStartedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["turn/started"], Field(title="Turn/startedNotificationMethod") - ] - params: TurnStartedNotification - - -class TurnCompletedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["turn/completed"], Field(title="Turn/completedNotificationMethod") - ] - params: TurnCompletedNotification - - -class ItemAutoApprovalReviewStartedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["item/autoApprovalReview/started"], - Field(title="Item/autoApprovalReview/startedNotificationMethod"), - ] - params: ItemGuardianApprovalReviewStartedNotification - - -class ItemAutoApprovalReviewCompletedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["item/autoApprovalReview/completed"], - Field(title="Item/autoApprovalReview/completedNotificationMethod"), - ] - params: ItemGuardianApprovalReviewCompletedNotification - - -class Thread(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - agent_nickname: Annotated[ - str | None, - Field( - alias="agentNickname", - description="Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", - ), - ] = None - agent_role: Annotated[ - str | None, - Field( - alias="agentRole", - description="Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", - ), - ] = None - cli_version: Annotated[ - str, - Field( - alias="cliVersion", - description="Version of the CLI that created the thread.", - ), - ] - created_at: Annotated[ - int, - Field( - alias="createdAt", - description="Unix timestamp (in seconds) when the thread was created.", - ), - ] - cwd: Annotated[ - AbsolutePathBuf, Field(description="Working directory captured for the thread.") - ] - ephemeral: Annotated[ - bool, - Field( - description="Whether the thread is ephemeral and should not be materialized on disk." - ), - ] - forked_from_id: Annotated[ - str | None, - Field( - alias="forkedFromId", - description="Source thread id when this thread was created by forking another thread.", - ), - ] = None - git_info: Annotated[ - GitInfo | None, - Field( - alias="gitInfo", - description="Optional Git metadata captured when the thread was created.", - ), - ] = None - id: str - model_provider: Annotated[ - str, - Field( - alias="modelProvider", - description="Model provider used for this thread (for example, 'openai').", - ), - ] - name: Annotated[ - str | None, Field(description="Optional user-facing thread title.") - ] = None - path: Annotated[ - str | None, Field(description="[UNSTABLE] Path to the thread on disk.") - ] = None - preview: Annotated[ - str, - Field( - description="Usually the first user message in the thread, if available." - ), - ] - source: Annotated[ - SessionSource, - Field( - description="Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.)." - ), - ] - status: Annotated[ - ThreadStatus, Field(description="Current runtime status for the thread.") - ] - turns: Annotated[ - list[Turn], - Field( - description="Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list." - ), - ] - updated_at: Annotated[ - int, - Field( - alias="updatedAt", - description="Unix timestamp (in seconds) when the thread was last updated.", - ), - ] - - -class ThreadForkResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - approval_policy: Annotated[AskForApproval, Field(alias="approvalPolicy")] - approvals_reviewer: Annotated[ - ApprovalsReviewer, - Field( - alias="approvalsReviewer", - description="Reviewer currently used for approval requests on this thread.", - ), - ] - cwd: AbsolutePathBuf - instruction_sources: Annotated[ - list[AbsolutePathBuf] | None, - Field( - alias="instructionSources", - description="Instruction source files currently loaded for this thread.", - ), - ] = [] - model: str - model_provider: Annotated[str, Field(alias="modelProvider")] - reasoning_effort: Annotated[ - ReasoningEffort | None, Field(alias="reasoningEffort") - ] = None - sandbox: SandboxPolicy - service_tier: Annotated[ServiceTier | None, Field(alias="serviceTier")] = None - thread: Thread - - -class ThreadListResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - backwards_cursor: Annotated[ - str | None, - Field( - alias="backwardsCursor", - description="Opaque cursor to pass as `cursor` when reversing `sortDirection`. This is only populated when the page contains at least one thread. Use it with the opposite `sortDirection`; for timestamp sorts it anchors at the start of the page timestamp so same-second updates are not skipped.", - ), - ] = None - data: list[Thread] - next_cursor: Annotated[ - str | None, - Field( - alias="nextCursor", - description="Opaque cursor to pass to the next call to continue after the last item. if None, there are no more items to return.", - ), - ] = None - - -class ThreadMetadataUpdateResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread: Thread - - -class ThreadReadResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread: Thread - - -class ThreadResumeResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - approval_policy: Annotated[AskForApproval, Field(alias="approvalPolicy")] - approvals_reviewer: Annotated[ - ApprovalsReviewer, - Field( - alias="approvalsReviewer", - description="Reviewer currently used for approval requests on this thread.", - ), - ] - cwd: AbsolutePathBuf - instruction_sources: Annotated[ - list[AbsolutePathBuf] | None, - Field( - alias="instructionSources", - description="Instruction source files currently loaded for this thread.", - ), - ] = [] - model: str - model_provider: Annotated[str, Field(alias="modelProvider")] - reasoning_effort: Annotated[ - ReasoningEffort | None, Field(alias="reasoningEffort") - ] = None - sandbox: SandboxPolicy - service_tier: Annotated[ServiceTier | None, Field(alias="serviceTier")] = None - thread: Thread - - -class ThreadRollbackResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread: Annotated[ - Thread, - Field( - description="The updated thread after applying the rollback, with `turns` populated.\n\nThe ThreadItems stored in each Turn are lossy since we explicitly do not persist all agent interactions, such as command executions. This is the same behavior as `thread/resume`." - ), - ] - - -class ThreadStartResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - approval_policy: Annotated[AskForApproval, Field(alias="approvalPolicy")] - approvals_reviewer: Annotated[ - ApprovalsReviewer, - Field( - alias="approvalsReviewer", - description="Reviewer currently used for approval requests on this thread.", - ), - ] - cwd: AbsolutePathBuf - instruction_sources: Annotated[ - list[AbsolutePathBuf] | None, - Field( - alias="instructionSources", - description="Instruction source files currently loaded for this thread.", - ), - ] = [] - model: str - model_provider: Annotated[str, Field(alias="modelProvider")] - reasoning_effort: Annotated[ - ReasoningEffort | None, Field(alias="reasoningEffort") - ] = None - sandbox: SandboxPolicy - service_tier: Annotated[ServiceTier | None, Field(alias="serviceTier")] = None - thread: Thread - - -class ThreadStartedNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread: Thread - - -class ThreadTurnsListResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - backwards_cursor: Annotated[ - str | None, - Field( - alias="backwardsCursor", - description="Opaque cursor to pass as `cursor` when reversing `sortDirection`. This is only populated when the page contains at least one turn. Use it with the opposite `sortDirection` to include the anchor turn again and catch updates to that turn.", - ), - ] = None - data: list[Turn] - next_cursor: Annotated[ - str | None, - Field( - alias="nextCursor", - description="Opaque cursor to pass to the next call to continue after the last turn. if None, there are no more turns to return.", - ), - ] = None - - -class ThreadUnarchiveResponse(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - thread: Thread - - -class ExternalAgentConfigImportRequest(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: RequestId - method: Annotated[ - Literal["externalAgentConfig/import"], - Field(title="ExternalAgentConfig/importRequestMethod"), - ] - params: ExternalAgentConfigImportParams - - -class ClientRequest( - RootModel[ - InitializeRequest - | ThreadStartRequest - | ThreadResumeRequest - | ThreadForkRequest - | ThreadArchiveRequest - | ThreadUnsubscribeRequest - | ThreadNameSetRequest - | ThreadMetadataUpdateRequest - | ThreadUnarchiveRequest - | ThreadCompactStartRequest - | ThreadShellCommandRequest - | ThreadRollbackRequest - | ThreadListRequest - | ThreadLoadedListRequest - | ThreadReadRequest - | ThreadTurnsListRequest - | ThreadInjectItemsRequest - | SkillsListRequest - | MarketplaceAddRequest - | MarketplaceRemoveRequest - | PluginListRequest - | PluginReadRequest - | AppListRequest - | FsReadFileRequest - | FsWriteFileRequest - | FsCreateDirectoryRequest - | FsGetMetadataRequest - | FsReadDirectoryRequest - | FsRemoveRequest - | FsCopyRequest - | FsWatchRequest - | FsUnwatchRequest - | SkillsConfigWriteRequest - | PluginInstallRequest - | PluginUninstallRequest - | TurnStartRequest - | TurnSteerRequest - | TurnInterruptRequest - | ReviewStartRequest - | ModelListRequest - | ExperimentalFeatureListRequest - | ExperimentalFeatureEnablementSetRequest - | McpServerOauthLoginRequest - | ConfigMcpServerReloadRequest - | McpServerStatusListRequest - | McpServerResourceReadRequest - | McpServerToolCallRequest - | WindowsSandboxSetupStartRequest - | AccountLoginStartRequest - | AccountLoginCancelRequest - | AccountLogoutRequest - | AccountRateLimitsReadRequest - | AccountSendAddCreditsNudgeEmailRequest - | FeedbackUploadRequest - | CommandExecRequest - | CommandExecWriteRequest - | CommandExecTerminateRequest - | CommandExecResizeRequest - | ConfigReadRequest - | ExternalAgentConfigDetectRequest - | ExternalAgentConfigImportRequest - | ConfigValueWriteRequest - | ConfigBatchWriteRequest - | ConfigRequirementsReadRequest - | AccountReadRequest - | FuzzyFileSearchRequest - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: Annotated[ - InitializeRequest - | ThreadStartRequest - | ThreadResumeRequest - | ThreadForkRequest - | ThreadArchiveRequest - | ThreadUnsubscribeRequest - | ThreadNameSetRequest - | ThreadMetadataUpdateRequest - | ThreadUnarchiveRequest - | ThreadCompactStartRequest - | ThreadShellCommandRequest - | ThreadRollbackRequest - | ThreadListRequest - | ThreadLoadedListRequest - | ThreadReadRequest - | ThreadTurnsListRequest - | ThreadInjectItemsRequest - | SkillsListRequest - | MarketplaceAddRequest - | MarketplaceRemoveRequest - | PluginListRequest - | PluginReadRequest - | AppListRequest - | FsReadFileRequest - | FsWriteFileRequest - | FsCreateDirectoryRequest - | FsGetMetadataRequest - | FsReadDirectoryRequest - | FsRemoveRequest - | FsCopyRequest - | FsWatchRequest - | FsUnwatchRequest - | SkillsConfigWriteRequest - | PluginInstallRequest - | PluginUninstallRequest - | TurnStartRequest - | TurnSteerRequest - | TurnInterruptRequest - | ReviewStartRequest - | ModelListRequest - | ExperimentalFeatureListRequest - | ExperimentalFeatureEnablementSetRequest - | McpServerOauthLoginRequest - | ConfigMcpServerReloadRequest - | McpServerStatusListRequest - | McpServerResourceReadRequest - | McpServerToolCallRequest - | WindowsSandboxSetupStartRequest - | AccountLoginStartRequest - | AccountLoginCancelRequest - | AccountLogoutRequest - | AccountRateLimitsReadRequest - | AccountSendAddCreditsNudgeEmailRequest - | FeedbackUploadRequest - | CommandExecRequest - | CommandExecWriteRequest - | CommandExecTerminateRequest - | CommandExecResizeRequest - | ConfigReadRequest - | ExternalAgentConfigDetectRequest - | ExternalAgentConfigImportRequest - | ConfigValueWriteRequest - | ConfigBatchWriteRequest - | ConfigRequirementsReadRequest - | AccountReadRequest - | FuzzyFileSearchRequest, - Field( - description="Request from the client to the server.", title="ClientRequest" - ), - ] - - -class ThreadStartedServerNotification(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - method: Annotated[ - Literal["thread/started"], Field(title="Thread/startedNotificationMethod") - ] - params: ThreadStartedNotification - - -class ServerNotification( - RootModel[ - ErrorServerNotification - | ThreadStartedServerNotification - | ThreadStatusChangedServerNotification - | ThreadArchivedServerNotification - | ThreadUnarchivedServerNotification - | ThreadClosedServerNotification - | SkillsChangedServerNotification - | ThreadNameUpdatedServerNotification - | ThreadTokenUsageUpdatedServerNotification - | TurnStartedServerNotification - | HookStartedServerNotification - | TurnCompletedServerNotification - | HookCompletedServerNotification - | TurnDiffUpdatedServerNotification - | TurnPlanUpdatedServerNotification - | ItemStartedServerNotification - | ItemAutoApprovalReviewStartedServerNotification - | ItemAutoApprovalReviewCompletedServerNotification - | ItemCompletedServerNotification - | ItemAgentMessageDeltaServerNotification - | ItemPlanDeltaServerNotification - | CommandExecOutputDeltaServerNotification - | ItemCommandExecutionOutputDeltaServerNotification - | ItemCommandExecutionTerminalInteractionServerNotification - | ItemFileChangeOutputDeltaServerNotification - | ItemFileChangePatchUpdatedServerNotification - | ServerRequestResolvedServerNotification - | ItemMcpToolCallProgressServerNotification - | McpServerOauthLoginCompletedServerNotification - | McpServerStartupStatusUpdatedServerNotification - | AccountUpdatedServerNotification - | AccountRateLimitsUpdatedServerNotification - | AppListUpdatedServerNotification - | ExternalAgentConfigImportCompletedServerNotification - | FsChangedServerNotification - | ItemReasoningSummaryTextDeltaServerNotification - | ItemReasoningSummaryPartAddedServerNotification - | ItemReasoningTextDeltaServerNotification - | ThreadCompactedServerNotification - | ModelReroutedServerNotification - | WarningServerNotification - | DeprecationNoticeServerNotification - | ConfigWarningServerNotification - | FuzzyFileSearchSessionUpdatedServerNotification - | FuzzyFileSearchSessionCompletedServerNotification - | ThreadRealtimeStartedServerNotification - | ThreadRealtimeItemAddedServerNotification - | ThreadRealtimeTranscriptDeltaServerNotification - | ThreadRealtimeTranscriptDoneServerNotification - | ThreadRealtimeOutputAudioDeltaServerNotification - | ThreadRealtimeSdpServerNotification - | ThreadRealtimeErrorServerNotification - | ThreadRealtimeClosedServerNotification - | WindowsWorldWritableWarningServerNotification - | WindowsSandboxSetupCompletedServerNotification - | AccountLoginCompletedServerNotification - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: Annotated[ - ErrorServerNotification - | ThreadStartedServerNotification - | ThreadStatusChangedServerNotification - | ThreadArchivedServerNotification - | ThreadUnarchivedServerNotification - | ThreadClosedServerNotification - | SkillsChangedServerNotification - | ThreadNameUpdatedServerNotification - | ThreadTokenUsageUpdatedServerNotification - | TurnStartedServerNotification - | HookStartedServerNotification - | TurnCompletedServerNotification - | HookCompletedServerNotification - | TurnDiffUpdatedServerNotification - | TurnPlanUpdatedServerNotification - | ItemStartedServerNotification - | ItemAutoApprovalReviewStartedServerNotification - | ItemAutoApprovalReviewCompletedServerNotification - | ItemCompletedServerNotification - | ItemAgentMessageDeltaServerNotification - | ItemPlanDeltaServerNotification - | CommandExecOutputDeltaServerNotification - | ItemCommandExecutionOutputDeltaServerNotification - | ItemCommandExecutionTerminalInteractionServerNotification - | ItemFileChangeOutputDeltaServerNotification - | ItemFileChangePatchUpdatedServerNotification - | ServerRequestResolvedServerNotification - | ItemMcpToolCallProgressServerNotification - | McpServerOauthLoginCompletedServerNotification - | McpServerStartupStatusUpdatedServerNotification - | AccountUpdatedServerNotification - | AccountRateLimitsUpdatedServerNotification - | AppListUpdatedServerNotification - | ExternalAgentConfigImportCompletedServerNotification - | FsChangedServerNotification - | ItemReasoningSummaryTextDeltaServerNotification - | ItemReasoningSummaryPartAddedServerNotification - | ItemReasoningTextDeltaServerNotification - | ThreadCompactedServerNotification - | ModelReroutedServerNotification - | WarningServerNotification - | DeprecationNoticeServerNotification - | ConfigWarningServerNotification - | FuzzyFileSearchSessionUpdatedServerNotification - | FuzzyFileSearchSessionCompletedServerNotification - | ThreadRealtimeStartedServerNotification - | ThreadRealtimeItemAddedServerNotification - | ThreadRealtimeTranscriptDeltaServerNotification - | ThreadRealtimeTranscriptDoneServerNotification - | ThreadRealtimeOutputAudioDeltaServerNotification - | ThreadRealtimeSdpServerNotification - | ThreadRealtimeErrorServerNotification - | ThreadRealtimeClosedServerNotification - | WindowsWorldWritableWarningServerNotification - | WindowsSandboxSetupCompletedServerNotification - | AccountLoginCompletedServerNotification, - Field( - description="Notification sent from the server to the client.", - title="ServerNotification", - ), - ] diff --git a/vendor/codex/sdk/python/src/codex_app_server/models.py b/vendor/codex/sdk/python/src/codex_app_server/models.py deleted file mode 100644 index 70c61d44..00000000 --- a/vendor/codex/sdk/python/src/codex_app_server/models.py +++ /dev/null @@ -1,99 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from typing import TypeAlias - -from pydantic import BaseModel - -from .generated.v2_all import ( - AccountLoginCompletedNotification, - AccountRateLimitsUpdatedNotification, - AccountUpdatedNotification, - AgentMessageDeltaNotification, - AppListUpdatedNotification, - CommandExecutionOutputDeltaNotification, - ConfigWarningNotification, - ContextCompactedNotification, - DeprecationNoticeNotification, - ErrorNotification, - FileChangeOutputDeltaNotification, - ItemCompletedNotification, - ItemStartedNotification, - McpServerOauthLoginCompletedNotification, - McpToolCallProgressNotification, - PlanDeltaNotification, - RawResponseItemCompletedNotification, - ReasoningSummaryPartAddedNotification, - ReasoningSummaryTextDeltaNotification, - ReasoningTextDeltaNotification, - TerminalInteractionNotification, - ThreadNameUpdatedNotification, - ThreadStartedNotification, - ThreadTokenUsageUpdatedNotification, - TurnCompletedNotification, - TurnDiffUpdatedNotification, - TurnPlanUpdatedNotification, - TurnStartedNotification, - WindowsWorldWritableWarningNotification, -) - -JsonScalar: TypeAlias = str | int | float | bool | None -JsonValue: TypeAlias = JsonScalar | dict[str, "JsonValue"] | list["JsonValue"] -JsonObject: TypeAlias = dict[str, JsonValue] - - -@dataclass(slots=True) -class UnknownNotification: - params: JsonObject - - -NotificationPayload: TypeAlias = ( - AccountLoginCompletedNotification - | AccountRateLimitsUpdatedNotification - | AccountUpdatedNotification - | AgentMessageDeltaNotification - | AppListUpdatedNotification - | CommandExecutionOutputDeltaNotification - | ConfigWarningNotification - | ContextCompactedNotification - | DeprecationNoticeNotification - | ErrorNotification - | FileChangeOutputDeltaNotification - | ItemCompletedNotification - | ItemStartedNotification - | McpServerOauthLoginCompletedNotification - | McpToolCallProgressNotification - | PlanDeltaNotification - | RawResponseItemCompletedNotification - | ReasoningSummaryPartAddedNotification - | ReasoningSummaryTextDeltaNotification - | ReasoningTextDeltaNotification - | TerminalInteractionNotification - | ThreadNameUpdatedNotification - | ThreadStartedNotification - | ThreadTokenUsageUpdatedNotification - | TurnCompletedNotification - | TurnDiffUpdatedNotification - | TurnPlanUpdatedNotification - | TurnStartedNotification - | WindowsWorldWritableWarningNotification - | UnknownNotification -) - - -@dataclass(slots=True) -class Notification: - method: str - payload: NotificationPayload - - -class ServerInfo(BaseModel): - name: str | None = None - version: str | None = None - - -class InitializeResponse(BaseModel): - serverInfo: ServerInfo | None = None - userAgent: str | None = None - platformFamily: str | None = None - platformOs: str | None = None diff --git a/vendor/codex/sdk/python/src/codex_app_server/py.typed b/vendor/codex/sdk/python/src/codex_app_server/py.typed deleted file mode 100644 index e69de29b..00000000 diff --git a/vendor/codex/sdk/python/src/codex_app_server/retry.py b/vendor/codex/sdk/python/src/codex_app_server/retry.py deleted file mode 100644 index b7e4f774..00000000 --- a/vendor/codex/sdk/python/src/codex_app_server/retry.py +++ /dev/null @@ -1,41 +0,0 @@ -from __future__ import annotations - -import random -import time -from typing import Callable, TypeVar - -from .errors import is_retryable_error - -T = TypeVar("T") - - -def retry_on_overload( - op: Callable[[], T], - *, - max_attempts: int = 3, - initial_delay_s: float = 0.25, - max_delay_s: float = 2.0, - jitter_ratio: float = 0.2, -) -> T: - """Retry helper for transient server-overload errors.""" - - if max_attempts < 1: - raise ValueError("max_attempts must be >= 1") - - delay = initial_delay_s - attempt = 0 - while True: - attempt += 1 - try: - return op() - except Exception as exc: - if attempt >= max_attempts: - raise - if not is_retryable_error(exc): - raise - - jitter = delay * jitter_ratio - sleep_for = min(max_delay_s, delay) + random.uniform(-jitter, jitter) - if sleep_for > 0: - time.sleep(sleep_for) - delay = min(max_delay_s, delay * 2) diff --git a/vendor/codex/sdk/python/tests/conftest.py b/vendor/codex/sdk/python/tests/conftest.py deleted file mode 100644 index f23f55e4..00000000 --- a/vendor/codex/sdk/python/tests/conftest.py +++ /dev/null @@ -1,16 +0,0 @@ -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 == "codex_app_server" or module_name.startswith("codex_app_server."): - sys.modules.pop(module_name) diff --git a/vendor/codex/sdk/python/tests/test_artifact_workflow_and_binaries.py b/vendor/codex/sdk/python/tests/test_artifact_workflow_and_binaries.py deleted file mode 100644 index 03252154..00000000 --- a/vendor/codex/sdk/python/tests/test_artifact_workflow_and_binaries.py +++ /dev/null @@ -1,514 +0,0 @@ -from __future__ import annotations - -import ast -import importlib.util -import io -import json -import sys -import tomllib -import urllib.error -from pathlib import Path - -import pytest - -ROOT = Path(__file__).resolve().parents[1] - - -def _load_update_script_module(): - script_path = ROOT / "scripts" / "update_sdk_artifacts.py" - spec = importlib.util.spec_from_file_location("update_sdk_artifacts", script_path) - if spec is None or spec.loader is None: - raise AssertionError(f"Failed to load script module: {script_path}") - module = importlib.util.module_from_spec(spec) - sys.modules[spec.name] = module - spec.loader.exec_module(module) - return module - - -def _load_runtime_setup_module(): - runtime_setup_path = ROOT / "_runtime_setup.py" - spec = importlib.util.spec_from_file_location("_runtime_setup", runtime_setup_path) - if spec is None or spec.loader is None: - raise AssertionError(f"Failed to load runtime setup module: {runtime_setup_path}") - module = importlib.util.module_from_spec(spec) - sys.modules[spec.name] = module - spec.loader.exec_module(module) - return module - - -def test_generation_has_single_maintenance_entrypoint_script() -> None: - scripts = sorted(p.name for p in (ROOT / "scripts").glob("*.py")) - assert scripts == ["update_sdk_artifacts.py"] - - -def test_generate_types_wires_all_generation_steps() -> None: - source = (ROOT / "scripts" / "update_sdk_artifacts.py").read_text() - tree = ast.parse(source) - - generate_types_fn = next( - ( - node - for node in tree.body - if isinstance(node, ast.FunctionDef) and node.name == "generate_types" - ), - None, - ) - assert generate_types_fn is not None - - calls: list[str] = [] - for node in generate_types_fn.body: - if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call): - fn = node.value.func - if isinstance(fn, ast.Name): - calls.append(fn.id) - - assert calls == [ - "generate_v2_all", - "generate_notification_registry", - "generate_public_api_flat_methods", - ] - - -def test_schema_normalization_only_flattens_string_literal_oneofs() -> None: - script = _load_update_script_module() - schema = json.loads( - ( - ROOT.parent.parent - / "codex-rs" - / "app-server-protocol" - / "schema" - / "json" - / "codex_app_server_protocol.v2.schemas.json" - ).read_text() - ) - - definitions = schema["definitions"] - flattened = [ - name - for name, definition in definitions.items() - if isinstance(definition, dict) - and script._flatten_string_enum_one_of(definition.copy()) - ] - - assert flattened == [ - "AuthMode", - "CommandExecOutputStream", - "ExperimentalFeatureStage", - "InputModality", - "MessagePhase", - ] - - -def test_python_codegen_schema_annotation_adds_stable_variant_titles() -> None: - script = _load_update_script_module() - schema = json.loads( - ( - ROOT.parent.parent - / "codex-rs" - / "app-server-protocol" - / "schema" - / "json" - / "codex_app_server_protocol.v2.schemas.json" - ).read_text() - ) - - script._annotate_schema(schema) - definitions = schema["definitions"] - - server_notification_titles = { - variant.get("title") - for variant in definitions["ServerNotification"]["oneOf"] - if isinstance(variant, dict) - } - assert "ErrorServerNotification" in server_notification_titles - assert "ThreadStartedServerNotification" in server_notification_titles - assert "ErrorNotification" not in server_notification_titles - assert "Thread/startedNotification" not in server_notification_titles - - ask_for_approval_titles = [ - variant.get("title") for variant in definitions["AskForApproval"]["oneOf"] - ] - assert ask_for_approval_titles == [ - "AskForApprovalValue", - "GranularAskForApproval", - ] - - reasoning_summary_titles = [ - variant.get("title") for variant in definitions["ReasoningSummary"]["oneOf"] - ] - assert reasoning_summary_titles == [ - "ReasoningSummaryValue", - "NoneReasoningSummary", - ] - - -def test_generate_v2_all_uses_titles_for_generated_names() -> None: - source = (ROOT / "scripts" / "update_sdk_artifacts.py").read_text() - assert "--use-title-as-name" in source - assert "--use-annotated" in source - assert "--formatters" in source - assert "ruff-format" in source - - -def test_runtime_package_template_has_no_checked_in_binaries() -> None: - runtime_root = ROOT.parent / "python-runtime" / "src" / "codex_cli_bin" - assert sorted( - path.name - for path in runtime_root.rglob("*") - if path.is_file() and "__pycache__" not in path.parts - ) == ["__init__.py"] - - -def test_examples_readme_matches_pinned_runtime_version() -> None: - runtime_setup = _load_runtime_setup_module() - readme = (ROOT / "examples" / "README.md").read_text() - assert ( - f"Current pinned runtime version: `{runtime_setup.pinned_runtime_version()}`" - in readme - ) - - -def test_runtime_distribution_name_is_consistent() -> None: - script = _load_update_script_module() - runtime_setup = _load_runtime_setup_module() - from codex_app_server import client as client_module - - assert script.RUNTIME_DISTRIBUTION_NAME == "openai-codex-cli-bin" - assert runtime_setup.PACKAGE_NAME == "openai-codex-cli-bin" - assert client_module.RUNTIME_PKG_NAME == "openai-codex-cli-bin" - assert "importlib.metadata.version('codex-cli-bin')" not in ( - ROOT / "_runtime_setup.py" - ).read_text() - - -def test_release_metadata_retries_without_invalid_auth(monkeypatch: pytest.MonkeyPatch) -> None: - runtime_setup = _load_runtime_setup_module() - authorizations: list[str | None] = [] - - def fake_urlopen(request): - authorization = request.headers.get("Authorization") - authorizations.append(authorization) - if authorization is not None: - raise urllib.error.HTTPError( - request.full_url, - 401, - "Unauthorized", - hdrs=None, - fp=None, - ) - return io.StringIO('{"assets": []}') - - monkeypatch.setenv("GH_TOKEN", "invalid-token") - monkeypatch.setattr(runtime_setup.urllib.request, "urlopen", fake_urlopen) - - assert runtime_setup._release_metadata("1.2.3") == {"assets": []} - assert authorizations == ["Bearer invalid-token", None] - - -def test_runtime_package_is_wheel_only_and_builds_platform_specific_wheels() -> None: - pyproject = tomllib.loads( - (ROOT.parent / "python-runtime" / "pyproject.toml").read_text() - ) - hook_source = (ROOT.parent / "python-runtime" / "hatch_build.py").read_text() - hook_tree = ast.parse(hook_source) - initialize_fn = next( - node - for node in ast.walk(hook_tree) - if isinstance(node, ast.FunctionDef) and node.name == "initialize" - ) - - sdist_guard = next( - ( - node - for node in initialize_fn.body - if isinstance(node, ast.If) - and isinstance(node.test, ast.Compare) - and isinstance(node.test.left, ast.Attribute) - and isinstance(node.test.left.value, ast.Name) - and node.test.left.value.id == "self" - and node.test.left.attr == "target_name" - and len(node.test.ops) == 1 - and isinstance(node.test.ops[0], ast.Eq) - and len(node.test.comparators) == 1 - and isinstance(node.test.comparators[0], ast.Constant) - and node.test.comparators[0].value == "sdist" - ), - None, - ) - build_data_assignments = {} - for node in initialize_fn.body: - if ( - not isinstance(node, ast.Assign) - or len(node.targets) != 1 - or not isinstance(node.targets[0], ast.Subscript) - or not isinstance(node.targets[0].value, ast.Name) - or node.targets[0].value.id != "build_data" - or not isinstance(node.targets[0].slice, ast.Constant) - or not isinstance(node.targets[0].slice.value, str) - ): - continue - if isinstance(node.value, ast.Constant): - build_data_assignments[node.targets[0].slice.value] = node.value.value - elif isinstance(node.value, ast.JoinedStr): - build_data_assignments[node.targets[0].slice.value] = "joined-string" - - assert pyproject["project"]["name"] == "openai-codex-cli-bin" - assert pyproject["tool"]["hatch"]["build"]["targets"]["wheel"] == { - "packages": ["src/codex_cli_bin"], - "include": ["src/codex_cli_bin/bin/**"], - "hooks": {"custom": {}}, - } - assert pyproject["tool"]["hatch"]["build"]["targets"]["sdist"] == { - "hooks": {"custom": {}}, - } - assert sdist_guard is not None - assert build_data_assignments == { - "pure_python": False, - "infer_tag": False, - "tag": "joined-string", - } - - -def test_stage_runtime_release_copies_binary_and_sets_version(tmp_path: Path) -> None: - script = _load_update_script_module() - fake_binary = tmp_path / script.runtime_binary_name() - fake_binary.write_text("fake codex\n") - - staged = script.stage_python_runtime_package( - tmp_path / "runtime-stage", - "1.2.3", - fake_binary, - ) - - assert staged == tmp_path / "runtime-stage" - assert script.staged_runtime_bin_path(staged).read_text() == "fake codex\n" - assert 'name = "openai-codex-cli-bin"' in (staged / "pyproject.toml").read_text() - assert 'version = "1.2.3"' in (staged / "pyproject.toml").read_text() - - -def test_normalize_codex_version_accepts_release_tags_and_pep440_versions() -> None: - script = _load_update_script_module() - - assert script.normalize_codex_version("rust-v0.116.0-alpha.1") == "0.116.0a1" - assert script.normalize_codex_version("v0.116.0-beta.2") == "0.116.0b2" - assert script.normalize_codex_version("0.116.0rc3") == "0.116.0rc3" - assert script.normalize_codex_version("0.116.0") == "0.116.0" - - -def test_stage_runtime_release_replaces_existing_staging_dir(tmp_path: Path) -> None: - script = _load_update_script_module() - staging_dir = tmp_path / "runtime-stage" - old_file = staging_dir / "stale.txt" - old_file.parent.mkdir(parents=True) - old_file.write_text("stale") - - fake_binary = tmp_path / script.runtime_binary_name() - fake_binary.write_text("fake codex\n") - - staged = script.stage_python_runtime_package( - staging_dir, - "1.2.3", - fake_binary, - ) - - assert staged == staging_dir - assert not old_file.exists() - assert script.staged_runtime_bin_path(staged).read_text() == "fake codex\n" - - -def test_stage_runtime_release_can_pin_wheel_platform_tag(tmp_path: Path) -> None: - script = _load_update_script_module() - fake_binary = tmp_path / script.runtime_binary_name() - fake_binary.write_text("fake codex\n") - - staged = script.stage_python_runtime_package( - tmp_path / "runtime-stage", - "0.116.0a1", - fake_binary, - platform_tag="musllinux_1_1_x86_64", - ) - - pyproject = (staged / "pyproject.toml").read_text() - assert 'platform-tag = "musllinux_1_1_x86_64"' in pyproject - - -def test_stage_sdk_release_injects_exact_runtime_pin(tmp_path: Path) -> None: - script = _load_update_script_module() - staged = script.stage_python_sdk_package(tmp_path / "sdk-stage", "0.2.1", "1.2.3") - - pyproject = (staged / "pyproject.toml").read_text() - assert 'version = "0.2.1"' in pyproject - assert '"openai-codex-cli-bin==1.2.3"' in pyproject - assert '"codex-cli-bin==1.2.3"' not in pyproject - assert not any((staged / "src" / "codex_app_server").glob("bin/**")) - - -def test_stage_sdk_release_replaces_existing_staging_dir(tmp_path: Path) -> None: - script = _load_update_script_module() - staging_dir = tmp_path / "sdk-stage" - old_file = staging_dir / "stale.txt" - old_file.parent.mkdir(parents=True) - old_file.write_text("stale") - - staged = script.stage_python_sdk_package(staging_dir, "0.2.1", "1.2.3") - - assert staged == staging_dir - assert not old_file.exists() - - -def test_stage_sdk_runs_type_generation_before_staging(tmp_path: Path) -> None: - script = _load_update_script_module() - calls: list[str] = [] - args = script.parse_args( - [ - "stage-sdk", - str(tmp_path / "sdk-stage"), - "--runtime-version", - "1.2.3", - ] - ) - - def fake_generate_types() -> None: - calls.append("generate_types") - - def fake_stage_sdk_package( - _staging_dir: Path, _sdk_version: str, _runtime_version: str - ) -> Path: - calls.append("stage_sdk") - return tmp_path / "sdk-stage" - - def fake_stage_runtime_package( - _staging_dir: Path, - _runtime_version: str, - _runtime_binary: Path, - _platform_tag: str | None, - ) -> Path: - raise AssertionError("runtime staging should not run for stage-sdk") - - def fake_current_sdk_version() -> str: - return "0.2.0" - - ops = script.CliOps( - generate_types=fake_generate_types, - stage_python_sdk_package=fake_stage_sdk_package, - stage_python_runtime_package=fake_stage_runtime_package, - current_sdk_version=fake_current_sdk_version, - ) - - script.run_command(args, ops) - - assert calls == ["generate_types", "stage_sdk"] - - -def test_stage_runtime_stages_binary_without_type_generation(tmp_path: Path) -> None: - script = _load_update_script_module() - fake_binary = tmp_path / script.runtime_binary_name() - fake_binary.write_text("fake codex\n") - calls: list[str] = [] - args = script.parse_args( - [ - "stage-runtime", - str(tmp_path / "runtime-stage"), - str(fake_binary), - "--codex-version", - "rust-v0.116.0-alpha.1", - "--platform-tag", - "musllinux_1_1_x86_64", - ] - ) - - def fake_generate_types() -> None: - calls.append("generate_types") - - def fake_stage_sdk_package( - _staging_dir: Path, _sdk_version: str, _runtime_version: str - ) -> Path: - raise AssertionError("sdk staging should not run for stage-runtime") - - def fake_stage_runtime_package( - _staging_dir: Path, - codex_version: str, - _runtime_binary: Path, - platform_tag: str | None, - ) -> Path: - calls.append(f"stage_runtime:{codex_version}:{platform_tag}") - return tmp_path / "runtime-stage" - - def fake_current_sdk_version() -> str: - return "0.2.0" - - ops = script.CliOps( - generate_types=fake_generate_types, - stage_python_sdk_package=fake_stage_sdk_package, - stage_python_runtime_package=fake_stage_runtime_package, - current_sdk_version=fake_current_sdk_version, - ) - - script.run_command(args, ops) - - assert calls == ["stage_runtime:0.116.0a1:musllinux_1_1_x86_64"] - - -def test_default_runtime_is_resolved_from_installed_runtime_package( - tmp_path: Path, -) -> None: - from codex_app_server import client as client_module - - fake_binary = tmp_path / ("codex.exe" if client_module.os.name == "nt" else "codex") - fake_binary.write_text("") - ops = client_module.CodexBinResolverOps( - installed_codex_path=lambda: fake_binary, - path_exists=lambda path: path == fake_binary, - ) - - config = client_module.AppServerConfig() - assert config.codex_bin is None - assert client_module.resolve_codex_bin(config, ops) == fake_binary - - -def test_explicit_codex_bin_override_takes_priority(tmp_path: Path) -> None: - from codex_app_server import client as client_module - - explicit_binary = tmp_path / ( - "custom-codex.exe" if client_module.os.name == "nt" else "custom-codex" - ) - explicit_binary.write_text("") - ops = client_module.CodexBinResolverOps( - installed_codex_path=lambda: (_ for _ in ()).throw( - AssertionError("packaged runtime should not be used") - ), - path_exists=lambda path: path == explicit_binary, - ) - - config = client_module.AppServerConfig(codex_bin=str(explicit_binary)) - assert client_module.resolve_codex_bin(config, ops) == explicit_binary - - -def test_missing_runtime_package_requires_explicit_codex_bin() -> None: - from codex_app_server import client as client_module - - ops = client_module.CodexBinResolverOps( - installed_codex_path=lambda: (_ for _ in ()).throw( - FileNotFoundError("missing packaged runtime") - ), - path_exists=lambda _path: False, - ) - - with pytest.raises(FileNotFoundError, match="missing packaged runtime"): - client_module.resolve_codex_bin(client_module.AppServerConfig(), ops) - - -def test_broken_runtime_package_does_not_fall_back() -> None: - from codex_app_server import client as client_module - - ops = client_module.CodexBinResolverOps( - installed_codex_path=lambda: (_ for _ in ()).throw( - FileNotFoundError("missing packaged binary") - ), - path_exists=lambda _path: False, - ) - - with pytest.raises(FileNotFoundError) as exc_info: - client_module.resolve_codex_bin(client_module.AppServerConfig(), ops) - - assert str(exc_info.value) == ("missing packaged binary") diff --git a/vendor/codex/sdk/python/tests/test_async_client_behavior.py b/vendor/codex/sdk/python/tests/test_async_client_behavior.py deleted file mode 100644 index 580ff2a9..00000000 --- a/vendor/codex/sdk/python/tests/test_async_client_behavior.py +++ /dev/null @@ -1,64 +0,0 @@ -from __future__ import annotations - -import asyncio -import time - -from codex_app_server.async_client import AsyncAppServerClient - - -def test_async_client_serializes_transport_calls() -> None: - async def scenario() -> int: - client = AsyncAppServerClient() - active = 0 - max_active = 0 - - def fake_model_list(include_hidden: bool = False) -> bool: - 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()) == 1 - - -def test_async_stream_text_is_incremental_and_blocks_parallel_calls() -> None: - async def scenario() -> tuple[str, list[str], bool]: - client = AsyncAppServerClient() - - def fake_stream_text(thread_id: str, text: str, params=None): # type: ignore[no-untyped-def] - yield "first" - time.sleep(0.03) - yield "second" - yield "third" - - def fake_model_list(include_hidden: bool = False) -> str: - return "done" - - client._sync.stream_text = fake_stream_text # type: ignore[method-assign] - client._sync.model_list = fake_model_list # type: ignore[method-assign] - - stream = client.stream_text("thread-1", "hello") - first = await anext(stream) - - blocked_before_stream_done = False - competing_call = asyncio.create_task(client.model_list()) - await asyncio.sleep(0.01) - blocked_before_stream_done = not competing_call.done() - - remaining: list[str] = [] - async for item in stream: - remaining.append(item) - - await competing_call - return first, remaining, blocked_before_stream_done - - first, remaining, blocked = asyncio.run(scenario()) - assert first == "first" - assert remaining == ["second", "third"] - assert blocked diff --git a/vendor/codex/sdk/python/tests/test_client_rpc_methods.py b/vendor/codex/sdk/python/tests/test_client_rpc_methods.py deleted file mode 100644 index 27421805..00000000 --- a/vendor/codex/sdk/python/tests/test_client_rpc_methods.py +++ /dev/null @@ -1,95 +0,0 @@ -from __future__ import annotations - -from pathlib import Path -from typing import Any - -from codex_app_server.client import AppServerClient, _params_dict -from codex_app_server.generated.v2_all import ThreadListParams, ThreadTokenUsageUpdatedNotification -from codex_app_server.models import UnknownNotification - -ROOT = Path(__file__).resolve().parents[1] - - -def test_thread_set_name_and_compact_use_current_rpc_methods() -> None: - client = AppServerClient() - calls: list[tuple[str, dict[str, Any] | None]] = [] - - def fake_request(method: str, params, *, response_model): # type: ignore[no-untyped-def] - calls.append((method, params)) - return response_model.model_validate({}) - - client.request = fake_request # type: ignore[method-assign] - - client.thread_set_name("thread-1", "sdk-name") - client.thread_compact("thread-1") - - assert calls[0][0] == "thread/name/set" - assert calls[1][0] == "thread/compact/start" - - -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" / "codex_app_server" / "generated" / "v2_all.py").read_text() - assert source.count("class PlanType(") == 1 - - -def test_notifications_are_typed_with_canonical_v2_methods() -> None: - client = AppServerClient() - 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 = AppServerClient() - 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"} - - -def test_invalid_notification_payload_falls_back_to_unknown() -> None: - client = AppServerClient() - event = client._coerce_notification("thread/tokenUsage/updated", {"threadId": "missing"}) - - assert event.method == "thread/tokenUsage/updated" - assert isinstance(event.payload, UnknownNotification) diff --git a/vendor/codex/sdk/python/tests/test_contract_generation.py b/vendor/codex/sdk/python/tests/test_contract_generation.py deleted file mode 100644 index bb5ec18b..00000000 --- a/vendor/codex/sdk/python/tests/test_contract_generation.py +++ /dev/null @@ -1,52 +0,0 @@ -from __future__ import annotations - -import os -import subprocess -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -GENERATED_TARGETS = [ - Path("src/codex_app_server/generated/notification_registry.py"), - Path("src/codex_app_server/generated/v2_all.py"), - Path("src/codex_app_server/api.py"), -] - - -def _snapshot_target(root: Path, rel_path: Path) -> dict[str, bytes] | bytes | None: - 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]: - return { - str(rel_path): _snapshot_target(root, rel_path) for rel_path in GENERATED_TARGETS - } - - -def test_generated_files_are_up_to_date(): - before = _snapshot_targets(ROOT) - - # Regenerate contract artifacts via single maintenance entrypoint. - env = os.environ.copy() - python_bin = str(Path(sys.executable).parent) - env["PATH"] = f"{python_bin}{os.pathsep}{env.get('PATH', '')}" - - subprocess.run( - [sys.executable, "scripts/update_sdk_artifacts.py", "generate-types"], - cwd=ROOT, - check=True, - env=env, - ) - - after = _snapshot_targets(ROOT) - assert before == after, "Generated files drifted after regeneration" diff --git a/vendor/codex/sdk/python/tests/test_public_api_runtime_behavior.py b/vendor/codex/sdk/python/tests/test_public_api_runtime_behavior.py deleted file mode 100644 index 10865cf8..00000000 --- a/vendor/codex/sdk/python/tests/test_public_api_runtime_behavior.py +++ /dev/null @@ -1,575 +0,0 @@ -from __future__ import annotations - -import asyncio -from collections import deque -from pathlib import Path -from types import SimpleNamespace - -import pytest - -import codex_app_server.api as public_api_module -from codex_app_server.client import AppServerClient -from codex_app_server.generated.v2_all import ( - AgentMessageDeltaNotification, - ItemCompletedNotification, - MessagePhase, - ThreadTokenUsageUpdatedNotification, - TurnCompletedNotification, - TurnStatus, -) -from codex_app_server.models import InitializeResponse, Notification -from codex_app_server.api import ( - AsyncCodex, - AsyncThread, - AsyncTurnHandle, - Codex, - RunResult, - Thread, - TurnHandle, -) - -ROOT = Path(__file__).resolve().parents[1] - - -def _delta_notification( - *, - thread_id: str = "thread-1", - turn_id: str = "turn-1", - text: str = "delta-text", -) -> Notification: - return Notification( - method="item/agentMessage/delta", - payload=AgentMessageDeltaNotification.model_validate( - { - "delta": text, - "itemId": "item-1", - "threadId": thread_id, - "turnId": turn_id, - } - ), - ) - - -def _completed_notification( - *, - thread_id: str = "thread-1", - turn_id: str = "turn-1", - status: str = "completed", - error_message: str | None = None, -) -> Notification: - turn: dict[str, object] = { - "id": turn_id, - "items": [], - "status": status, - } - if error_message is not None: - turn["error"] = {"message": error_message} - return Notification( - method="turn/completed", - payload=TurnCompletedNotification.model_validate( - { - "threadId": thread_id, - "turn": turn, - } - ), - ) - - -def _item_completed_notification( - *, - thread_id: str = "thread-1", - turn_id: str = "turn-1", - text: str = "final text", - phase: MessagePhase | None = None, -) -> Notification: - item: dict[str, object] = { - "id": "item-1", - "text": text, - "type": "agentMessage", - } - if phase is not None: - item["phase"] = phase.value - return Notification( - method="item/completed", - payload=ItemCompletedNotification.model_validate( - { - "item": item, - "threadId": thread_id, - "turnId": turn_id, - } - ), - ) - - -def _token_usage_notification( - *, - thread_id: str = "thread-1", - turn_id: str = "turn-1", -) -> Notification: - return Notification( - method="thread/tokenUsage/updated", - payload=ThreadTokenUsageUpdatedNotification.model_validate( - { - "threadId": thread_id, - "turnId": turn_id, - "tokenUsage": { - "last": { - "cachedInputTokens": 1, - "inputTokens": 2, - "outputTokens": 3, - "reasoningOutputTokens": 4, - "totalTokens": 9, - }, - "total": { - "cachedInputTokens": 5, - "inputTokens": 6, - "outputTokens": 7, - "reasoningOutputTokens": 8, - "totalTokens": 26, - }, - }, - } - ), - ) - - -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, "AppServerClient", 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()) - - -def test_turn_stream_rejects_second_active_consumer() -> None: - client = AppServerClient() - notifications: deque[Notification] = deque( - [ - _delta_notification(turn_id="turn-1"), - _completed_notification(turn_id="turn-1"), - ] - ) - client.next_notification = notifications.popleft # type: ignore[method-assign] - - first_stream = TurnHandle(client, "thread-1", "turn-1").stream() - assert next(first_stream).method == "item/agentMessage/delta" - - second_stream = TurnHandle(client, "thread-1", "turn-2").stream() - with pytest.raises(RuntimeError, match="Concurrent turn consumers are not yet supported"): - next(second_stream) - - first_stream.close() - - -def test_async_turn_stream_rejects_second_active_consumer() -> None: - async def scenario() -> None: - codex = AsyncCodex() - - async def fake_ensure_initialized() -> None: - return None - - notifications: deque[Notification] = deque( - [ - _delta_notification(turn_id="turn-1"), - _completed_notification(turn_id="turn-1"), - ] - ) - - async def fake_next_notification() -> Notification: - return notifications.popleft() - - codex._ensure_initialized = fake_ensure_initialized # type: ignore[method-assign] - codex._client.next_notification = fake_next_notification # type: ignore[method-assign] - - first_stream = AsyncTurnHandle(codex, "thread-1", "turn-1").stream() - assert (await anext(first_stream)).method == "item/agentMessage/delta" - - second_stream = AsyncTurnHandle(codex, "thread-1", "turn-2").stream() - with pytest.raises(RuntimeError, match="Concurrent turn consumers are not yet supported"): - await anext(second_stream) - - await first_stream.aclose() - - asyncio.run(scenario()) - - -def test_turn_run_returns_completed_turn_payload() -> None: - client = AppServerClient() - notifications: deque[Notification] = deque( - [ - _completed_notification(), - ] - ) - client.next_notification = notifications.popleft # type: ignore[method-assign] - - result = TurnHandle(client, "thread-1", "turn-1").run() - - assert result.id == "turn-1" - assert result.status == TurnStatus.completed - assert result.items == [] - - -def test_thread_run_accepts_string_input_and_returns_run_result() -> None: - client = AppServerClient() - item_notification = _item_completed_notification(text="Hello.") - usage_notification = _token_usage_notification() - notifications: deque[Notification] = deque( - [ - item_notification, - usage_notification, - _completed_notification(), - ] - ) - client.next_notification = notifications.popleft # type: ignore[method-assign] - seen: dict[str, object] = {} - - def fake_turn_start(thread_id: str, wire_input: object, *, params=None): # noqa: ANN001,ANN202 - seen["thread_id"] = thread_id - seen["wire_input"] = wire_input - seen["params"] = params - return SimpleNamespace(turn=SimpleNamespace(id="turn-1")) - - client.turn_start = fake_turn_start # type: ignore[method-assign] - - result = Thread(client, "thread-1").run("hello") - - assert seen["thread_id"] == "thread-1" - assert seen["wire_input"] == [{"type": "text", "text": "hello"}] - assert result == RunResult( - final_response="Hello.", - items=[item_notification.payload.item], - usage=usage_notification.payload.token_usage, - ) - - -def test_thread_run_uses_last_completed_assistant_message_as_final_response() -> None: - client = AppServerClient() - first_item_notification = _item_completed_notification(text="First message") - second_item_notification = _item_completed_notification(text="Second message") - notifications: deque[Notification] = deque( - [ - first_item_notification, - second_item_notification, - _completed_notification(), - ] - ) - client.next_notification = notifications.popleft # type: ignore[method-assign] - client.turn_start = lambda thread_id, wire_input, *, params=None: SimpleNamespace( # noqa: ARG005,E731 - turn=SimpleNamespace(id="turn-1") - ) - - result = Thread(client, "thread-1").run("hello") - - assert result.final_response == "Second message" - assert result.items == [ - first_item_notification.payload.item, - second_item_notification.payload.item, - ] - - -def test_thread_run_preserves_empty_last_assistant_message() -> None: - client = AppServerClient() - first_item_notification = _item_completed_notification(text="First message") - second_item_notification = _item_completed_notification(text="") - notifications: deque[Notification] = deque( - [ - first_item_notification, - second_item_notification, - _completed_notification(), - ] - ) - client.next_notification = notifications.popleft # type: ignore[method-assign] - client.turn_start = lambda thread_id, wire_input, *, params=None: SimpleNamespace( # noqa: ARG005,E731 - turn=SimpleNamespace(id="turn-1") - ) - - result = Thread(client, "thread-1").run("hello") - - assert result.final_response == "" - assert result.items == [ - first_item_notification.payload.item, - second_item_notification.payload.item, - ] - - -def test_thread_run_prefers_explicit_final_answer_over_later_commentary() -> None: - client = AppServerClient() - final_answer_notification = _item_completed_notification( - text="Final answer", - phase=MessagePhase.final_answer, - ) - commentary_notification = _item_completed_notification( - text="Commentary", - phase=MessagePhase.commentary, - ) - notifications: deque[Notification] = deque( - [ - final_answer_notification, - commentary_notification, - _completed_notification(), - ] - ) - client.next_notification = notifications.popleft # type: ignore[method-assign] - client.turn_start = lambda thread_id, wire_input, *, params=None: SimpleNamespace( # noqa: ARG005,E731 - turn=SimpleNamespace(id="turn-1") - ) - - result = Thread(client, "thread-1").run("hello") - - assert result.final_response == "Final answer" - assert result.items == [ - final_answer_notification.payload.item, - commentary_notification.payload.item, - ] - - -def test_thread_run_returns_none_when_only_commentary_messages_complete() -> None: - client = AppServerClient() - commentary_notification = _item_completed_notification( - text="Commentary", - phase=MessagePhase.commentary, - ) - notifications: deque[Notification] = deque( - [ - commentary_notification, - _completed_notification(), - ] - ) - client.next_notification = notifications.popleft # type: ignore[method-assign] - client.turn_start = lambda thread_id, wire_input, *, params=None: SimpleNamespace( # noqa: ARG005,E731 - turn=SimpleNamespace(id="turn-1") - ) - - result = Thread(client, "thread-1").run("hello") - - assert result.final_response is None - assert result.items == [commentary_notification.payload.item] - - -def test_thread_run_raises_on_failed_turn() -> None: - client = AppServerClient() - notifications: deque[Notification] = deque( - [ - _completed_notification(status="failed", error_message="boom"), - ] - ) - client.next_notification = notifications.popleft # type: ignore[method-assign] - client.turn_start = lambda thread_id, wire_input, *, params=None: SimpleNamespace( # noqa: ARG005,E731 - turn=SimpleNamespace(id="turn-1") - ) - - with pytest.raises(RuntimeError, match="boom"): - Thread(client, "thread-1").run("hello") - - -def test_async_thread_run_accepts_string_input_and_returns_run_result() -> None: - async def scenario() -> None: - codex = AsyncCodex() - - async def fake_ensure_initialized() -> None: - return None - - item_notification = _item_completed_notification(text="Hello async.") - usage_notification = _token_usage_notification() - notifications: deque[Notification] = deque( - [ - item_notification, - usage_notification, - _completed_notification(), - ] - ) - seen: dict[str, object] = {} - - async def fake_turn_start(thread_id: str, wire_input: object, *, params=None): # noqa: ANN001,ANN202 - seen["thread_id"] = thread_id - seen["wire_input"] = wire_input - seen["params"] = params - return SimpleNamespace(turn=SimpleNamespace(id="turn-1")) - - async def fake_next_notification() -> Notification: - return notifications.popleft() - - codex._ensure_initialized = fake_ensure_initialized # type: ignore[method-assign] - codex._client.turn_start = fake_turn_start # type: ignore[method-assign] - codex._client.next_notification = fake_next_notification # type: ignore[method-assign] - - result = await AsyncThread(codex, "thread-1").run("hello") - - assert seen["thread_id"] == "thread-1" - assert seen["wire_input"] == [{"type": "text", "text": "hello"}] - assert result == RunResult( - final_response="Hello async.", - items=[item_notification.payload.item], - usage=usage_notification.payload.token_usage, - ) - - asyncio.run(scenario()) - - -def test_async_thread_run_uses_last_completed_assistant_message_as_final_response() -> None: - async def scenario() -> None: - codex = AsyncCodex() - - async def fake_ensure_initialized() -> None: - return None - - first_item_notification = _item_completed_notification(text="First async message") - second_item_notification = _item_completed_notification(text="Second async message") - notifications: deque[Notification] = deque( - [ - first_item_notification, - second_item_notification, - _completed_notification(), - ] - ) - - async def fake_turn_start(thread_id: str, wire_input: object, *, params=None): # noqa: ANN001,ANN202,ARG001 - return SimpleNamespace(turn=SimpleNamespace(id="turn-1")) - - async def fake_next_notification() -> Notification: - return notifications.popleft() - - codex._ensure_initialized = fake_ensure_initialized # type: ignore[method-assign] - codex._client.turn_start = fake_turn_start # type: ignore[method-assign] - codex._client.next_notification = fake_next_notification # type: ignore[method-assign] - - result = await AsyncThread(codex, "thread-1").run("hello") - - assert result.final_response == "Second async message" - assert result.items == [ - first_item_notification.payload.item, - second_item_notification.payload.item, - ] - - asyncio.run(scenario()) - - -def test_async_thread_run_returns_none_when_only_commentary_messages_complete() -> None: - async def scenario() -> None: - codex = AsyncCodex() - - async def fake_ensure_initialized() -> None: - return None - - commentary_notification = _item_completed_notification( - text="Commentary", - phase=MessagePhase.commentary, - ) - notifications: deque[Notification] = deque( - [ - commentary_notification, - _completed_notification(), - ] - ) - - async def fake_turn_start(thread_id: str, wire_input: object, *, params=None): # noqa: ANN001,ANN202,ARG001 - return SimpleNamespace(turn=SimpleNamespace(id="turn-1")) - - async def fake_next_notification() -> Notification: - return notifications.popleft() - - codex._ensure_initialized = fake_ensure_initialized # type: ignore[method-assign] - codex._client.turn_start = fake_turn_start # type: ignore[method-assign] - codex._client.next_notification = fake_next_notification # type: ignore[method-assign] - - result = await AsyncThread(codex, "thread-1").run("hello") - - assert result.final_response is None - assert result.items == [commentary_notification.payload.item] - - asyncio.run(scenario()) - - -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 diff --git a/vendor/codex/sdk/python/tests/test_public_api_signatures.py b/vendor/codex/sdk/python/tests/test_public_api_signatures.py deleted file mode 100644 index 68097d4b..00000000 --- a/vendor/codex/sdk/python/tests/test_public_api_signatures.py +++ /dev/null @@ -1,260 +0,0 @@ -from __future__ import annotations - -import importlib.resources as resources -import inspect -from typing import Any - -from codex_app_server import AppServerConfig, RunResult -from codex_app_server.models import InitializeResponse -from codex_app_server.api import AsyncCodex, AsyncThread, Codex, Thread - - -def _keyword_only_names(fn: object) -> list[str]: - signature = inspect.signature(fn) - return [ - param.name - for param in signature.parameters.values() - if param.kind == inspect.Parameter.KEYWORD_ONLY - ] - - -def _assert_no_any_annotations(fn: object) -> None: - 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_app_server_config() -> None: - assert AppServerConfig.__name__ == "AppServerConfig" - - -def test_root_exports_run_result() -> None: - assert RunResult.__name__ == "RunResult" - - -def test_package_includes_py_typed_marker() -> None: - marker = resources.files("codex_app_server").joinpath("py.typed") - assert marker.is_file() - - -def test_generated_public_signatures_are_snake_case_and_typed() -> None: - expected = { - Codex.thread_start: [ - "approval_policy", - "approvals_reviewer", - "base_instructions", - "config", - "cwd", - "developer_instructions", - "ephemeral", - "model", - "model_provider", - "personality", - "sandbox", - "service_name", - "service_tier", - "session_start_source", - ], - Codex.thread_list: [ - "archived", - "cursor", - "cwd", - "limit", - "model_providers", - "search_term", - "sort_direction", - "sort_key", - "source_kinds", - ], - Codex.thread_resume: [ - "approval_policy", - "approvals_reviewer", - "base_instructions", - "config", - "cwd", - "developer_instructions", - "model", - "model_provider", - "personality", - "sandbox", - "service_tier", - ], - Codex.thread_fork: [ - "approval_policy", - "approvals_reviewer", - "base_instructions", - "config", - "cwd", - "developer_instructions", - "ephemeral", - "model", - "model_provider", - "sandbox", - "service_tier", - ], - Thread.turn: [ - "approval_policy", - "approvals_reviewer", - "cwd", - "effort", - "model", - "output_schema", - "personality", - "sandbox_policy", - "service_tier", - "summary", - ], - Thread.run: [ - "approval_policy", - "approvals_reviewer", - "cwd", - "effort", - "model", - "output_schema", - "personality", - "sandbox_policy", - "service_tier", - "summary", - ], - AsyncCodex.thread_start: [ - "approval_policy", - "approvals_reviewer", - "base_instructions", - "config", - "cwd", - "developer_instructions", - "ephemeral", - "model", - "model_provider", - "personality", - "sandbox", - "service_name", - "service_tier", - "session_start_source", - ], - AsyncCodex.thread_list: [ - "archived", - "cursor", - "cwd", - "limit", - "model_providers", - "search_term", - "sort_direction", - "sort_key", - "source_kinds", - ], - AsyncCodex.thread_resume: [ - "approval_policy", - "approvals_reviewer", - "base_instructions", - "config", - "cwd", - "developer_instructions", - "model", - "model_provider", - "personality", - "sandbox", - "service_tier", - ], - AsyncCodex.thread_fork: [ - "approval_policy", - "approvals_reviewer", - "base_instructions", - "config", - "cwd", - "developer_instructions", - "ephemeral", - "model", - "model_provider", - "sandbox", - "service_tier", - ], - AsyncThread.turn: [ - "approval_policy", - "approvals_reviewer", - "cwd", - "effort", - "model", - "output_schema", - "personality", - "sandbox_policy", - "service_tier", - "summary", - ], - AsyncThread.run: [ - "approval_policy", - "approvals_reviewer", - "cwd", - "effort", - "model", - "output_schema", - "personality", - "sandbox_policy", - "service_tier", - "summary", - ], - } - - 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_lifecycle_methods_are_codex_scoped() -> None: - 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: - payload = InitializeResponse.model_validate({"userAgent": "codex-cli/1.2.3"}) - parsed = Codex._validate_initialize(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: - try: - Codex._validate_initialize(InitializeResponse.model_validate({})) - except RuntimeError as exc: - assert "missing required metadata" in str(exc) - else: - raise AssertionError( - "expected RuntimeError when initialize metadata is missing" - ) diff --git a/vendor/codex/sdk/python/tests/test_real_app_server_integration.py b/vendor/codex/sdk/python/tests/test_real_app_server_integration.py deleted file mode 100644 index 3c114f12..00000000 --- a/vendor/codex/sdk/python/tests/test_real_app_server_integration.py +++ /dev/null @@ -1,545 +0,0 @@ -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_compatibility_hint( - runtime_env: PreparedRuntimeEnv, - *, - stdout: str, - stderr: str, -) -> str: - combined = f"{stdout}\n{stderr}" - if "ThreadStartResponse" in combined and "approvalsReviewer" in combined: - return ( - "\nCompatibility 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_compatibility_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 codex_app_server 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 codex_app_server import Codex, TextInput - - with Codex() as codex: - thread = codex.thread_start( - model="gpt-5.4", - config={"model_reasoning_effort": "high"}, - ) - result = thread.turn(TextInput("hello")).run() - persisted = thread.read(include_turns=True) - persisted_turn = next( - (turn for turn in persisted.thread.turns or [] if turn.id == result.id), - None, - ) - print(json.dumps({ - "thread_id": thread.id, - "turn_id": result.id, - "status": result.status.value, - "items_count": len(result.items or []), - "persisted_items_count": 0 if persisted_turn is None else len(persisted_turn.items or []), - })) - """ - ), - ) - - 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 isinstance(data["items_count"], int) - assert isinstance(data["persisted_items_count"], int) - - -def test_real_thread_run_convenience_smoke(runtime_env: PreparedRuntimeEnv) -> None: - data = _run_json_python( - runtime_env, - textwrap.dedent( - """ - import json - from codex_app_server 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_async_thread_turn_usage_and_ids_smoke( - runtime_env: PreparedRuntimeEnv, -) -> None: - data = _run_json_python( - runtime_env, - textwrap.dedent( - """ - import asyncio - import json - from codex_app_server import AsyncCodex, TextInput - - 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(TextInput("say ok"))).run() - persisted = await thread.read(include_turns=True) - persisted_turn = next( - (turn for turn in persisted.thread.turns or [] if turn.id == result.id), - None, - ) - print(json.dumps({ - "thread_id": thread.id, - "turn_id": result.id, - "status": result.status.value, - "items_count": len(result.items or []), - "persisted_items_count": 0 if persisted_turn is None else len(persisted_turn.items or []), - })) - - 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 isinstance(data["items_count"], int) - assert isinstance(data["persisted_items_count"], int) - - -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 codex_app_server 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(3), - ] - ) - 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(7), - ] - ) - 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 codex_app_server import Codex, TextInput - - with Codex() as codex: - thread = codex.thread_start( - model="gpt-5.4", - config={"model_reasoning_effort": "high"}, - ) - turn = thread.turn(TextInput("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 codex_app_server import Codex, TextInput - - with Codex() as codex: - thread = codex.thread_start( - model="gpt-5.4", - config={"model_reasoning_effort": "high"}, - ) - turn = thread.turn(TextInput("Count from 1 to 200 with commas.")) - turn.interrupt() - follow_up = thread.turn(TextInput("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_compatibility_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 "persisted.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 diff --git a/vendor/codex/sdk/typescript/.prettierignore b/vendor/codex/sdk/typescript/.prettierignore deleted file mode 100644 index 007ea8a7..00000000 --- a/vendor/codex/sdk/typescript/.prettierignore +++ /dev/null @@ -1,3 +0,0 @@ -dist -node_modules -coverage diff --git a/vendor/codex/sdk/typescript/.prettierrc b/vendor/codex/sdk/typescript/.prettierrc deleted file mode 100644 index b68d0e11..00000000 --- a/vendor/codex/sdk/typescript/.prettierrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "printWidth": 100, - "singleQuote": false, - "trailingComma": "all" -} diff --git a/vendor/codex/sdk/typescript/README.md b/vendor/codex/sdk/typescript/README.md deleted file mode 100644 index afbbde57..00000000 --- a/vendor/codex/sdk/typescript/README.md +++ /dev/null @@ -1,149 +0,0 @@ -# Codex SDK - -Embed the Codex agent in your workflows and apps. - -The TypeScript SDK wraps the `codex` CLI from `@openai/codex`. It spawns the CLI and exchanges JSONL events over stdin/stdout. - -## Installation - -```bash -npm install @openai/codex-sdk -``` - -Requires Node.js 18+. - -## Quickstart - -```typescript -import { Codex } from "@openai/codex-sdk"; - -const codex = new Codex(); -const thread = codex.startThread(); -const turn = await thread.run("Diagnose the test failure and propose a fix"); - -console.log(turn.finalResponse); -console.log(turn.items); -``` - -Call `run()` repeatedly on the same `Thread` instance to continue that conversation. - -```typescript -const nextTurn = await thread.run("Implement the fix"); -``` - -### Streaming responses - -`run()` buffers events until the turn finishes. To react to intermediate progress—tool calls, streaming responses, and file change notifications—use `runStreamed()` instead, which returns an async generator of structured events. - -```typescript -const { events } = await thread.runStreamed("Diagnose the test failure and propose a fix"); - -for await (const event of events) { - switch (event.type) { - case "item.completed": - console.log("item", event.item); - break; - case "turn.completed": - console.log("usage", event.usage); - break; - } -} -``` - -### Structured output - -The Codex agent can produce a JSON response that conforms to a specified schema. The schema can be provided for each turn as a plain JSON object. - -```typescript -const schema = { - type: "object", - properties: { - summary: { type: "string" }, - status: { type: "string", enum: ["ok", "action_required"] }, - }, - required: ["summary", "status"], - additionalProperties: false, -} as const; - -const turn = await thread.run("Summarize repository status", { outputSchema: schema }); -console.log(turn.finalResponse); -``` - -You can also create a JSON schema from a [Zod schema](https://github.com/colinhacks/zod) using the [`zod-to-json-schema`](https://www.npmjs.com/package/zod-to-json-schema) package and setting the `target` to `"openAi"`. - -```typescript -const schema = z.object({ - summary: z.string(), - status: z.enum(["ok", "action_required"]), -}); - -const turn = await thread.run("Summarize repository status", { - outputSchema: zodToJsonSchema(schema, { target: "openAi" }), -}); -console.log(turn.finalResponse); -``` - -### Attaching images - -Provide structured input entries when you need to include images alongside text. Text entries are concatenated into the final prompt while image entries are passed to the Codex CLI via `--image`. - -```typescript -const turn = await thread.run([ - { type: "text", text: "Describe these screenshots" }, - { type: "local_image", path: "./ui.png" }, - { type: "local_image", path: "./diagram.jpg" }, -]); -``` - -### Resuming an existing thread - -Threads are persisted in `~/.codex/sessions`. If you lose the in-memory `Thread` object, reconstruct it with `resumeThread()` and keep going. - -```typescript -const savedThreadId = process.env.CODEX_THREAD_ID!; -const thread = codex.resumeThread(savedThreadId); -await thread.run("Implement the fix"); -``` - -### Working directory controls - -Codex runs in the current working directory by default. To avoid unrecoverable errors, Codex requires the working directory to be a Git repository. You can skip the Git repository check by passing the `skipGitRepoCheck` option when creating a thread. - -```typescript -const thread = codex.startThread({ - workingDirectory: "/path/to/project", - skipGitRepoCheck: true, -}); -``` - -### Controlling the Codex CLI environment - -By default, the Codex CLI inherits the Node.js process environment. Provide the optional `env` parameter when instantiating the -`Codex` client to fully control which variables the CLI receives—useful for sandboxed hosts like Electron apps. - -```typescript -const codex = new Codex({ - env: { - PATH: "/usr/local/bin", - }, -}); -``` - -The SDK still injects its required variables (such as `CODEX_API_KEY`) on top of the environment you provide. If you set -`baseUrl`, the SDK passes it as a `--config openai_base_url=...` override. - -### Passing `--config` overrides - -Use the `config` option to provide additional Codex CLI configuration overrides. The SDK accepts a JSON object, flattens it -into dotted paths, and serializes values as TOML literals before passing them as repeated `--config key=value` flags. - -```typescript -const codex = new Codex({ - config: { - show_raw_agent_reasoning: true, - sandbox_workspace_write: { network_access: true }, - }, -}); -``` - -Thread options still take precedence for overlapping settings because they are emitted after these global overrides. diff --git a/vendor/codex/sdk/typescript/eslint.config.js b/vendor/codex/sdk/typescript/eslint.config.js deleted file mode 100644 index 324d0681..00000000 --- a/vendor/codex/sdk/typescript/eslint.config.js +++ /dev/null @@ -1,21 +0,0 @@ -import eslint from "@eslint/js"; -import { defineConfig } from "eslint/config"; -import tseslint from "typescript-eslint"; -import nodeImport from "eslint-plugin-node-import"; - -export default defineConfig(eslint.configs.recommended, tseslint.configs.recommended, { - plugins: { - "node-import": nodeImport, - }, - - rules: { - "node-import/prefer-node-protocol": 2, - "@typescript-eslint/no-unused-vars": [ - "error", - { - argsIgnorePattern: "^_", - varsIgnorePattern: "^_", - }, - ], - }, -}); diff --git a/vendor/codex/sdk/typescript/jest.config.cjs b/vendor/codex/sdk/typescript/jest.config.cjs deleted file mode 100644 index 37f03d51..00000000 --- a/vendor/codex/sdk/typescript/jest.config.cjs +++ /dev/null @@ -1,32 +0,0 @@ -/** @type {import('jest').Config} */ -module.exports = { - preset: "ts-jest/presets/default-esm", - testEnvironment: "node", - extensionsToTreatAsEsm: [".ts"], - setupFilesAfterEnv: ["/tests/setupCodexHome.ts"], - moduleNameMapper: { - "^(\\.{1,2}/.*)\\.js$": "$1", - }, - testMatch: ["**/tests/**/*.test.ts"], - transform: { - "^.+\\.tsx?$": [ - "ts-jest", - { - useESM: true, - tsconfig: "tsconfig.json", - diagnostics: { - ignoreCodes: [1343], - }, - astTransformers: { - before: [ - { - path: "ts-jest-mock-import-meta", - // Workaround for meta.url not working in jest - options: { metaObjectReplacement: { url: "file://" + __dirname + "/dist/index.js" } }, - }, - ], - }, - }, - ], - }, -}; diff --git a/vendor/codex/sdk/typescript/package.json b/vendor/codex/sdk/typescript/package.json deleted file mode 100644 index 5959477e..00000000 --- a/vendor/codex/sdk/typescript/package.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "name": "@openai/codex-sdk", - "version": "0.0.0-dev", - "description": "TypeScript SDK for Codex APIs.", - "repository": { - "type": "git", - "url": "git+https://github.com/openai/codex.git", - "directory": "sdk/typescript" - }, - "keywords": [ - "openai", - "codex", - "sdk", - "typescript", - "api" - ], - "license": "Apache-2.0", - "type": "module", - "engines": { - "node": ">=18" - }, - "module": "./dist/index.js", - "types": "./dist/index.d.ts", - "exports": { - ".": { - "import": "./dist/index.js", - "types": "./dist/index.d.ts" - } - }, - "files": [ - "dist" - ], - "sideEffects": false, - "scripts": { - "clean": "rm -rf dist", - "build": "tsup", - "build:watch": "tsup --watch", - "lint": "pnpm eslint \"src/**/*.ts\" \"tests/**/*.ts\"", - "lint:fix": "pnpm eslint --fix \"src/**/*.ts\" \"tests/**/*.ts\"", - "test": "jest", - "test:watch": "jest --watch", - "coverage": "jest --coverage", - "format": "prettier --check .", - "format:fix": "prettier --write .", - "prepare": "pnpm run build" - }, - "devDependencies": { - "@modelcontextprotocol/sdk": "^1.24.0", - "@types/jest": "^29.5.14", - "@types/node": "^20.19.18", - "eslint": "^9.36.0", - "eslint-config-prettier": "^9.1.2", - "eslint-plugin-jest": "^29.0.1", - "eslint-plugin-node-import": "^1.0.5", - "jest": "^29.7.0", - "prettier": "^3.6.2", - "ts-jest": "^29.3.4", - "ts-jest-mock-import-meta": "^1.3.1", - "ts-node": "^10.9.2", - "tsup": "^8.5.0", - "typescript": "^5.9.2", - "typescript-eslint": "^8.45.0", - "zod": "^3.24.2", - "zod-to-json-schema": "^3.24.6" - }, - "packageManager": "pnpm@10.29.3+sha512.498e1fb4cca5aa06c1dcf2611e6fafc50972ffe7189998c409e90de74566444298ffe43e6cd2acdc775ba1aa7cc5e092a8b7054c811ba8c5770f84693d33d2dc" -} diff --git a/vendor/codex/sdk/typescript/samples/basic_streaming.ts b/vendor/codex/sdk/typescript/samples/basic_streaming.ts deleted file mode 100644 index f9ccbe40..00000000 --- a/vendor/codex/sdk/typescript/samples/basic_streaming.ts +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env -S NODE_NO_WARNINGS=1 pnpm ts-node-esm --files - -import { createInterface } from "node:readline/promises"; -import { stdin as input, stdout as output } from "node:process"; - -import { Codex } from "@openai/codex-sdk"; -import type { ThreadEvent, ThreadItem } from "@openai/codex-sdk"; -import { codexPathOverride } from "./helpers.ts"; - -const codex = new Codex({ codexPathOverride: codexPathOverride() }); -const thread = codex.startThread(); -const rl = createInterface({ input, output }); - -const handleItemCompleted = (item: ThreadItem): void => { - switch (item.type) { - case "agent_message": - console.log(`Assistant: ${item.text}`); - break; - case "reasoning": - console.log(`Reasoning: ${item.text}`); - break; - case "command_execution": { - const exitText = item.exit_code !== undefined ? ` Exit code ${item.exit_code}.` : ""; - console.log(`Command ${item.command} ${item.status}.${exitText}`); - break; - } - case "file_change": { - for (const change of item.changes) { - console.log(`File ${change.kind} ${change.path}`); - } - break; - } - } -}; - -const handleItemUpdated = (item: ThreadItem): void => { - switch (item.type) { - case "todo_list": { - console.log(`Todo:`); - for (const todo of item.items) { - console.log(`\t ${todo.completed ? "x" : " "} ${todo.text}`); - } - break; - } - } -}; - -const handleEvent = (event: ThreadEvent): void => { - switch (event.type) { - case "item.completed": - handleItemCompleted(event.item); - break; - case "item.updated": - case "item.started": - handleItemUpdated(event.item); - break; - case "turn.completed": - console.log( - `Used ${event.usage.input_tokens} input tokens, ${event.usage.cached_input_tokens} cached input tokens, ${event.usage.output_tokens} output tokens.`, - ); - break; - case "turn.failed": - console.error(`Turn failed: ${event.error.message}`); - break; - } -}; - -const main = async (): Promise => { - try { - while (true) { - const inputText = await rl.question(">"); - const trimmed = inputText.trim(); - if (trimmed.length === 0) { - continue; - } - const { events } = await thread.runStreamed(inputText); - for await (const event of events) { - handleEvent(event); - } - } - } finally { - rl.close(); - } -}; - -main().catch((err) => { - const message = err instanceof Error ? err.message : String(err); - console.error(`Unexpected error: ${message}`); - process.exit(1); -}); diff --git a/vendor/codex/sdk/typescript/samples/helpers.ts b/vendor/codex/sdk/typescript/samples/helpers.ts deleted file mode 100644 index c4643091..00000000 --- a/vendor/codex/sdk/typescript/samples/helpers.ts +++ /dev/null @@ -1,8 +0,0 @@ -import path from "node:path"; - -export function codexPathOverride() { - return ( - process.env.CODEX_EXECUTABLE ?? - path.join(process.cwd(), "..", "..", "codex-rs", "target", "debug", "codex") - ); -} diff --git a/vendor/codex/sdk/typescript/samples/structured_output.ts b/vendor/codex/sdk/typescript/samples/structured_output.ts deleted file mode 100644 index 60063c10..00000000 --- a/vendor/codex/sdk/typescript/samples/structured_output.ts +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env -S NODE_NO_WARNINGS=1 pnpm ts-node-esm --files - -import { Codex } from "@openai/codex-sdk"; - -import { codexPathOverride } from "./helpers.ts"; - -const codex = new Codex({ codexPathOverride: codexPathOverride() }); - -const thread = codex.startThread(); - -const schema = { - type: "object", - properties: { - summary: { type: "string" }, - status: { type: "string", enum: ["ok", "action_required"] }, - }, - required: ["summary", "status"], - additionalProperties: false, -} as const; - -const turn = await thread.run("Summarize repository status", { outputSchema: schema }); -console.log(turn.finalResponse); diff --git a/vendor/codex/sdk/typescript/samples/structured_output_zod.ts b/vendor/codex/sdk/typescript/samples/structured_output_zod.ts deleted file mode 100644 index 917bc391..00000000 --- a/vendor/codex/sdk/typescript/samples/structured_output_zod.ts +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env -S NODE_NO_WARNINGS=1 pnpm ts-node-esm --files - -import { Codex } from "@openai/codex-sdk"; -import { codexPathOverride } from "./helpers.ts"; -import z from "zod"; -import zodToJsonSchema from "zod-to-json-schema"; - -const codex = new Codex({ codexPathOverride: codexPathOverride() }); -const thread = codex.startThread(); - -const schema = z.object({ - summary: z.string(), - status: z.enum(["ok", "action_required"]), -}); - -const turn = await thread.run("Summarize repository status", { - outputSchema: zodToJsonSchema(schema, { target: "openAi" }), -}); -console.log(turn.finalResponse); diff --git a/vendor/codex/sdk/typescript/src/codex.ts b/vendor/codex/sdk/typescript/src/codex.ts deleted file mode 100644 index e3ce4aa0..00000000 --- a/vendor/codex/sdk/typescript/src/codex.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { CodexOptions } from "./codexOptions"; -import { CodexExec } from "./exec"; -import { Thread } from "./thread"; -import { ThreadOptions } from "./threadOptions"; - -/** - * Codex is the main class for interacting with the Codex agent. - * - * Use the `startThread()` method to start a new thread or `resumeThread()` to resume a previously started thread. - */ -export class Codex { - private exec: CodexExec; - private options: CodexOptions; - - constructor(options: CodexOptions = {}) { - const { codexPathOverride, env, config } = options; - this.exec = new CodexExec(codexPathOverride, env, config); - this.options = options; - } - - /** - * Starts a new conversation with an agent. - * @returns A new thread instance. - */ - startThread(options: ThreadOptions = {}): Thread { - return new Thread(this.exec, this.options, options); - } - - /** - * Resumes a conversation with an agent based on the thread id. - * Threads are persisted in ~/.codex/sessions. - * - * @param id The id of the thread to resume. - * @returns A new thread instance. - */ - resumeThread(id: string, options: ThreadOptions = {}): Thread { - return new Thread(this.exec, this.options, options, id); - } -} diff --git a/vendor/codex/sdk/typescript/src/codexOptions.ts b/vendor/codex/sdk/typescript/src/codexOptions.ts deleted file mode 100644 index b6abb94b..00000000 --- a/vendor/codex/sdk/typescript/src/codexOptions.ts +++ /dev/null @@ -1,22 +0,0 @@ -export type CodexConfigValue = string | number | boolean | CodexConfigValue[] | CodexConfigObject; - -export type CodexConfigObject = { [key: string]: CodexConfigValue }; - -export type CodexOptions = { - codexPathOverride?: string; - baseUrl?: string; - apiKey?: string; - /** - * Additional `--config key=value` overrides to pass to the Codex CLI. - * - * Provide a JSON object and the SDK will flatten it into dotted paths and - * serialize values as TOML literals so they are compatible with the CLI's - * `--config` parsing. - */ - config?: CodexConfigObject; - /** - * Environment variables passed to the Codex CLI process. When provided, the SDK - * will not inherit variables from `process.env`. - */ - env?: Record; -}; diff --git a/vendor/codex/sdk/typescript/src/events.ts b/vendor/codex/sdk/typescript/src/events.ts deleted file mode 100644 index b8adcfb4..00000000 --- a/vendor/codex/sdk/typescript/src/events.ts +++ /dev/null @@ -1,80 +0,0 @@ -// based on event types from codex-rs/exec/src/exec_events.rs - -import type { ThreadItem } from "./items"; - -/** Emitted when a new thread is started as the first event. */ -export type ThreadStartedEvent = { - type: "thread.started"; - /** The identifier of the new thread. Can be used to resume the thread later. */ - thread_id: string; -}; - -/** - * Emitted when a turn is started by sending a new prompt to the model. - * A turn encompasses all events that happen while the agent is processing the prompt. - */ -export type TurnStartedEvent = { - type: "turn.started"; -}; - -/** Describes the usage of tokens during a turn. */ -export type Usage = { - /** The number of input tokens used during the turn. */ - input_tokens: number; - /** The number of cached input tokens used during the turn. */ - cached_input_tokens: number; - /** The number of output tokens used during the turn. */ - output_tokens: number; -}; - -/** Emitted when a turn is completed. Typically right after the assistant's response. */ -export type TurnCompletedEvent = { - type: "turn.completed"; - usage: Usage; -}; - -/** Indicates that a turn failed with an error. */ -export type TurnFailedEvent = { - type: "turn.failed"; - error: ThreadError; -}; - -/** Emitted when a new item is added to the thread. Typically the item is initially "in progress". */ -export type ItemStartedEvent = { - type: "item.started"; - item: ThreadItem; -}; - -/** Emitted when an item is updated. */ -export type ItemUpdatedEvent = { - type: "item.updated"; - item: ThreadItem; -}; - -/** Signals that an item has reached a terminal state—either success or failure. */ -export type ItemCompletedEvent = { - type: "item.completed"; - item: ThreadItem; -}; - -/** Fatal error emitted by the stream. */ -export type ThreadError = { - message: string; -}; - -/** Represents an unrecoverable error emitted directly by the event stream. */ -export type ThreadErrorEvent = { - type: "error"; - message: string; -}; - -/** Top-level JSONL events emitted by codex exec. */ -export type ThreadEvent = - | ThreadStartedEvent - | TurnStartedEvent - | TurnCompletedEvent - | TurnFailedEvent - | ItemStartedEvent - | ItemUpdatedEvent - | ItemCompletedEvent - | ThreadErrorEvent; diff --git a/vendor/codex/sdk/typescript/src/exec.ts b/vendor/codex/sdk/typescript/src/exec.ts deleted file mode 100644 index 3447a31f..00000000 --- a/vendor/codex/sdk/typescript/src/exec.ts +++ /dev/null @@ -1,389 +0,0 @@ -import { spawn } from "node:child_process"; -import path from "node:path"; -import readline from "node:readline"; -import { createRequire } from "node:module"; - -import type { CodexConfigObject, CodexConfigValue } from "./codexOptions"; -import { SandboxMode, ModelReasoningEffort, ApprovalMode, WebSearchMode } from "./threadOptions"; - -export type CodexExecArgs = { - input: string; - - baseUrl?: string; - apiKey?: string; - threadId?: string | null; - images?: string[]; - // --model - model?: string; - // --sandbox - sandboxMode?: SandboxMode; - // --cd - workingDirectory?: string; - // --add-dir - additionalDirectories?: string[]; - // --skip-git-repo-check - skipGitRepoCheck?: boolean; - // --output-schema - outputSchemaFile?: string; - // --config model_reasoning_effort - modelReasoningEffort?: ModelReasoningEffort; - // AbortSignal to cancel the execution - signal?: AbortSignal; - // --config sandbox_workspace_write.network_access - networkAccessEnabled?: boolean; - // --config web_search - webSearchMode?: WebSearchMode; - // legacy --config features.web_search_request - webSearchEnabled?: boolean; - // --config approval_policy - approvalPolicy?: ApprovalMode; -}; - -const INTERNAL_ORIGINATOR_ENV = "CODEX_INTERNAL_ORIGINATOR_OVERRIDE"; -const TYPESCRIPT_SDK_ORIGINATOR = "codex_sdk_ts"; -const CODEX_NPM_NAME = "@openai/codex"; - -const PLATFORM_PACKAGE_BY_TARGET: Record = { - "x86_64-unknown-linux-musl": "@openai/codex-linux-x64", - "aarch64-unknown-linux-musl": "@openai/codex-linux-arm64", - "x86_64-apple-darwin": "@openai/codex-darwin-x64", - "aarch64-apple-darwin": "@openai/codex-darwin-arm64", - "x86_64-pc-windows-msvc": "@openai/codex-win32-x64", - "aarch64-pc-windows-msvc": "@openai/codex-win32-arm64", -}; - -const moduleRequire = createRequire(import.meta.url); - -export class CodexExec { - private executablePath: string; - private envOverride?: Record; - private configOverrides?: CodexConfigObject; - - constructor( - executablePath: string | null = null, - env?: Record, - configOverrides?: CodexConfigObject, - ) { - this.executablePath = executablePath || findCodexPath(); - this.envOverride = env; - this.configOverrides = configOverrides; - } - - async *run(args: CodexExecArgs): AsyncGenerator { - const commandArgs: string[] = ["exec", "--experimental-json"]; - - if (this.configOverrides) { - for (const override of serializeConfigOverrides(this.configOverrides)) { - commandArgs.push("--config", override); - } - } - - if (args.baseUrl) { - commandArgs.push( - "--config", - `openai_base_url=${toTomlValue(args.baseUrl, "openai_base_url")}`, - ); - } - - if (args.model) { - commandArgs.push("--model", args.model); - } - - if (args.sandboxMode) { - commandArgs.push("--sandbox", args.sandboxMode); - } - - if (args.workingDirectory) { - commandArgs.push("--cd", args.workingDirectory); - } - - if (args.additionalDirectories?.length) { - for (const dir of args.additionalDirectories) { - commandArgs.push("--add-dir", dir); - } - } - - if (args.skipGitRepoCheck) { - commandArgs.push("--skip-git-repo-check"); - } - - if (args.outputSchemaFile) { - commandArgs.push("--output-schema", args.outputSchemaFile); - } - - if (args.modelReasoningEffort) { - commandArgs.push("--config", `model_reasoning_effort="${args.modelReasoningEffort}"`); - } - - if (args.networkAccessEnabled !== undefined) { - commandArgs.push( - "--config", - `sandbox_workspace_write.network_access=${args.networkAccessEnabled}`, - ); - } - - if (args.webSearchMode) { - commandArgs.push("--config", `web_search="${args.webSearchMode}"`); - } else if (args.webSearchEnabled === true) { - commandArgs.push("--config", `web_search="live"`); - } else if (args.webSearchEnabled === false) { - commandArgs.push("--config", `web_search="disabled"`); - } - - if (args.approvalPolicy) { - commandArgs.push("--config", `approval_policy="${args.approvalPolicy}"`); - } - - if (args.threadId) { - commandArgs.push("resume", args.threadId); - } - - if (args.images?.length) { - for (const image of args.images) { - commandArgs.push("--image", image); - } - } - - const env: Record = {}; - if (this.envOverride) { - Object.assign(env, this.envOverride); - } else { - for (const [key, value] of Object.entries(process.env)) { - if (value !== undefined) { - env[key] = value; - } - } - } - if (!env[INTERNAL_ORIGINATOR_ENV]) { - env[INTERNAL_ORIGINATOR_ENV] = TYPESCRIPT_SDK_ORIGINATOR; - } - if (args.apiKey) { - env.CODEX_API_KEY = args.apiKey; - } - - const child = spawn(this.executablePath, commandArgs, { - env, - signal: args.signal, - }); - - let spawnError: unknown | null = null; - child.once("error", (err) => (spawnError = err)); - - if (!child.stdin) { - child.kill(); - throw new Error("Child process has no stdin"); - } - child.stdin.write(args.input); - child.stdin.end(); - - if (!child.stdout) { - child.kill(); - throw new Error("Child process has no stdout"); - } - const stderrChunks: Buffer[] = []; - - if (child.stderr) { - child.stderr.on("data", (data) => { - stderrChunks.push(data); - }); - } - - const exitPromise = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>( - (resolve) => { - child.once("exit", (code, signal) => { - resolve({ code, signal }); - }); - }, - ); - - const rl = readline.createInterface({ - input: child.stdout, - crlfDelay: Infinity, - }); - - try { - for await (const line of rl) { - // `line` is a string (Node sets default encoding to utf8 for readline) - yield line as string; - } - - if (spawnError) throw spawnError; - const { code, signal } = await exitPromise; - if (code !== 0 || signal) { - const stderrBuffer = Buffer.concat(stderrChunks); - const detail = signal ? `signal ${signal}` : `code ${code ?? 1}`; - throw new Error(`Codex Exec exited with ${detail}: ${stderrBuffer.toString("utf8")}`); - } - } finally { - rl.close(); - child.removeAllListeners(); - try { - if (!child.killed) child.kill(); - } catch { - // ignore - } - } - } -} - -function serializeConfigOverrides(configOverrides: CodexConfigObject): string[] { - const overrides: string[] = []; - flattenConfigOverrides(configOverrides, "", overrides); - return overrides; -} - -function flattenConfigOverrides( - value: CodexConfigValue, - prefix: string, - overrides: string[], -): void { - if (!isPlainObject(value)) { - if (prefix) { - overrides.push(`${prefix}=${toTomlValue(value, prefix)}`); - return; - } else { - throw new Error("Codex config overrides must be a plain object"); - } - } - - const entries = Object.entries(value); - if (!prefix && entries.length === 0) { - return; - } - - if (prefix && entries.length === 0) { - overrides.push(`${prefix}={}`); - return; - } - - for (const [key, child] of entries) { - if (!key) { - throw new Error("Codex config override keys must be non-empty strings"); - } - if (child === undefined) { - continue; - } - const path = prefix ? `${prefix}.${key}` : key; - if (isPlainObject(child)) { - flattenConfigOverrides(child, path, overrides); - } else { - overrides.push(`${path}=${toTomlValue(child, path)}`); - } - } -} - -function toTomlValue(value: CodexConfigValue, path: string): string { - if (typeof value === "string") { - return JSON.stringify(value); - } else if (typeof value === "number") { - if (!Number.isFinite(value)) { - throw new Error(`Codex config override at ${path} must be a finite number`); - } - return `${value}`; - } else if (typeof value === "boolean") { - return value ? "true" : "false"; - } else if (Array.isArray(value)) { - const rendered = value.map((item, index) => toTomlValue(item, `${path}[${index}]`)); - return `[${rendered.join(", ")}]`; - } else if (isPlainObject(value)) { - const parts: string[] = []; - for (const [key, child] of Object.entries(value)) { - if (!key) { - throw new Error("Codex config override keys must be non-empty strings"); - } - if (child === undefined) { - continue; - } - parts.push(`${formatTomlKey(key)} = ${toTomlValue(child, `${path}.${key}`)}`); - } - return `{${parts.join(", ")}}`; - } else if (value === null) { - throw new Error(`Codex config override at ${path} cannot be null`); - } else { - const typeName = typeof value; - throw new Error(`Unsupported Codex config override value at ${path}: ${typeName}`); - } -} - -const TOML_BARE_KEY = /^[A-Za-z0-9_-]+$/; -function formatTomlKey(key: string): string { - return TOML_BARE_KEY.test(key) ? key : JSON.stringify(key); -} - -function isPlainObject(value: unknown): value is CodexConfigObject { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -function findCodexPath() { - const { platform, arch } = process; - - let targetTriple = null; - switch (platform) { - case "linux": - case "android": - switch (arch) { - case "x64": - targetTriple = "x86_64-unknown-linux-musl"; - break; - case "arm64": - targetTriple = "aarch64-unknown-linux-musl"; - break; - default: - break; - } - break; - case "darwin": - switch (arch) { - case "x64": - targetTriple = "x86_64-apple-darwin"; - break; - case "arm64": - targetTriple = "aarch64-apple-darwin"; - break; - default: - break; - } - break; - case "win32": - switch (arch) { - case "x64": - targetTriple = "x86_64-pc-windows-msvc"; - break; - case "arm64": - targetTriple = "aarch64-pc-windows-msvc"; - break; - default: - break; - } - break; - default: - break; - } - - if (!targetTriple) { - throw new Error(`Unsupported platform: ${platform} (${arch})`); - } - - const platformPackage = PLATFORM_PACKAGE_BY_TARGET[targetTriple]; - if (!platformPackage) { - throw new Error(`Unsupported target triple: ${targetTriple}`); - } - - let vendorRoot: string; - try { - const codexPackageJsonPath = moduleRequire.resolve(`${CODEX_NPM_NAME}/package.json`); - const codexRequire = createRequire(codexPackageJsonPath); - const platformPackageJsonPath = codexRequire.resolve(`${platformPackage}/package.json`); - vendorRoot = path.join(path.dirname(platformPackageJsonPath), "vendor"); - } catch { - throw new Error( - `Unable to locate Codex CLI binaries. Ensure ${CODEX_NPM_NAME} is installed with optional dependencies.`, - ); - } - - const archRoot = path.join(vendorRoot, targetTriple); - const codexBinaryName = process.platform === "win32" ? "codex.exe" : "codex"; - const binaryPath = path.join(archRoot, "codex", codexBinaryName); - - return binaryPath; -} diff --git a/vendor/codex/sdk/typescript/src/index.ts b/vendor/codex/sdk/typescript/src/index.ts deleted file mode 100644 index a74f391a..00000000 --- a/vendor/codex/sdk/typescript/src/index.ts +++ /dev/null @@ -1,40 +0,0 @@ -export type { - ThreadEvent, - ThreadStartedEvent, - TurnStartedEvent, - TurnCompletedEvent, - TurnFailedEvent, - ItemStartedEvent, - ItemUpdatedEvent, - ItemCompletedEvent, - ThreadError, - ThreadErrorEvent, - Usage, -} from "./events"; -export type { - ThreadItem, - AgentMessageItem, - ReasoningItem, - CommandExecutionItem, - FileChangeItem, - McpToolCallItem, - WebSearchItem, - TodoListItem, - ErrorItem, -} from "./items"; - -export { Thread } from "./thread"; -export type { RunResult, RunStreamedResult, Input, UserInput } from "./thread"; - -export { Codex } from "./codex"; - -export type { CodexOptions } from "./codexOptions"; - -export type { - ThreadOptions, - ApprovalMode, - SandboxMode, - ModelReasoningEffort, - WebSearchMode, -} from "./threadOptions"; -export type { TurnOptions } from "./turnOptions"; diff --git a/vendor/codex/sdk/typescript/src/items.ts b/vendor/codex/sdk/typescript/src/items.ts deleted file mode 100644 index 182878f5..00000000 --- a/vendor/codex/sdk/typescript/src/items.ts +++ /dev/null @@ -1,127 +0,0 @@ -// based on item types from codex-rs/exec/src/exec_events.rs - -import type { ContentBlock as McpContentBlock } from "@modelcontextprotocol/sdk/types.js"; - -/** The status of a command execution. */ -export type CommandExecutionStatus = "in_progress" | "completed" | "failed"; - -/** A command executed by the agent. */ -export type CommandExecutionItem = { - id: string; - type: "command_execution"; - /** The command line executed by the agent. */ - command: string; - /** Aggregated stdout and stderr captured while the command was running. */ - aggregated_output: string; - /** Set when the command exits; omitted while still running. */ - exit_code?: number; - /** Current status of the command execution. */ - status: CommandExecutionStatus; -}; - -/** Indicates the type of the file change. */ -export type PatchChangeKind = "add" | "delete" | "update"; - -/** A set of file changes by the agent. */ -export type FileUpdateChange = { - path: string; - kind: PatchChangeKind; -}; - -/** The status of a file change. */ -export type PatchApplyStatus = "completed" | "failed"; - -/** A set of file changes by the agent. Emitted once the patch succeeds or fails. */ -export type FileChangeItem = { - id: string; - type: "file_change"; - /** Individual file changes that comprise the patch. */ - changes: FileUpdateChange[]; - /** Whether the patch ultimately succeeded or failed. */ - status: PatchApplyStatus; -}; - -/** The status of an MCP tool call. */ -export type McpToolCallStatus = "in_progress" | "completed" | "failed"; - -/** - * Represents a call to an MCP tool. The item starts when the invocation is dispatched - * and completes when the MCP server reports success or failure. - */ -export type McpToolCallItem = { - id: string; - type: "mcp_tool_call"; - /** Name of the MCP server handling the request. */ - server: string; - /** The tool invoked on the MCP server. */ - tool: string; - /** Arguments forwarded to the tool invocation. */ - arguments: unknown; - /** Result payload returned by the MCP server for successful calls. */ - result?: { - content: McpContentBlock[]; - structured_content: unknown; - }; - /** Error message reported for failed calls. */ - error?: { - message: string; - }; - /** Current status of the tool invocation. */ - status: McpToolCallStatus; -}; - -/** Response from the agent. Either natural-language text or JSON when structured output is requested. */ -export type AgentMessageItem = { - id: string; - type: "agent_message"; - /** Either natural-language text or JSON when structured output is requested. */ - text: string; -}; - -/** Agent's reasoning summary. */ -export type ReasoningItem = { - id: string; - type: "reasoning"; - text: string; -}; - -/** Captures a web search request. Completes when results are returned to the agent. */ -export type WebSearchItem = { - id: string; - type: "web_search"; - query: string; -}; - -/** Describes a non-fatal error surfaced as an item. */ -export type ErrorItem = { - id: string; - type: "error"; - message: string; -}; - -/** An item in the agent's to-do list. */ -export type TodoItem = { - text: string; - completed: boolean; -}; - -/** - * Tracks the agent's running to-do list. Starts when the plan is issued, updates as steps change, - * and completes when the turn ends. - */ -export type TodoListItem = { - id: string; - type: "todo_list"; - items: TodoItem[]; -}; - -/** Canonical union of thread items and their type-specific payloads. */ -export type ThreadItem = - | AgentMessageItem - | ReasoningItem - | CommandExecutionItem - | FileChangeItem - | McpToolCallItem - | WebSearchItem - | TodoListItem - | ErrorItem; diff --git a/vendor/codex/sdk/typescript/src/outputSchemaFile.ts b/vendor/codex/sdk/typescript/src/outputSchemaFile.ts deleted file mode 100644 index 13adb4c7..00000000 --- a/vendor/codex/sdk/typescript/src/outputSchemaFile.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { promises as fs } from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -export type OutputSchemaFile = { - schemaPath?: string; - cleanup: () => Promise; -}; - -export async function createOutputSchemaFile(schema: unknown): Promise { - if (schema === undefined) { - return { cleanup: async () => {} }; - } - - if (!isJsonObject(schema)) { - throw new Error("outputSchema must be a plain JSON object"); - } - - const schemaDir = await fs.mkdtemp(path.join(os.tmpdir(), "codex-output-schema-")); - const schemaPath = path.join(schemaDir, "schema.json"); - const cleanup = async () => { - try { - await fs.rm(schemaDir, { recursive: true, force: true }); - } catch { - // suppress - } - }; - - try { - await fs.writeFile(schemaPath, JSON.stringify(schema), "utf8"); - return { schemaPath, cleanup }; - } catch (error) { - await cleanup(); - throw error; - } -} - -function isJsonObject(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} diff --git a/vendor/codex/sdk/typescript/src/thread.ts b/vendor/codex/sdk/typescript/src/thread.ts deleted file mode 100644 index 9ab425e6..00000000 --- a/vendor/codex/sdk/typescript/src/thread.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { CodexOptions } from "./codexOptions"; -import { ThreadEvent, ThreadError, Usage } from "./events"; -import { CodexExec } from "./exec"; -import { ThreadItem } from "./items"; -import { ThreadOptions } from "./threadOptions"; -import { TurnOptions } from "./turnOptions"; -import { createOutputSchemaFile } from "./outputSchemaFile"; - -/** Completed turn. */ -export type Turn = { - items: ThreadItem[]; - finalResponse: string; - usage: Usage | null; -}; - -/** Alias for `Turn` to describe the result of `run()`. */ -export type RunResult = Turn; - -/** The result of the `runStreamed` method. */ -export type StreamedTurn = { - events: AsyncGenerator; -}; - -/** Alias for `StreamedTurn` to describe the result of `runStreamed()`. */ -export type RunStreamedResult = StreamedTurn; - -/** An input to send to the agent. */ -export type UserInput = - | { - type: "text"; - text: string; - } - | { - type: "local_image"; - path: string; - }; - -export type Input = string | UserInput[]; - -/** Represent a thread of conversation with the agent. One thread can have multiple consecutive turns. */ -export class Thread { - private _exec: CodexExec; - private _options: CodexOptions; - private _id: string | null; - private _threadOptions: ThreadOptions; - - /** Returns the ID of the thread. Populated after the first turn starts. */ - public get id(): string | null { - return this._id; - } - - /* @internal */ - constructor( - exec: CodexExec, - options: CodexOptions, - threadOptions: ThreadOptions, - id: string | null = null, - ) { - this._exec = exec; - this._options = options; - this._id = id; - this._threadOptions = threadOptions; - } - - /** Provides the input to the agent and streams events as they are produced during the turn. */ - async runStreamed(input: Input, turnOptions: TurnOptions = {}): Promise { - return { events: this.runStreamedInternal(input, turnOptions) }; - } - - private async *runStreamedInternal( - input: Input, - turnOptions: TurnOptions = {}, - ): AsyncGenerator { - const { schemaPath, cleanup } = await createOutputSchemaFile(turnOptions.outputSchema); - const options = this._threadOptions; - const { prompt, images } = normalizeInput(input); - const generator = this._exec.run({ - input: prompt, - baseUrl: this._options.baseUrl, - apiKey: this._options.apiKey, - threadId: this._id, - images, - model: options?.model, - sandboxMode: options?.sandboxMode, - workingDirectory: options?.workingDirectory, - skipGitRepoCheck: options?.skipGitRepoCheck, - outputSchemaFile: schemaPath, - modelReasoningEffort: options?.modelReasoningEffort, - signal: turnOptions.signal, - networkAccessEnabled: options?.networkAccessEnabled, - webSearchMode: options?.webSearchMode, - webSearchEnabled: options?.webSearchEnabled, - approvalPolicy: options?.approvalPolicy, - additionalDirectories: options?.additionalDirectories, - }); - try { - for await (const item of generator) { - let parsed: ThreadEvent; - try { - parsed = JSON.parse(item) as ThreadEvent; - } catch (error) { - throw new Error(`Failed to parse item: ${item}`, { cause: error }); - } - if (parsed.type === "thread.started") { - this._id = parsed.thread_id; - } - yield parsed; - } - } finally { - await cleanup(); - } - } - - /** Provides the input to the agent and returns the completed turn. */ - async run(input: Input, turnOptions: TurnOptions = {}): Promise { - const generator = this.runStreamedInternal(input, turnOptions); - const items: ThreadItem[] = []; - let finalResponse: string = ""; - let usage: Usage | null = null; - let turnFailure: ThreadError | null = null; - for await (const event of generator) { - if (event.type === "item.completed") { - if (event.item.type === "agent_message") { - finalResponse = event.item.text; - } - items.push(event.item); - } else if (event.type === "turn.completed") { - usage = event.usage; - } else if (event.type === "turn.failed") { - turnFailure = event.error; - break; - } - } - if (turnFailure) { - throw new Error(turnFailure.message); - } - return { items, finalResponse, usage }; - } -} - -function normalizeInput(input: Input): { prompt: string; images: string[] } { - if (typeof input === "string") { - return { prompt: input, images: [] }; - } - const promptParts: string[] = []; - const images: string[] = []; - for (const item of input) { - if (item.type === "text") { - promptParts.push(item.text); - } else if (item.type === "local_image") { - images.push(item.path); - } - } - return { prompt: promptParts.join("\n\n"), images }; -} diff --git a/vendor/codex/sdk/typescript/src/threadOptions.ts b/vendor/codex/sdk/typescript/src/threadOptions.ts deleted file mode 100644 index 7bde5e4d..00000000 --- a/vendor/codex/sdk/typescript/src/threadOptions.ts +++ /dev/null @@ -1,20 +0,0 @@ -export type ApprovalMode = "never" | "on-request" | "on-failure" | "untrusted"; - -export type SandboxMode = "read-only" | "workspace-write" | "danger-full-access"; - -export type ModelReasoningEffort = "minimal" | "low" | "medium" | "high" | "xhigh"; - -export type WebSearchMode = "disabled" | "cached" | "live"; - -export type ThreadOptions = { - model?: string; - sandboxMode?: SandboxMode; - workingDirectory?: string; - skipGitRepoCheck?: boolean; - modelReasoningEffort?: ModelReasoningEffort; - networkAccessEnabled?: boolean; - webSearchMode?: WebSearchMode; - webSearchEnabled?: boolean; - approvalPolicy?: ApprovalMode; - additionalDirectories?: string[]; -}; diff --git a/vendor/codex/sdk/typescript/src/turnOptions.ts b/vendor/codex/sdk/typescript/src/turnOptions.ts deleted file mode 100644 index 1eda8066..00000000 --- a/vendor/codex/sdk/typescript/src/turnOptions.ts +++ /dev/null @@ -1,6 +0,0 @@ -export type TurnOptions = { - /** JSON schema describing the expected agent output. */ - outputSchema?: unknown; - /** AbortSignal to cancel the turn. */ - signal?: AbortSignal; -}; diff --git a/vendor/codex/sdk/typescript/tests/abort.test.ts b/vendor/codex/sdk/typescript/tests/abort.test.ts deleted file mode 100644 index 0af31827..00000000 --- a/vendor/codex/sdk/typescript/tests/abort.test.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { describe, expect, it } from "@jest/globals"; - -import { - assistantMessage, - responseCompleted, - responseStarted, - shell_call as shellCall, - sse, - SseResponseBody, - startResponsesTestProxy, -} from "./responsesProxy"; -import { createMockClient } from "./testCodex"; - -function* infiniteShellCall(): Generator { - while (true) { - yield sse(responseStarted(), shellCall(), responseCompleted()); - } -} - -describe("AbortSignal support", () => { - it("aborts run() when signal is aborted", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: infiniteShellCall(), - }); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - - // Create an abort controller and abort it immediately - const controller = new AbortController(); - controller.abort("Test abort"); - - // The operation should fail because the signal is already aborted - await expect(thread.run("Hello, world!", { signal: controller.signal })).rejects.toThrow(); - } finally { - cleanup(); - await close(); - } - }); - - it("aborts runStreamed() when signal is aborted", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: infiniteShellCall(), - }); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - - // Create an abort controller and abort it immediately - const controller = new AbortController(); - controller.abort("Test abort"); - - const { events } = await thread.runStreamed("Hello, world!", { signal: controller.signal }); - - // Attempting to iterate should fail - let iterationStarted = false; - try { - for await (const event of events) { - iterationStarted = true; - // Should not get here - expect(event).toBeUndefined(); - } - // If we get here, the test should fail - throw new Error( - "Expected iteration to throw due to aborted signal, but it completed successfully", - ); - } catch (error) { - // We expect an error to be thrown - expect(iterationStarted).toBe(false); // Should fail before any iteration - expect(error).toBeDefined(); - } - } finally { - cleanup(); - await close(); - } - }); - - it("aborts run() when signal is aborted during execution", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: infiniteShellCall(), - }); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - - const controller = new AbortController(); - - // Start the operation and abort it immediately after - const runPromise = thread.run("Hello, world!", { signal: controller.signal }); - - // Abort after a tiny delay to simulate aborting during execution - setTimeout(() => controller.abort("Aborted during execution"), 10); - - // The operation should fail - await expect(runPromise).rejects.toThrow(); - } finally { - cleanup(); - await close(); - } - }); - - it("aborts runStreamed() when signal is aborted during iteration", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: infiniteShellCall(), - }); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - - const controller = new AbortController(); - - const { events } = await thread.runStreamed("Hello, world!", { signal: controller.signal }); - - // Abort during iteration - let eventCount = 0; - await expect( - (async () => { - for await (const event of events) { - void event; // Consume the event - eventCount++; - // Abort after first event - if (eventCount === 5) { - controller.abort("Aborted during iteration"); - } - // Continue iterating - should eventually throw - } - })(), - ).rejects.toThrow(); - } finally { - cleanup(); - await close(); - } - }); - - it("completes normally when signal is not aborted", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [sse(responseStarted(), assistantMessage("Hi!"), responseCompleted())], - }); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - - const controller = new AbortController(); - - // Don't abort - should complete successfully - const result = await thread.run("Hello, world!", { signal: controller.signal }); - - expect(result.finalResponse).toBe("Hi!"); - expect(result.items).toHaveLength(1); - } finally { - cleanup(); - await close(); - } - }); -}); diff --git a/vendor/codex/sdk/typescript/tests/codexExecSpy.ts b/vendor/codex/sdk/typescript/tests/codexExecSpy.ts deleted file mode 100644 index 81092b74..00000000 --- a/vendor/codex/sdk/typescript/tests/codexExecSpy.ts +++ /dev/null @@ -1,37 +0,0 @@ -import * as child_process from "node:child_process"; - -jest.mock("node:child_process", () => { - const actual = jest.requireActual("node:child_process"); - return { ...actual, spawn: jest.fn(actual.spawn) }; -}); - -const actualChildProcess = - jest.requireActual("node:child_process"); -const spawnMock = child_process.spawn as jest.MockedFunction; - -export function codexExecSpy(): { - args: string[][]; - envs: (Record | undefined)[]; - restore: () => void; -} { - const previousImplementation = spawnMock.getMockImplementation() ?? actualChildProcess.spawn; - const args: string[][] = []; - const envs: (Record | undefined)[] = []; - - spawnMock.mockImplementation(((...spawnArgs: Parameters) => { - const commandArgs = spawnArgs[1]; - args.push(Array.isArray(commandArgs) ? [...commandArgs] : []); - const options = spawnArgs[2] as child_process.SpawnOptions | undefined; - envs.push(options?.env as Record | undefined); - return previousImplementation(...spawnArgs); - }) as typeof actualChildProcess.spawn); - - return { - args, - envs, - restore: () => { - spawnMock.mockClear(); - spawnMock.mockImplementation(previousImplementation); - }, - }; -} diff --git a/vendor/codex/sdk/typescript/tests/exec.test.ts b/vendor/codex/sdk/typescript/tests/exec.test.ts deleted file mode 100644 index c8aa7964..00000000 --- a/vendor/codex/sdk/typescript/tests/exec.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -import * as child_process from "node:child_process"; -import { EventEmitter } from "node:events"; -import { PassThrough } from "node:stream"; - -import { describe, expect, it } from "@jest/globals"; - -jest.mock("node:child_process", () => { - const actual = jest.requireActual("node:child_process"); - return { ...actual, spawn: jest.fn() }; -}); - -const _actualChildProcess = - jest.requireActual("node:child_process"); -const spawnMock = child_process.spawn as jest.MockedFunction; - -class FakeChildProcess extends EventEmitter { - stdin = new PassThrough(); - stdout = new PassThrough(); - stderr = new PassThrough(); - killed = false; - - kill(): boolean { - this.killed = true; - return true; - } -} - -function createEarlyExitChild(exitCode = 2): FakeChildProcess { - const child = new FakeChildProcess(); - setImmediate(() => { - child.stderr.write("boom"); - child.emit("exit", exitCode, null); - setImmediate(() => { - child.stdout.end(); - child.stderr.end(); - }); - }); - return child; -} - -const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); - -describe("CodexExec", () => { - it("rejects when exit happens before stdout closes", async () => { - const { CodexExec } = await import("../src/exec"); - const child = createEarlyExitChild(); - spawnMock.mockReturnValue(child as unknown as child_process.ChildProcess); - - const exec = new CodexExec("codex"); - const runPromise = (async () => { - for await (const _ of exec.run({ input: "hi" })) { - // no-op - } - })().then( - () => ({ status: "resolved" as const }), - (error) => ({ status: "rejected" as const, error }), - ); - - const result = await Promise.race([ - runPromise, - delay(500).then(() => ({ status: "timeout" as const })), - ]); - - expect(result.status).toBe("rejected"); - if (result.status === "rejected") { - expect(result.error).toBeInstanceOf(Error); - expect(result.error.message).toMatch(/Codex Exec exited/); - } - }); - - it("places resume args before image args", async () => { - const { CodexExec } = await import("../src/exec"); - spawnMock.mockClear(); - const child = new FakeChildProcess(); - spawnMock.mockReturnValue(child as unknown as child_process.ChildProcess); - - setImmediate(() => { - child.stdout.end(); - child.stderr.end(); - child.emit("exit", 0, null); - }); - - const exec = new CodexExec("codex"); - for await (const _ of exec.run({ input: "hi", images: ["img.png"], threadId: "thread-id" })) { - // no-op - } - - const commandArgs = spawnMock.mock.calls[0]?.[1] as string[] | undefined; - expect(commandArgs).toBeDefined(); - const resumeIndex = commandArgs!.indexOf("resume"); - const imageIndex = commandArgs!.indexOf("--image"); - expect(resumeIndex).toBeGreaterThan(-1); - expect(imageIndex).toBeGreaterThan(-1); - expect(resumeIndex).toBeLessThan(imageIndex); - }); - - it("allows overriding the env passed to the Codex CLI", async () => { - const { CodexExec } = await import("../src/exec"); - spawnMock.mockClear(); - const child = new FakeChildProcess(); - spawnMock.mockReturnValue(child as unknown as child_process.ChildProcess); - - setImmediate(() => { - child.stdout.end(); - child.stderr.end(); - child.emit("exit", 0, null); - }); - - process.env.CODEX_ENV_SHOULD_NOT_LEAK = "leak"; - - try { - const exec = new CodexExec("codex", { - CODEX_HOME: "/tmp/codex-home", - CUSTOM_ENV: "custom", - }); - - for await (const _ of exec.run({ - input: "custom env", - apiKey: "test", - baseUrl: "https://example.test", - })) { - // no-op - } - - const commandArgs = spawnMock.mock.calls[0]?.[1] as string[] | undefined; - expect(commandArgs).toBeDefined(); - const spawnOptions = spawnMock.mock.calls[0]?.[2] as child_process.SpawnOptions | undefined; - const spawnEnv = spawnOptions?.env as Record | undefined; - expect(spawnEnv).toBeDefined(); - if (!spawnEnv || !commandArgs) { - throw new Error("Spawn args missing"); - } - - expect(spawnEnv.CODEX_HOME).toBe("/tmp/codex-home"); - expect(spawnEnv.CUSTOM_ENV).toBe("custom"); - expect(spawnEnv.CODEX_ENV_SHOULD_NOT_LEAK).toBeUndefined(); - expect(spawnEnv.CODEX_API_KEY).toBe("test"); - expect(spawnEnv.CODEX_INTERNAL_ORIGINATOR_OVERRIDE).toBeDefined(); - expect(commandArgs).toContain("--config"); - expect(commandArgs).toContain(`openai_base_url=${JSON.stringify("https://example.test")}`); - } finally { - delete process.env.CODEX_ENV_SHOULD_NOT_LEAK; - } - }); -}); diff --git a/vendor/codex/sdk/typescript/tests/responsesProxy.ts b/vendor/codex/sdk/typescript/tests/responsesProxy.ts deleted file mode 100644 index e9d3b291..00000000 --- a/vendor/codex/sdk/typescript/tests/responsesProxy.ts +++ /dev/null @@ -1,225 +0,0 @@ -import http from "node:http"; - -const DEFAULT_RESPONSE_ID = "resp_mock"; -const DEFAULT_MESSAGE_ID = "msg_mock"; - -type ResponseCompletedUsage = { - input_tokens: number; - input_tokens_details: { cached_tokens: number } | null; - output_tokens: number; - output_tokens_details: { reasoning_tokens: number } | null; - total_tokens: number; -}; - -const DEFAULT_COMPLETED_USAGE: ResponseCompletedUsage = { - input_tokens: 42, - input_tokens_details: { cached_tokens: 12 }, - output_tokens: 5, - output_tokens_details: null, - total_tokens: 47, -}; - -export type SseEvent = { - type: string; - [key: string]: unknown; -}; - -export type SseResponseBody = { - kind: "sse"; - events: SseEvent[]; -}; - -export type ResponsesProxyOptions = { - responseBodies: Generator | SseResponseBody[]; - statusCode?: number; -}; - -export type ResponsesProxy = { - url: string; - close: () => Promise; - requests: RecordedRequest[]; -}; - -export type ResponsesApiRequest = { - model?: string; - input: Array<{ - role: string; - content?: Array<{ type: string; text: string }>; - }>; - text?: { - format?: Record; - }; -}; - -export type RecordedRequest = { - body: string; - json: ResponsesApiRequest; - headers: http.IncomingHttpHeaders; -}; - -function formatSseEvent(event: SseEvent): string { - return `event: ${event.type}\n` + `data: ${JSON.stringify(event)}\n\n`; -} - -export async function startResponsesTestProxy( - options: ResponsesProxyOptions, -): Promise { - function* createGenerator(array: SseResponseBody[]): Generator { - for (const elem of array) { - yield elem; - } - throw new Error("not enough responses provided"); - } - - const responseBodies: Generator = Array.isArray(options.responseBodies) - ? createGenerator(options.responseBodies) - : options.responseBodies; - - const requests: RecordedRequest[] = []; - - function readRequestBody(req: http.IncomingMessage): Promise { - return new Promise((resolve, reject) => { - const chunks: Buffer[] = []; - req.on("data", (chunk) => { - chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk); - }); - req.on("end", () => { - resolve(Buffer.concat(chunks).toString("utf8")); - }); - req.on("error", reject); - }); - } - - const server = http.createServer((req, res) => { - async function handle(): Promise { - if (req.method === "POST" && req.url === "/responses") { - const body = await readRequestBody(req); - const json = JSON.parse(body); - requests.push({ body, json, headers: { ...req.headers } }); - - const status = options.statusCode ?? 200; - res.statusCode = status; - res.setHeader("content-type", "text/event-stream"); - - const responseBody = responseBodies.next().value; - for (const event of responseBody.events) { - res.write(formatSseEvent(event)); - } - res.end(); - return; - } - - res.statusCode = 404; - res.end(); - } - - handle().catch(() => { - res.statusCode = 500; - res.end(); - }); - }); - - const url = await new Promise((resolve, reject) => { - server.listen(0, "127.0.0.1", () => { - const address = server.address(); - if (!address || typeof address === "string") { - reject(new Error("Unable to determine proxy address")); - return; - } - server.off("error", reject); - const info = address; - resolve(`http://${info.address}:${info.port}`); - }); - server.once("error", reject); - }); - - async function close(): Promise { - await new Promise((resolve, reject) => { - server.close((err) => { - if (err) { - reject(err); - return; - } - resolve(); - }); - }); - } - return { url, close, requests }; -} - -export function sse(...events: SseEvent[]): SseResponseBody { - return { - kind: "sse", - events, - }; -} - -export function responseStarted(responseId: string = DEFAULT_RESPONSE_ID): SseEvent { - return { - type: "response.created", - response: { - id: responseId, - }, - }; -} - -export function assistantMessage(text: string, itemId: string = DEFAULT_MESSAGE_ID): SseEvent { - return { - type: "response.output_item.done", - item: { - type: "message", - role: "assistant", - id: itemId, - content: [ - { - type: "output_text", - text, - }, - ], - }, - }; -} - -export function shell_call(): SseEvent { - const command = ["bash", "-lc", "echo 'Hello, world!'"]; - return { - type: "response.output_item.done", - item: { - type: "function_call", - call_id: `call_id${Math.random().toString(36).slice(2)}`, - name: "shell", - arguments: JSON.stringify({ - command, - timeout_ms: 100, - }), - }, - }; -} - -export function responseFailed(errorMessage: string): SseEvent { - return { - type: "error", - error: { code: "rate_limit_exceeded", message: errorMessage }, - }; -} - -export function responseCompleted( - responseId: string = DEFAULT_RESPONSE_ID, - usage: ResponseCompletedUsage = DEFAULT_COMPLETED_USAGE, -): SseEvent { - const inputDetails = usage.input_tokens_details ? { ...usage.input_tokens_details } : null; - const outputDetails = usage.output_tokens_details ? { ...usage.output_tokens_details } : null; - return { - type: "response.completed", - response: { - id: responseId, - usage: { - input_tokens: usage.input_tokens, - input_tokens_details: inputDetails, - output_tokens: usage.output_tokens, - output_tokens_details: outputDetails, - total_tokens: usage.total_tokens, - }, - }, - }; -} diff --git a/vendor/codex/sdk/typescript/tests/run.test.ts b/vendor/codex/sdk/typescript/tests/run.test.ts deleted file mode 100644 index 7af8126e..00000000 --- a/vendor/codex/sdk/typescript/tests/run.test.ts +++ /dev/null @@ -1,807 +0,0 @@ -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { codexExecSpy } from "./codexExecSpy"; -import { describe, expect, it } from "@jest/globals"; - -import { - assistantMessage, - responseCompleted, - responseStarted, - sse, - responseFailed, - startResponsesTestProxy, - SseResponseBody, -} from "./responsesProxy"; -import { createMockClient, createTestClient } from "./testCodex"; - -describe("Codex", () => { - it("returns thread events", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [sse(responseStarted(), assistantMessage("Hi!"), responseCompleted())], - }); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - const result = await thread.run("Hello, world!"); - - const expectedItems = [ - { - id: expect.any(String), - type: "agent_message", - text: "Hi!", - }, - ]; - expect(result.items).toEqual(expectedItems); - expect(result.usage).toEqual({ - cached_input_tokens: 12, - input_tokens: 42, - output_tokens: 5, - }); - expect(thread.id).toEqual(expect.any(String)); - } finally { - cleanup(); - await close(); - } - }); - - it("sends previous items when run is called twice", async () => { - const { url, close, requests } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("First response", "item_1"), - responseCompleted("response_1"), - ), - sse( - responseStarted("response_2"), - assistantMessage("Second response", "item_2"), - responseCompleted("response_2"), - ), - ], - }); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - await thread.run("first input"); - await thread.run("second input"); - - // Check second request continues the same thread - expect(requests.length).toBeGreaterThanOrEqual(2); - const secondRequest = requests[1]; - expect(secondRequest).toBeDefined(); - const payload = secondRequest!.json; - - const assistantEntry = payload.input.find( - (entry: { role: string }) => entry.role === "assistant", - ); - expect(assistantEntry).toBeDefined(); - const assistantText = assistantEntry?.content?.find( - (item: { type: string; text: string }) => item.type === "output_text", - )?.text; - expect(assistantText).toBe("First response"); - } finally { - cleanup(); - await close(); - } - }); - - it("continues the thread when run is called twice with options", async () => { - const { url, close, requests } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("First response", "item_1"), - responseCompleted("response_1"), - ), - sse( - responseStarted("response_2"), - assistantMessage("Second response", "item_2"), - responseCompleted("response_2"), - ), - ], - }); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - await thread.run("first input"); - await thread.run("second input"); - - // Check second request continues the same thread - expect(requests.length).toBeGreaterThanOrEqual(2); - const secondRequest = requests[1]; - expect(secondRequest).toBeDefined(); - const payload = secondRequest!.json; - - expect(payload.input.at(-1)!.content![0]!.text).toBe("second input"); - const assistantEntry = payload.input.find( - (entry: { role: string }) => entry.role === "assistant", - ); - expect(assistantEntry).toBeDefined(); - const assistantText = assistantEntry?.content?.find( - (item: { type: string; text: string }) => item.type === "output_text", - )?.text; - expect(assistantText).toBe("First response"); - } finally { - cleanup(); - await close(); - } - }); - - it("resumes thread by id", async () => { - const { url, close, requests } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("First response", "item_1"), - responseCompleted("response_1"), - ), - sse( - responseStarted("response_2"), - assistantMessage("Second response", "item_2"), - responseCompleted("response_2"), - ), - ], - }); - const { client, cleanup } = createMockClient(url); - - try { - const originalThread = client.startThread(); - await originalThread.run("first input"); - - const resumedThread = client.resumeThread(originalThread.id!); - const result = await resumedThread.run("second input"); - - expect(resumedThread.id).toBe(originalThread.id); - expect(result.finalResponse).toBe("Second response"); - - expect(requests.length).toBeGreaterThanOrEqual(2); - const secondRequest = requests[1]; - expect(secondRequest).toBeDefined(); - const payload = secondRequest!.json; - - const assistantEntry = payload.input.find( - (entry: { role: string }) => entry.role === "assistant", - ); - expect(assistantEntry).toBeDefined(); - const assistantText = assistantEntry?.content?.find( - (item: { type: string; text: string }) => item.type === "output_text", - )?.text; - expect(assistantText).toBe("First response"); - } finally { - cleanup(); - await close(); - } - }); - - it("passes turn options to exec", async () => { - const { url, close, requests } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Turn options applied", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - - const { args: spawnArgs, restore } = codexExecSpy(); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread({ - model: "gpt-test-1", - sandboxMode: "workspace-write", - }); - await thread.run("apply options"); - - const payload = requests[0]; - expect(payload).toBeDefined(); - const json = payload!.json as { model?: string } | undefined; - - expect(json?.model).toBe("gpt-test-1"); - expect(spawnArgs.length).toBeGreaterThan(0); - const commandArgs = spawnArgs[0]; - - expectPair(commandArgs, ["--sandbox", "workspace-write"]); - expectPair(commandArgs, ["--model", "gpt-test-1"]); - } finally { - cleanup(); - restore(); - await close(); - } - }); - - it("passes modelReasoningEffort to exec", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Reasoning effort applied", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - - const { args: spawnArgs, restore } = codexExecSpy(); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread({ - modelReasoningEffort: "high", - }); - await thread.run("apply reasoning effort"); - - const commandArgs = spawnArgs[0]; - expect(commandArgs).toBeDefined(); - expectPair(commandArgs, ["--config", 'model_reasoning_effort="high"']); - } finally { - cleanup(); - restore(); - await close(); - } - }); - - it("passes networkAccessEnabled to exec", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Network access enabled", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - - const { args: spawnArgs, restore } = codexExecSpy(); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread({ - networkAccessEnabled: true, - }); - await thread.run("test network access"); - - const commandArgs = spawnArgs[0]; - expect(commandArgs).toBeDefined(); - expectPair(commandArgs, ["--config", "sandbox_workspace_write.network_access=true"]); - } finally { - cleanup(); - restore(); - await close(); - } - }); - - it("passes webSearchEnabled to exec", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Web search enabled", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - - const { args: spawnArgs, restore } = codexExecSpy(); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread({ - webSearchEnabled: true, - }); - await thread.run("test web search"); - - const commandArgs = spawnArgs[0]; - expect(commandArgs).toBeDefined(); - expectPair(commandArgs, ["--config", 'web_search="live"']); - } finally { - cleanup(); - restore(); - await close(); - } - }); - - it("passes webSearchMode to exec", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Web search cached", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - - const { args: spawnArgs, restore } = codexExecSpy(); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread({ - webSearchMode: "cached", - }); - await thread.run("test web search mode"); - - const commandArgs = spawnArgs[0]; - expect(commandArgs).toBeDefined(); - expectPair(commandArgs, ["--config", 'web_search="cached"']); - } finally { - cleanup(); - restore(); - await close(); - } - }); - - it("passes webSearchEnabled false to exec", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Web search disabled", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - - const { args: spawnArgs, restore } = codexExecSpy(); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread({ - webSearchEnabled: false, - }); - await thread.run("test web search disabled"); - - const commandArgs = spawnArgs[0]; - expect(commandArgs).toBeDefined(); - expectPair(commandArgs, ["--config", 'web_search="disabled"']); - } finally { - cleanup(); - restore(); - await close(); - } - }); - - it("passes approvalPolicy to exec", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Approval policy set", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - - const { args: spawnArgs, restore } = codexExecSpy(); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread({ - approvalPolicy: "on-request", - }); - await thread.run("test approval policy"); - - const commandArgs = spawnArgs[0]; - expect(commandArgs).toBeDefined(); - expectPair(commandArgs, ["--config", 'approval_policy="on-request"']); - } finally { - cleanup(); - restore(); - await close(); - } - }); - - it("passes CodexOptions config overrides as TOML --config flags", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Config overrides applied", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - - const { args: spawnArgs, restore } = codexExecSpy(); - const { client, cleanup } = createTestClient({ - baseUrl: url, - apiKey: "test", - config: { - approval_policy: "never", - sandbox_workspace_write: { network_access: true }, - retry_budget: 3, - tool_rules: { allow: ["git status", "git diff"] }, - }, - }); - - try { - const thread = client.startThread(); - await thread.run("apply config overrides"); - - const commandArgs = spawnArgs[0]; - expect(commandArgs).toBeDefined(); - expectPair(commandArgs, ["--config", 'approval_policy="never"']); - expectPair(commandArgs, ["--config", "sandbox_workspace_write.network_access=true"]); - expectPair(commandArgs, ["--config", "retry_budget=3"]); - expectPair(commandArgs, ["--config", 'tool_rules.allow=["git status", "git diff"]']); - } finally { - cleanup(); - restore(); - await close(); - } - }); - - it("lets thread options override CodexOptions config overrides", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Thread overrides applied", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - - const { args: spawnArgs, restore } = codexExecSpy(); - const { client, cleanup } = createTestClient({ - baseUrl: url, - apiKey: "test", - config: { approval_policy: "never" }, - }); - - try { - const thread = client.startThread({ approvalPolicy: "on-request" }); - await thread.run("override approval policy"); - - const commandArgs = spawnArgs[0]; - const approvalPolicyOverrides = collectConfigValues(commandArgs, "approval_policy"); - expect(approvalPolicyOverrides).toEqual([ - 'approval_policy="never"', - 'approval_policy="on-request"', - ]); - expect(approvalPolicyOverrides.at(-1)).toBe('approval_policy="on-request"'); - } finally { - cleanup(); - restore(); - await close(); - } - }); - - it("passes additionalDirectories as repeated flags", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Additional directories applied", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - - const { args: spawnArgs, restore } = codexExecSpy(); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread({ - additionalDirectories: ["../backend", "/tmp/shared"], - }); - await thread.run("test additional dirs"); - - const commandArgs = spawnArgs[0]; - expect(commandArgs).toBeDefined(); - if (!commandArgs) { - throw new Error("Command args missing"); - } - - // Find the --add-dir flags - const addDirArgs: string[] = []; - for (let i = 0; i < commandArgs.length; i += 1) { - if (commandArgs[i] === "--add-dir") { - addDirArgs.push(commandArgs[i + 1] ?? ""); - } - } - expect(addDirArgs).toEqual(["../backend", "/tmp/shared"]); - } finally { - cleanup(); - restore(); - await close(); - } - }); - - it("writes output schema to a temporary file and forwards it", async () => { - const { url, close, requests } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Structured response", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - - const { args: spawnArgs, restore } = codexExecSpy(); - - const schema = { - type: "object", - properties: { - answer: { type: "string" }, - }, - required: ["answer"], - additionalProperties: false, - } as const; - - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - await thread.run("structured", { outputSchema: schema }); - - expect(requests.length).toBeGreaterThanOrEqual(1); - const payload = requests[0]; - expect(payload).toBeDefined(); - const text = payload!.json.text; - expect(text).toBeDefined(); - expect(text?.format).toEqual({ - name: "codex_output_schema", - type: "json_schema", - strict: true, - schema, - }); - - const commandArgs = spawnArgs[0]; - expect(commandArgs).toBeDefined(); - const schemaFlagIndex = commandArgs!.indexOf("--output-schema"); - expect(schemaFlagIndex).toBeGreaterThan(-1); - const schemaPath = commandArgs![schemaFlagIndex + 1]; - expect(typeof schemaPath).toBe("string"); - if (typeof schemaPath !== "string") { - throw new Error("--output-schema flag missing path argument"); - } - expect(fs.existsSync(schemaPath)).toBe(false); - } finally { - cleanup(); - restore(); - await close(); - } - }); - it("combines structured text input segments", async () => { - const { url, close, requests } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Combined input applied", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - await thread.run([ - { type: "text", text: "Describe file changes" }, - { type: "text", text: "Focus on impacted tests" }, - ]); - - const payload = requests[0]; - expect(payload).toBeDefined(); - const lastUser = payload!.json.input.at(-1); - expect(lastUser?.content?.[0]?.text).toBe("Describe file changes\n\nFocus on impacted tests"); - } finally { - cleanup(); - await close(); - } - }); - it("forwards images to exec", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Images applied", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - - const { args: spawnArgs, restore } = codexExecSpy(); - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "codex-images-")); - const imagesDirectoryEntries: [string, string] = [ - path.join(tempDir, "first.png"), - path.join(tempDir, "second.jpg"), - ]; - imagesDirectoryEntries.forEach((image, index) => { - fs.writeFileSync(image, `image-${index}`); - }); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - await thread.run([ - { type: "text", text: "describe the images" }, - { type: "local_image", path: imagesDirectoryEntries[0] }, - { type: "local_image", path: imagesDirectoryEntries[1] }, - ]); - - const commandArgs = spawnArgs[0]; - expect(commandArgs).toBeDefined(); - const forwardedImages: string[] = []; - for (let i = 0; i < commandArgs!.length; i += 1) { - if (commandArgs![i] === "--image") { - forwardedImages.push(commandArgs![i + 1] ?? ""); - } - } - expect(forwardedImages).toEqual(imagesDirectoryEntries); - } finally { - cleanup(); - fs.rmSync(tempDir, { recursive: true, force: true }); - restore(); - await close(); - } - }); - it("runs in provided working directory", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Working directory applied", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - - const { args: spawnArgs, restore } = codexExecSpy(); - const workingDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "codex-working-dir-")); - const { client, cleanup } = createTestClient({ - baseUrl: url, - apiKey: "test", - }); - - try { - const thread = client.startThread({ - workingDirectory, - skipGitRepoCheck: true, - }); - await thread.run("use custom working directory"); - - const commandArgs = spawnArgs[0]; - expectPair(commandArgs, ["--cd", workingDirectory]); - } finally { - cleanup(); - fs.rmSync(workingDirectory, { recursive: true, force: true }); - restore(); - await close(); - } - }); - - it("throws if working directory is not git and no skipGitRepoCheck is provided", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Working directory applied", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - const workingDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "codex-working-dir-")); - const { client, cleanup } = createTestClient({ - baseUrl: url, - apiKey: "test", - }); - - try { - const thread = client.startThread({ - workingDirectory, - }); - await expect(thread.run("use custom working directory")).rejects.toThrow( - /Not inside a trusted directory/, - ); - } finally { - cleanup(); - fs.rmSync(workingDirectory, { recursive: true, force: true }); - await close(); - } - }); - - it("sets the codex sdk originator header", async () => { - const { url, close, requests } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [sse(responseStarted(), assistantMessage("Hi!"), responseCompleted())], - }); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - await thread.run("Hello, originator!"); - - expect(requests.length).toBeGreaterThan(0); - const originatorHeader = requests[0]!.headers["originator"]; - if (Array.isArray(originatorHeader)) { - expect(originatorHeader).toContain("codex_sdk_ts"); - } else { - expect(originatorHeader).toBe("codex_sdk_ts"); - } - } finally { - cleanup(); - await close(); - } - }); - it("throws ThreadRunError on turn failures", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: (function* (): Generator { - yield sse(responseStarted("response_1")); - while (true) { - yield sse(responseFailed("rate limit exceeded")); - } - })(), - }); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - await expect(thread.run("fail")).rejects.toThrow("stream disconnected before completion:"); - } finally { - cleanup(); - await close(); - } - }, 10000); // TODO(pakrym): remove timeout -}); - -/** - * Given a list of args to `codex` and a `key`, collects all `--config` - * overrides for that key. - */ -function collectConfigValues(args: string[] | undefined, key: string): string[] { - if (!args) { - throw new Error("args is undefined"); - } - - const values: string[] = []; - for (let i = 0; i < args.length; i += 1) { - if (args[i] !== "--config") { - continue; - } - - const override = args[i + 1]; - if (override?.startsWith(`${key}=`)) { - values.push(override); - } - } - return values; -} - -function expectPair(args: string[] | undefined, pair: [string, string]) { - if (!args) { - throw new Error("args is undefined"); - } - const index = args.findIndex((arg, i) => arg === pair[0] && args[i + 1] === pair[1]); - if (index === -1) { - throw new Error(`Pair ${pair[0]} ${pair[1]} not found in args`); - } - expect(args[index + 1]).toBe(pair[1]); -} diff --git a/vendor/codex/sdk/typescript/tests/runStreamed.test.ts b/vendor/codex/sdk/typescript/tests/runStreamed.test.ts deleted file mode 100644 index 3eb0552d..00000000 --- a/vendor/codex/sdk/typescript/tests/runStreamed.test.ts +++ /dev/null @@ -1,207 +0,0 @@ -import { describe, expect, it } from "@jest/globals"; - -import { ThreadEvent } from "../src/index"; - -import { - assistantMessage, - responseCompleted, - responseStarted, - sse, - startResponsesTestProxy, -} from "./responsesProxy"; -import { createMockClient } from "./testCodex"; - -describe("Codex", () => { - it("returns thread events", async () => { - const { url, close } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [sse(responseStarted(), assistantMessage("Hi!"), responseCompleted())], - }); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - const result = await thread.runStreamed("Hello, world!"); - - const events: ThreadEvent[] = []; - for await (const event of result.events) { - events.push(event); - } - - expect(events).toEqual([ - { - type: "thread.started", - thread_id: expect.any(String), - }, - { - type: "turn.started", - }, - { - type: "item.completed", - item: { - id: "item_0", - type: "agent_message", - text: "Hi!", - }, - }, - { - type: "turn.completed", - usage: { - cached_input_tokens: 12, - input_tokens: 42, - output_tokens: 5, - }, - }, - ]); - expect(thread.id).toEqual(expect.any(String)); - } finally { - cleanup(); - await close(); - } - }); - - it("sends previous items when runStreamed is called twice", async () => { - const { url, close, requests } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("First response", "item_1"), - responseCompleted("response_1"), - ), - sse( - responseStarted("response_2"), - assistantMessage("Second response", "item_2"), - responseCompleted("response_2"), - ), - ], - }); - const { client, cleanup } = createMockClient(url); - - try { - const thread = client.startThread(); - const first = await thread.runStreamed("first input"); - await drainEvents(first.events); - - const second = await thread.runStreamed("second input"); - await drainEvents(second.events); - - // Check second request continues the same thread - expect(requests.length).toBeGreaterThanOrEqual(2); - const secondRequest = requests[1]; - expect(secondRequest).toBeDefined(); - const payload = secondRequest!.json; - - const assistantEntry = payload.input.find( - (entry: { role: string }) => entry.role === "assistant", - ); - expect(assistantEntry).toBeDefined(); - const assistantText = assistantEntry?.content?.find( - (item: { type: string; text: string }) => item.type === "output_text", - )?.text; - expect(assistantText).toBe("First response"); - } finally { - cleanup(); - await close(); - } - }); - - it("resumes thread by id when streaming", async () => { - const { url, close, requests } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("First response", "item_1"), - responseCompleted("response_1"), - ), - sse( - responseStarted("response_2"), - assistantMessage("Second response", "item_2"), - responseCompleted("response_2"), - ), - ], - }); - const { client, cleanup } = createMockClient(url); - - try { - const originalThread = client.startThread(); - const first = await originalThread.runStreamed("first input"); - await drainEvents(first.events); - - const resumedThread = client.resumeThread(originalThread.id!); - const second = await resumedThread.runStreamed("second input"); - await drainEvents(second.events); - - expect(resumedThread.id).toBe(originalThread.id); - - expect(requests.length).toBeGreaterThanOrEqual(2); - const secondRequest = requests[1]; - expect(secondRequest).toBeDefined(); - const payload = secondRequest!.json; - - const assistantEntry = payload.input.find( - (entry: { role: string }) => entry.role === "assistant", - ); - expect(assistantEntry).toBeDefined(); - const assistantText = assistantEntry?.content?.find( - (item: { type: string; text: string }) => item.type === "output_text", - )?.text; - expect(assistantText).toBe("First response"); - } finally { - cleanup(); - await close(); - } - }); - - it("applies output schema turn options when streaming", async () => { - const { url, close, requests } = await startResponsesTestProxy({ - statusCode: 200, - responseBodies: [ - sse( - responseStarted("response_1"), - assistantMessage("Structured response", "item_1"), - responseCompleted("response_1"), - ), - ], - }); - const { client, cleanup } = createMockClient(url); - - const schema = { - type: "object", - properties: { - answer: { type: "string" }, - }, - required: ["answer"], - additionalProperties: false, - } as const; - - try { - const thread = client.startThread(); - const streamed = await thread.runStreamed("structured", { outputSchema: schema }); - await drainEvents(streamed.events); - - expect(requests.length).toBeGreaterThanOrEqual(1); - const payload = requests[0]; - expect(payload).toBeDefined(); - const text = payload!.json.text; - expect(text).toBeDefined(); - expect(text?.format).toEqual({ - name: "codex_output_schema", - type: "json_schema", - strict: true, - schema, - }); - } finally { - cleanup(); - await close(); - } - }); -}); - -async function drainEvents(events: AsyncGenerator): Promise { - let done = false; - do { - done = (await events.next()).done ?? false; - } while (!done); -} diff --git a/vendor/codex/sdk/typescript/tests/setupCodexHome.ts b/vendor/codex/sdk/typescript/tests/setupCodexHome.ts deleted file mode 100644 index 83e49c6a..00000000 --- a/vendor/codex/sdk/typescript/tests/setupCodexHome.ts +++ /dev/null @@ -1,28 +0,0 @@ -import fs from "node:fs/promises"; -import os from "node:os"; -import path from "node:path"; - -import { afterEach, beforeEach } from "@jest/globals"; - -const originalCodexHome = process.env.CODEX_HOME; -let currentCodexHome: string | undefined; - -beforeEach(async () => { - currentCodexHome = await fs.mkdtemp(path.join(os.tmpdir(), "codex-sdk-test-")); - process.env.CODEX_HOME = currentCodexHome; -}); - -afterEach(async () => { - const codexHomeToDelete = currentCodexHome; - currentCodexHome = undefined; - - if (originalCodexHome === undefined) { - delete process.env.CODEX_HOME; - } else { - process.env.CODEX_HOME = originalCodexHome; - } - - if (codexHomeToDelete) { - await fs.rm(codexHomeToDelete, { recursive: true, force: true }); - } -}); diff --git a/vendor/codex/sdk/typescript/tests/testCodex.ts b/vendor/codex/sdk/typescript/tests/testCodex.ts deleted file mode 100644 index a95a6851..00000000 --- a/vendor/codex/sdk/typescript/tests/testCodex.ts +++ /dev/null @@ -1,106 +0,0 @@ -import path from "node:path"; - -import { Codex } from "../src/codex"; -import type { CodexConfigObject } from "../src/codexOptions"; - -export const codexExecPath = - process.env.CODEX_EXEC_PATH ?? - path.join(process.cwd(), "..", "..", "codex-rs", "target", "debug", "codex"); - -type CreateTestClientOptions = { - apiKey?: string; - baseUrl?: string; - config?: CodexConfigObject; - env?: Record; - inheritEnv?: boolean; -}; - -export type TestClient = { - cleanup: () => void; - client: Codex; -}; - -export function createMockClient(url: string): TestClient { - return createTestClient({ - config: { - model_provider: "mock", - model_providers: { - mock: { - name: "Mock provider for test", - base_url: url, - wire_api: "responses", - supports_websockets: false, - }, - }, - }, - }); -} - -export function createTestClient(options: CreateTestClientOptions = {}): TestClient { - const env = - options.inheritEnv === false ? { ...options.env } : { ...getCurrentEnv(), ...options.env }; - - return { - cleanup: () => {}, - client: new Codex({ - codexPathOverride: codexExecPath, - baseUrl: options.baseUrl, - apiKey: options.apiKey, - config: mergeTestConfig(options.baseUrl, options.config), - env, - }), - }; -} - -function mergeTestConfig( - baseUrl: string | undefined, - config: CodexConfigObject | undefined, -): CodexConfigObject | undefined { - const mergedConfig: CodexConfigObject | undefined = - !baseUrl || hasExplicitProviderConfig(config) - ? config - : { - ...config, - // Built-in providers are merged before user config, so tests need a - // custom provider entry to force SSE against the local mock server. - model_provider: "mock", - model_providers: { - mock: { - name: "Mock provider for test", - base_url: baseUrl, - wire_api: "responses", - supports_websockets: false, - }, - }, - }; - const featureOverrides = mergedConfig?.features; - - return { - ...mergedConfig, - // Disable plugins in SDK integration tests so background curated-plugin - // sync does not race temp CODEX_HOME cleanup. - features: - featureOverrides && typeof featureOverrides === "object" && !Array.isArray(featureOverrides) - ? { ...featureOverrides, plugins: false } - : { plugins: false }, - }; -} - -function hasExplicitProviderConfig(config: CodexConfigObject | undefined): boolean { - return config?.model_provider !== undefined || config?.model_providers !== undefined; -} - -function getCurrentEnv(): Record { - const env: Record = {}; - - for (const [key, value] of Object.entries(process.env)) { - if (key === "CODEX_INTERNAL_ORIGINATOR_OVERRIDE") { - continue; - } - if (value !== undefined) { - env[key] = value; - } - } - - return env; -} diff --git a/vendor/codex/sdk/typescript/tsconfig.json b/vendor/codex/sdk/typescript/tsconfig.json deleted file mode 100644 index 8d62e069..00000000 --- a/vendor/codex/sdk/typescript/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "module": "ESNext", - "moduleResolution": "bundler", - "allowSyntheticDefaultImports": true, - "esModuleInterop": true, - "forceConsistentCasingInFileNames": true, - "skipLibCheck": true, - "strict": true, - "noUncheckedIndexedAccess": true, - "resolveJsonModule": true, - "lib": ["ES2022"], - "types": ["node", "jest"], - "sourceMap": true, - "declaration": true, - "declarationMap": true, - "noImplicitAny": true, - "outDir": "dist", - "stripInternal": true - }, - "include": ["src", "tests", "tsup.config.ts", "samples"], - "exclude": ["dist", "node_modules"] -} diff --git a/vendor/codex/sdk/typescript/tsup.config.ts b/vendor/codex/sdk/typescript/tsup.config.ts deleted file mode 100644 index 22bcd039..00000000 --- a/vendor/codex/sdk/typescript/tsup.config.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { defineConfig } from "tsup"; - -export default defineConfig({ - entry: ["src/index.ts"], - format: ["esm"], - dts: true, - sourcemap: true, - clean: true, - minify: false, - target: "node18", - shims: false, -});