From 350220297973ee7658b7b81b61a0166b8dd957a0 Mon Sep 17 00:00:00 2001 From: User Date: Tue, 11 Aug 2026 17:05:56 -0700 Subject: [PATCH 01/30] feat: implement Python SDK v5 Add the typed high-level API, exact low-level namespace, lifecycle-safe streaming and sessions, MCP, observability, documentation, examples, and comprehensive tests. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- README.md | 430 +--- docs/python-sdk-reference.md | 1848 +++++++++++++++ examples/attachments.py | 96 + examples/interaction_helpers.py | 62 + examples/interactions.py | 53 + examples/interactive_session.py | 447 +--- examples/list_saved_sessions.py | 23 + examples/low_level_session.py | 47 + examples/observability.py | 99 + examples/one_shot.py | 23 + examples/resume_session.py | 25 + examples/sdk_mcp.py | 56 + examples/session_operations.py | 50 + examples/structured_output_model.py | 41 + pyproject.toml | 13 + src/droid_sdk/__init__.py | 341 ++- src/droid_sdk/_high_level/__init__.py | 1 + src/droid_sdk/_high_level/_immutable.py | 111 + src/droid_sdk/_high_level/attachments.py | 276 +++ src/droid_sdk/_high_level/config.py | 198 ++ src/droid_sdk/_high_level/discovery.py | 178 ++ src/droid_sdk/_high_level/enums.py | 154 ++ src/droid_sdk/_high_level/extensions.py | 363 +++ .../_high_level/interaction_adapter.py | 330 +++ src/droid_sdk/_high_level/interactions.py | 301 +++ src/droid_sdk/_high_level/messages.py | 535 +++++ src/droid_sdk/_high_level/output.py | 116 + src/droid_sdk/_high_level/runtime.py | 39 + src/droid_sdk/_high_level/session.py | 1998 +++++++++++++++++ src/droid_sdk/_high_level/streaming.py | 1130 ++++++++++ src/droid_sdk/client.py | 321 ++- src/droid_sdk/errors.py | 222 +- src/droid_sdk/low_level/__init__.py | 43 + src/droid_sdk/mcp.py | 487 ++++ src/droid_sdk/observability.py | 232 ++ src/droid_sdk/permissions.py | 31 + src/droid_sdk/protocol.py | 270 ++- src/droid_sdk/schemas/__init__.py | 136 +- src/droid_sdk/schemas/cli.py | 359 ++- src/droid_sdk/schemas/client.py | 661 +++++- src/droid_sdk/schemas/enums.py | 153 +- src/droid_sdk/schemas/mcp.py | 19 +- src/droid_sdk/schemas/messages.py | 94 +- src/droid_sdk/schemas/session.py | 43 + src/droid_sdk/stream.py | 2 + src/droid_sdk/transport.py | 286 ++- src/droid_sdk/types.py | 2 +- tests/mock_droid_subprocess.py | 2 + tests/test_cli_schemas.py | 9 +- tests/test_client.py | 174 +- tests/test_client_mcp.py | 113 + tests/test_client_protocol_surface.py | 168 +- tests/test_client_schemas.py | 36 +- tests/test_client_transport_abstraction.py | 6 +- tests/test_enums.py | 14 +- tests/test_errors.py | 2 +- tests/test_integration.py | 2 +- tests/test_live_droid_exec.py | 10 +- tests/test_low_level_example.py | 100 + tests/test_mcp_schemas.py | 6 +- tests/test_messages.py | 2 +- tests/test_protocol.py | 147 ++ tests/test_public_api.py | 779 +++---- tests/test_query.py | 8 +- tests/test_receive_response.py | 2 +- tests/test_transport.py | 122 +- tests/test_v5_compliance.py | 304 +++ tests/test_v5_discovery.py | 97 + tests/test_v5_foundation.py | 130 ++ tests/test_v5_mcp.py | 271 +++ tests/test_v5_public_models.py | 913 ++++++++ tests/test_v5_session.py | 1053 +++++++++ tests/test_v5_streaming_core.py | 1327 +++++++++++ tests/test_v5_typing_fixtures.py | 58 + tests/typing/negative.py | 65 + tests/typing/positive.py | 286 +++ tests/typing/pyright-negative.json | 6 + uv.lock | 756 ++++++- 78 files changed, 18008 insertions(+), 1705 deletions(-) create mode 100644 docs/python-sdk-reference.md create mode 100644 examples/attachments.py create mode 100644 examples/interaction_helpers.py create mode 100644 examples/interactions.py create mode 100644 examples/list_saved_sessions.py create mode 100644 examples/low_level_session.py create mode 100644 examples/observability.py create mode 100644 examples/one_shot.py create mode 100644 examples/resume_session.py create mode 100644 examples/sdk_mcp.py create mode 100644 examples/session_operations.py create mode 100644 examples/structured_output_model.py create mode 100644 src/droid_sdk/_high_level/__init__.py create mode 100644 src/droid_sdk/_high_level/_immutable.py create mode 100644 src/droid_sdk/_high_level/attachments.py create mode 100644 src/droid_sdk/_high_level/config.py create mode 100644 src/droid_sdk/_high_level/discovery.py create mode 100644 src/droid_sdk/_high_level/enums.py create mode 100644 src/droid_sdk/_high_level/extensions.py create mode 100644 src/droid_sdk/_high_level/interaction_adapter.py create mode 100644 src/droid_sdk/_high_level/interactions.py create mode 100644 src/droid_sdk/_high_level/messages.py create mode 100644 src/droid_sdk/_high_level/output.py create mode 100644 src/droid_sdk/_high_level/runtime.py create mode 100644 src/droid_sdk/_high_level/session.py create mode 100644 src/droid_sdk/_high_level/streaming.py create mode 100644 src/droid_sdk/low_level/__init__.py create mode 100644 src/droid_sdk/mcp.py create mode 100644 src/droid_sdk/observability.py create mode 100644 src/droid_sdk/permissions.py create mode 100644 src/droid_sdk/schemas/session.py create mode 100644 tests/test_low_level_example.py create mode 100644 tests/test_v5_compliance.py create mode 100644 tests/test_v5_discovery.py create mode 100644 tests/test_v5_foundation.py create mode 100644 tests/test_v5_mcp.py create mode 100644 tests/test_v5_public_models.py create mode 100644 tests/test_v5_session.py create mode 100644 tests/test_v5_streaming_core.py create mode 100644 tests/test_v5_typing_fixtures.py create mode 100644 tests/typing/negative.py create mode 100644 tests/typing/positive.py create mode 100644 tests/typing/pyright-negative.json diff --git a/README.md b/README.md index fd6a0a7..e8a0899 100644 --- a/README.md +++ b/README.md @@ -1,376 +1,184 @@ # Factory Droid SDK for Python -A Python asyncio SDK for communicating with the [Factory](https://factory.ai) Droid agent via JSON-RPC 2.0 over a subprocess (`droid exec`). +Async Python 3.10+ SDK for local Factory Droid sessions. -## Requirements - -- Python 3.10+ -- `droid` CLI installed (available at `~/.local/bin/droid`) - -## Installation +## Install and authenticate ```bash pip install droid-sdk ``` -Or with [uv](https://docs.astral.sh/uv/): +Use an authenticated local Droid CLI session, or set `FACTORY_API_KEY`. -```bash -uv add droid-sdk -``` +The `droid` executable must be on `PATH`. Keys are passed through the child +process environment, never command arguments. -## Quick Start +## One turn or a conversation -The simplest way to use the SDK is with the `query()` convenience function, which handles the full session lifecycle automatically: +Use `run()` for one turn: ```python import asyncio -from droid_sdk import query, DroidQueryOptions -from droid_sdk.stream import AssistantTextDelta, TurnComplete +from droid_sdk import run -async def main(): - async for msg in query("Explain this codebase", cwd="/path/to/project"): - if isinstance(msg, AssistantTextDelta): - print(msg.text, end="", flush=True) - elif isinstance(msg, TurnComplete): - print("\nDone!") +async def main() -> None: + result = await run("Summarize this repository.", timeout=60) + print(result.text if result.success else result.subtype) asyncio.run(main()) ``` -You can also pass a `DroidQueryOptions` object for more control: +Use `Session` for shared history and operations: ```python -async def main(): - options = DroidQueryOptions( - cwd="/path/to/project", - model_id="claude-sonnet-4", - reasoning_effort=ReasoningEffort.High, - ) - async for msg in query("Fix the bug in main.py", options=options): - if isinstance(msg, AssistantTextDelta): - print(msg.text, end="", flush=True) -``` - -### Using DroidClient directly +import asyncio -For more control over the session lifecycle, use `DroidClient` directly with `receive_response()`: +from droid_sdk import AssistantMessage, Session -```python -import asyncio -from droid_sdk import ( - DroidClient, - ProcessTransport, - AssistantTextDelta, - ThinkingTextDelta, - ToolUse, - ToolResult, - TurnComplete, -) - -async def main(): - # Create a transport that spawns a droid exec subprocess - transport = ProcessTransport(exec_path="droid", cwd="/path/to/project") - - # Use as an async context manager for automatic cleanup - async with DroidClient(transport=transport) as client: - # Initialize a new session - result = await client.initialize_session( - machine_id="my-machine", - cwd="/path/to/project", - ) - print(f"Session ID: {result.session_id}") - - # Send a message and stream the response - await client.add_user_message(text="Hello, Droid!") - - async for msg in client.receive_response(): - if isinstance(msg, AssistantTextDelta): - print(msg.text, end="", flush=True) - elif isinstance(msg, ThinkingTextDelta): - print(f"[thinking] {msg.text}") - elif isinstance(msg, ToolUse): - print(f"\nšŸ”§ Using tool: {msg.tool_name}") - elif isinstance(msg, ToolResult): - print(f" Result: {msg.content}") - elif isinstance(msg, TurnComplete): - if msg.token_usage: - print(f"\nTokens: {msg.token_usage.input_tokens} in / {msg.token_usage.output_tokens} out") - print("Done!") - - # Transport and subprocess are cleaned up automatically +async def main() -> None: + async with Session() as session: + async with session.stream("What does this project do?") as stream: + async for event in stream: + if isinstance(event, AssistantMessage): + print(event.text) + print(stream.result.subtype, session.id) asyncio.run(main()) ``` -## Event Handling +Sessions are lazy. `async with` opens and closes them. A manually opened +session must be closed by its caller. A session permits one active stream; +different sessions can run concurrently. Breaking iteration inside the stream +context, timeout, or task cancellation performs a best-effort interrupt and +detaches subscriptions. `run()` always closes everything it creates. -Register listeners for real-time notifications from the droid process: +## Results, errors, and typing -```python -from droid_sdk import ( - DroidClient, - ProcessTransport, - SessionNotificationType, -) - -async def main(): - transport = ProcessTransport(exec_path="droid", cwd="/path/to/project") - async with DroidClient(transport=transport) as client: - # Listen for all notifications - def on_notification(notification): - params = notification.get("params", {}) - inner = params.get("notification", {}) - print(f"Notification type: {inner.get('type')}") - - client.on_notification(on_notification) - - # Or filter by notification type - def on_text_delta(notification): - params = notification["params"]["notification"] - print(params.get("textDelta", ""), end="", flush=True) - - client.on_notification( - on_text_delta, - notification_type=SessionNotificationType.ASSISTANT_TEXT_DELTA, - ) - - result = await client.initialize_session( - machine_id="my-machine", - cwd="/path/to/project", - ) - await client.add_user_message(text="Explain this codebase") - - # Keep running to receive streamed notifications - import asyncio - await asyncio.sleep(60) -``` +Terminal outcomes are immutable `RunSuccess`, `RunInterrupted`, or +`RunFailure` values. Execution, interruption, and structured-output failures +do not raise. Setup, connection, process, protocol, timeout, and cancellation +failures do. `asyncio.CancelledError` is never wrapped. -## Stream Type Checking +The wheel contains `py.typed`. Result and event unions narrow with +`isinstance()`. `stream.result` is cached after completion and raises +`StreamIncompleteError` before then. -All stream message types are simple dataclasses that can be used with `isinstance()` for type-safe message handling: +## Structured output and attachments ```python -from droid_sdk import ( - AssistantTextDelta, - ThinkingTextDelta, - ToolUse, - ToolResult, - ToolProgress, - WorkingStateChanged, - TokenUsageUpdate, - TurnComplete, - ErrorEvent, - StreamMessage, -) - -def handle_message(msg: StreamMessage) -> None: - """Handle a stream message with exhaustive type checking.""" - if isinstance(msg, AssistantTextDelta): - print(msg.text, end="", flush=True) - elif isinstance(msg, ThinkingTextDelta): - print(f"[thinking] {msg.text}") - elif isinstance(msg, ToolUse): - print(f"Tool call: {msg.tool_name}({msg.tool_input})") - elif isinstance(msg, ToolResult): - status = "āŒ" if msg.is_error else "āœ…" - # tool_use_id correlates the result with its ToolUse; tool_name is - # backfilled from that call (None if the call was never seen). - print(f"{status} [{msg.tool_use_id}] {msg.tool_name}: {msg.content}") - elif isinstance(msg, ToolProgress): - print(f" ā³ {msg.tool_name}: {msg.content}") - elif isinstance(msg, WorkingStateChanged): - print(f"State: {msg.state.value}") - elif isinstance(msg, TokenUsageUpdate): - print(f"Tokens: {msg.input_tokens} in / {msg.output_tokens} out") - elif isinstance(msg, TurnComplete): - print("\n--- Turn complete ---") - elif isinstance(msg, ErrorEvent): - # error_type is often the unhelpful "Error"; error_name exposes the - # nested error.name (e.g. "LLMInvalidRequestError") to branch on. - print(f"Error [{msg.error_name or msg.error_type}]: {msg.message}") -``` +import asyncio -## Permission Handler +from pydantic import BaseModel +from droid_sdk import Document, Image, run -Handle permission requests when Droid needs approval to execute tools: +class Summary(BaseModel): + title: str + risks: list[str] -```python -from droid_sdk import DroidClient, ProcessTransport, ToolConfirmationOutcome - -async def main(): - transport = ProcessTransport(exec_path="droid", cwd="/path/to/project") - async with DroidClient(transport=transport) as client: - - def handle_permission(params): - tool_uses = params.get("toolUses", []) - for tool in tool_uses: - tool_use = tool.get("toolUse", {}) - print(f"Permission requested for: {tool_use.get('name')}") - # Approve the action - return ToolConfirmationOutcome.ProceedOnce.value - - client.set_permission_handler(handle_permission) - - result = await client.initialize_session( - machine_id="my-machine", - cwd="/path/to/project", - ) - await client.add_user_message(text="Create a hello.py file") -``` - -## Error Handling - -The SDK provides a typed error hierarchy: +async def main() -> None: + result = await run( + "Summarize these inputs.", + output=Summary, + images=[Image.from_path("screen.png")], + files=[Document.from_text("notes", name="notes.txt")], + ) + if result.output is not None: + print(result.output.title) -```python -from droid_sdk import ( - DroidClient, - DroidClientError, - ConnectionError, - TimeoutError, - ProtocolError, - SessionError, - SessionNotFoundError, - ProcessExitError, -) - -async def main(): - # ... setup client ... - try: - result = await client.load_session(session_id="nonexistent") - except SessionNotFoundError as e: - print(f"Session not found: {e.session_id}") - except TimeoutError as e: - print(f"Request timed out after {e.timeout_duration}s") - except ConnectionError as e: - print(f"Connection failed: {e}") - except ProtocolError as e: - print(f"Protocol error (code={e.code}): {e.message}") - except DroidClientError as e: - print(f"SDK error: {e}") +asyncio.run(main()) ``` -**Error hierarchy:** - -- `DroidClientError` — base for all SDK errors - - `ConnectionError` — transport/connection failures - - `TimeoutError` — request timeout - - `ProtocolError` — JSON-RPC protocol errors - - `SessionError` — session-related errors - - `SessionNotFoundError` — session does not exist - - `ProcessExitError` — subprocess exited unexpectedly +`JsonSchema` provides raw object-shaped JSON Schema output. Local constructors +support PNG/JPEG/GIF/WebP images, text documents, and PDFs. Invalid inputs +raise `InvalidAttachmentError` before a turn starts. -## API Reference +## Interactions and controls -### `DroidClient` +Attach `InteractionHandlers(on_permission=..., on_question=...)`. Permission +responses must choose an option offered by Droid; invalid responses and +handler failures safely cancel. Typed action classes are available from +`droid_sdk.permissions`. -The main client class. Wraps a transport and provides typed async methods for all `droid.*` RPC methods. +`SessionConfig` and `update_settings()` support model, reasoning, mode, +autonomy, tags, and all four native-tool controls: -**Session methods:** -- `initialize_session(...)` — Create a new session (supports `enabled_tool_ids` and `disabled_tool_ids`) -- `load_session(session_id=...)` — Load an existing session -- `add_user_message(text=..., output_format=...)` — Send a user message, optionally with a structured-output (JSON Schema) contract -- `interrupt_session()` — Interrupt the current session -- `kill_worker_session(worker_session_id=...)` — Kill a worker session -- `update_session_settings(...)` — Update session settings (supports `enabled_tool_ids`/`disabled_tool_ids`) -- `close_session(reason=...)` — Close the active session -- `compact_session(custom_instructions=...)` — Compact the conversation to reclaim context -- `fork_session(title=..., tags=...)` — Fork the session into a new one -- `rename_session(title=...)` — Rename the session +- `additional_tools`: add catalog IDs +- `enabled_tools`: enable available IDs +- `disabled_tools`: subtract IDs +- `restrict_tools`: restrictive allowlist; it never elevates permission -**Discovery methods:** -- `list_tools(...)` — List native CLI tools with `default_allowed`/`currently_allowed` (useful for locking the tool set down) -- `list_commands()` — List custom slash commands +Use `list_tools()`, `list_skills()`, MCP operations, `context()`, +`enter_spec()`/`leave_spec()`, `rename()`, and raw filtered +`on_notification()` subscriptions for ongoing sessions. -**Context and rewind methods:** -- `get_context_stats()` — Context-window usage (used/remaining/limit) -- `get_context_breakdown()` — Per-category/skill/MCP/droid token breakdown -- `get_rewind_info(message_id=...)` — Restorable/created/evicted files for a rewind point -- `execute_rewind(...)` — Rewind to a message, forking the session - -**Locking the tool set down:** +## Resume and replacement ownership ```python -# enabled_tool_ids is additive, so pass an explicit disable list to -# actually restrict native tools. list_tools() lets you verify the result. -catalog = await client.list_tools() -tool_ids = [t.id for t in catalog.tools] -await client.update_session_settings(enabled_tool_ids=[], disabled_tool_ids=tool_ids) +async with Session.resume(saved_id) as session: + ... ``` -**Structured output:** +Resume restores persisted history, cwd, title, and settings; handlers, runtime, +tool policy, observability, and session-scoped MCP servers must be attached +again. -```python -await client.add_user_message( - text="Return an answer.", - output_format={ - "type": "json_schema", - "schema": { - "type": "object", - "properties": {"answer": {"type": "integer"}}, - "required": ["answer"], - }, - }, -) -``` - -**MCP methods:** -- `toggle_mcp_server(...)` — Enable/disable an MCP server -- `authenticate_mcp_server(...)` — Authenticate an MCP server (OAuth) -- `cancel_mcp_auth(...)` / `clear_mcp_auth(...)` — Cancel/clear MCP auth -- `submit_mcp_auth_code(...)` — Submit an MCP auth code -- `add_mcp_server(...)` / `remove_mcp_server(...)` — Add/remove MCP servers -- `list_mcp_registry()` / `list_mcp_tools()` / `list_mcp_servers()` — List MCP resources -- `toggle_mcp_tool(...)` — Enable/disable an MCP tool +`fork()`, `compact()`, and `rewind()` return an already-open successor that +owns the existing connection. The source is retired: identity remains +readable, active methods raise `SessionReplacedError`, and source `close()` is +a no-op. -**Other methods:** -- `list_skills()` — List available skills -- `submit_bug_report(...)` — Submit a bug report +## MCP and custom runtime -**Event system:** -- `on_notification(callback, notification_type=None)` — Register a notification listener -- `set_permission_handler(handler)` / `clear_permission_handler()` — Permission handling -- `set_ask_user_handler(handler)` / `clear_ask_user_handler()` — Ask-user handling +External stdio, HTTP, and SSE configs live in `droid_sdk.mcp`. Annotated +Python functions can be exposed through an authenticated loopback-only +Streamable HTTP server: -**Lifecycle:** -- `connect()` / `close()` — Manual connection management -- `async with DroidClient(...) as client:` — Context manager (recommended) - -### `ProcessTransport` +```python +from droid_sdk import SessionConfig +from droid_sdk.mcp import create_sdk_mcp_server, tool -Spawns a `droid exec` subprocess and manages JSONL communication over stdin/stdout. +@tool("lookup", "Look up a local value.") +def lookup(key: str) -> str: + return f"value:{key}" -### `DroidClientTransport` +server = create_sdk_mcp_server("local-tools", [lookup]) +config = SessionConfig(mcp_servers=[server]) +``` -Protocol (interface) that all transport implementations must satisfy. Use this to create custom transports for testing or alternative communication channels. +The session starts and stops SDK MCP servers. Every start uses an ephemeral +port and fresh bearer token. -## Development +`Runtime` configures executable, extra args, environment, transport, and +privacy-safe observability. A caller transport must already be connected, +takes precedence over process options, and is closed by the session. -```bash -# Install dependencies -uv sync +## Saved sessions and examples -# Run tests -uv run --group dev python -m pytest +`await list_sessions()` reads local session files without starting Droid. +Use `all_workspaces=True`, `cwd=`, or `limit=`. -# Run opt-in tests against the installed, authenticated droid exec CLI. -# These create real sessions and consume model usage. -DROID_LIVE_TESTS=1 uv run --group dev python -m pytest \ - tests/test_live_droid_exec.py -v +Runnable examples are under `examples/`; offline examples require no +credentials, while model examples use bounded prompts and finite timeouts. +The complete command matrix is in +[`docs/python-sdk-reference.md`](docs/python-sdk-reference.md#runnable-examples). +See the complete contract in +[`docs/python-sdk-reference.md`](docs/python-sdk-reference.md). -# Override the executable path when droid is not on PATH. -DROID_LIVE_TESTS=1 DROID_EXEC_PATH=/path/to/droid \ - uv run --group dev python -m pytest tests/test_live_droid_exec.py -v +## Low-level escape hatch -# Type check (strict mode) -uv run mypy --strict src/ +Applications that own JSON-RPC lifecycle can import `DroidClient`, +`ProcessTransport`, transport protocols, and wire schemas from +`droid_sdk.low_level`. Legacy query/client/transport/event aliases are not +exported at package root. Mission and daemon APIs are excluded from the +package root; Mission wire schemas remain available through +`droid_sdk.low_level`. -# Lint and format -uv run ruff check src/ tests/ -uv run ruff format --check src/ tests/ -``` +## Limitations -## License +- Local `droid` subprocesses only +- asyncio only +- one active turn per session +- hooks remain file-configured +- image URLs are unsupported -Apache 2.0 — see [LICENSE](LICENSE) for details. +Apache-2.0. See [LICENSE](LICENSE). diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md new file mode 100644 index 0000000..ec79b1c --- /dev/null +++ b/docs/python-sdk-reference.md @@ -0,0 +1,1848 @@ +# Factory Droid SDK for Python, v5 API + +> Implemented public API for the Python SDK v5 line. + +The Python SDK follows the concepts and behavior of the Droid TypeScript SDK. +Python differences are limited to naming, typing, and async resource ownership. + +Install the package as `droid-sdk` and import it as `droid_sdk`. + +## Overview + +The first release starts a local `droid` subprocess and exposes two ways to +run a turn: + +| Goal | API | +| --- | --- | +| Run one turn and return its result | `await run(...)` | +| Run turns in an existing session | `session.stream(...)` | + +Use `Session` when prompts need shared history or session operations such as +interruption, compaction, or rewind. `Session` does not have a `run()` method. + +## Install and authenticate + +```bash +pip install droid-sdk +``` + +Requirements: + +- Python 3.10 or later +- `droid` on `PATH` +- an authenticated Droid CLI session or a Factory API key + +The SDK uses the Droid CLI's local authentication by default. It reads +`FACTORY_API_KEY` when present; pass `api_key=` only when the key comes from +application configuration. The SDK never places keys in command arguments, +logs, or exception messages. + +## Quick start + +### Run one turn + +```python +import asyncio + +from droid_sdk import run + + +async def main() -> None: + result = await run("Summarize this repository.") + if result.success: + print(result.text) + else: + print(result.subtype) + + +asyncio.run(main()) +``` + +`run()` creates a persisted session, consumes one default stream, and closes +the process and resources it owns. The saved session remains resumable. +See [Result types](#result-types) for every terminal outcome. + +### Continue a conversation + +```python +import asyncio +from pathlib import Path + +from droid_sdk import Session + + +async def run_turn(session: Session, prompt: str) -> str: + async with session.stream(prompt) as stream: + async for _ in stream: + pass + + result = stream.result + if not result.success: + raise RuntimeError(result.subtype) + return result.text + + +async def main() -> None: + async with Session(cwd=Path.cwd()) as session: + print(await run_turn(session, "What does this project do?")) + print(await run_turn(session, "What should I test first?")) + + +asyncio.run(main()) +``` + +The second turn includes context from the first. Exiting the session closes +the subprocess and session-owned resources. See +[Default stream types](#default-stream-types) for every yielded value. + +### Stream partial events + +```python +from droid_sdk import Session, TextDelta + +async with Session() as session: + async with session.stream( + "Explain the failing test.", + include_partial_messages=True, + ) as stream: + async for event in stream: + if isinstance(event, TextDelta): + print(event.text, end="", flush=True) + + print() + if not stream.result.success: + print(f"Turn ended: {stream.result.subtype}") +``` + +The default stream yields complete messages. Set +`include_partial_messages=True` to add deltas and operational events. Both +modes yield the terminal result and cache it in `stream.result`. See +[Partial stream types](#partial-stream-types) for the complete event union. + +## Core contract + +### Sessions and turns + +A `Session` owns conversation history, settings, a working directory, and one +Droid connection. It accepts one active turn at a time. + +A turn begins with `session.stream(prompt)` and ends when the stream yields a +`RunResult`. Create separate sessions for parallel work. + +### Results and exceptions + +Droid outcomes are results: + +- `RunSuccess` +- `RunInterrupted` +- `RunFailure` + +Interrupted turns, execution failures, and structured-output failures do not +raise. Setup, transport, process, protocol, timeout, and cancellation failures +raise exceptions. + +### Ownership + +| Object | Owner | +| --- | --- | +| Resources created by `run()` | `run()` | +| `Session` used with `async with` | The context manager | +| Manually opened `Session` | The caller | +| In-process MCP servers | The session | +| Caller-provided transport | The session | + +### Typing + +The package includes `py.typed`. Public unions narrow with `isinstance()`. +High-level value models are immutable dataclasses. `TraceContext` is a mutable +carrier so tracing providers can inject values. + +| Call | Static return type | +| --- | --- | +| `run(..., output=None)` | `RunResult[None]` | +| `run(..., output=Model)` | `RunResult[Model]` | +| `run(..., output=JsonSchema(...))` | `RunResult[JsonObject]` | +| `session.stream(...)` | `RunStream[T, StreamMessage[T]]` | +| Partial `session.stream(...)` | `RunStream[T, StreamEvent[T]]` | +| `stream.result` | `RunResult[T]` | + +Pydantic provides typed structured-output adapters. JSON-RPC boundaries use +the protocol models. Strict Pyright, mypy, and type tests are release gates. + +## Models + +Model IDs are strings because availability depends on account and +organization policy. Omit `model` to use the configured default. + +### Select a model + +```python +from droid_sdk import ReasoningEffort, run + +result = await run( + "Review this repository.", + model="model-id", + reasoning_effort=ReasoningEffort.HIGH, +) +``` + +Omit `reasoning_effort` to use the model default. + +Change the model for later turns: + +```python +await session.update_settings( + model="model-id", + reasoning_effort=ReasoningEffort.HIGH, +) +``` + +### Configure mode-specific models + +```python +from droid_sdk import Mode, Session, SessionConfig + +config = SessionConfig( + mode=Mode.SPEC, + spec_model="model-id", + spec_reasoning_effort=ReasoningEffort.HIGH, +) + +async with Session(model="auto", config=config) as session: + async with session.stream("Draft an implementation plan.") as stream: + async for _ in stream: + pass +``` + +The primary model handles Auto turns. `spec_model` handles Spec turns. + +### Model configuration contract + +| Field | Type | Used by | +| --- | --- | --- | +| `model` | `str \| None` | `run()`, `Session`, `update_settings()` | +| `reasoning_effort` | `ReasoningEffort \| None` | Same | +| `spec_model` | `str \| None` | `SessionConfig`, `update_settings()` | +| `spec_reasoning_effort` | `ReasoningEffort \| None` | Same | + +Model IDs are opaque strings. `None` uses the configured default. Setting a +nullable Spec field to `None` through `update_settings()` clears it. + +## Sessions + +Use a session when turns share history. + +### Open a session + +`Session` is lazy. It creates the subprocess and session on entry: + +```python +async with Session( + cwd=Path.cwd(), + model="auto", +) as session: + async with session.stream("Review the project.") as stream: + async for message in stream: + handle(message) +``` + +```python +from droid_sdk import Autonomy, InteractionHandlers, SessionConfig + +config = SessionConfig( + autonomy=Autonomy.LOW, + disabled_tools={"Execute"}, + disable_builtin_skills=True, +) + +async with Session( + config=config, + interactions=InteractionHandlers(on_permission=approve), +) as session: + ... +``` + +`SessionConfig` also accepts mode-specific models, MCP servers, tags, source +attribution, `machine_id`, automatic permission rejection, and native-tool +overrides. It does not expose a system-prompt API. + +### Resume a saved session + +```python +async with Session.resume( + session_id, + interactions=InteractionHandlers(on_question=answer), + disabled_tools={"Execute"}, +) as session: + async with session.stream("Continue the previous task.") as stream: + async for _ in stream: + pass +``` + +Resume restores conversation history, working directory, title, and settings. +It can reattach interaction handlers, MCP servers, observability, transport, +the disabled-tool policy, built-in-skill policy, automatic permission +rejection, and source attribution. It does not accept a new working directory +or model. + +### Open and close manually + +```python +session = Session() +await session.open() + +try: + async with session.stream("Review the project.") as stream: + async for _ in stream: + pass +finally: + await session.close() +``` + +Repeated `open()` while open and repeated `close()` after closing are safe. +A closed session cannot be reopened. Calling an active method before `open()` +raises `SessionNotOpenError`. + +Concurrent `open()` calls share one startup attempt. If one waiter is +cancelled, startup continues for the others. Cancelling the final waiter +cancels startup and completes resource cleanup before the session becomes +retryable. `close()` racing startup waits for startup cleanup and leaves the +session closed. + +### Read session state + +```python +print(session.id) +print(session.cwd) +print(session.settings.model) +print(session.settings.mode) +``` + +These properties are read-only. The immutable settings snapshot updates when +Droid reports a settings change. + +### Update settings + +```python +await session.update_settings( + model="model-id", + reasoning_effort=ReasoningEffort.HIGH, + autonomy=Autonomy.MEDIUM, + disabled_tools={"Execute"}, +) +``` + +Only supplied fields change. The method also accepts interaction mode, +mode-specific model settings, tags, compaction settings, and all native-tool +override fields. Set nullable Spec-model fields to `None` to clear them. + +`update_settings()` accepts: + +| Field | Type | +| --- | --- | +| `model` | `str \| None` | +| `reasoning_effort` | `ReasoningEffort \| None` | +| `mode` | `Mode \| None` | +| `autonomy` | `Autonomy \| None` | +| `spec_model` | `str \| None` | +| `spec_reasoning_effort` | `ReasoningEffort \| None` | +| `tags` | `Sequence[SessionTag] \| None` | +| `compaction_token_limit` | `int \| None` | +| `compaction_threshold_check_enabled` | `bool \| None` | +| `additional_tools` | `set[str] \| frozenset[str] \| None` | +| `enabled_tools` | `set[str] \| frozenset[str] \| None` | +| `disabled_tools` | `set[str] \| frozenset[str] \| None` | +| `restrict_tools` | `set[str] \| frozenset[str] \| None` | + +It returns `UpdateSettingsResult`. The result currently has no fields. + +### Rename a session + +```python +await session.rename("Authentication review") +``` + +`rename(title: str)` returns `None`. + +### Subscribe to raw notifications + +```python +unsubscribe = session.on_notification(handle_notification, type="custom_type") +try: + ... +finally: + unsubscribe() +``` + +High-level streams ignore unknown notifications. `on_notification()` exposes +them without creating a second client. + +### List saved sessions + +```python +from droid_sdk import list_sessions + +for saved in await list_sessions(limit=10): + print(saved.id, saved.title, saved.modified_at) +``` + +List sessions across working directories: + +```python +sessions = await list_sessions(all_workspaces=True, limit=20) +``` + +`list_sessions()` reads local files without starting Droid. Results are newest +first. Timestamps are timezone-aware. + +### Session construction contract + +`Session(...)` accepts: + +| Argument | Type | +| --- | --- | +| `cwd` | `str \| Path \| None` | +| `model` | `str \| None` | +| `reasoning_effort` | `ReasoningEffort \| None` | +| `config` | `SessionConfig \| None` | +| `interactions` | `InteractionHandlers \| None` | +| `runtime` | `Runtime \| None` | +| `api_key` | `str \| None` | + +`SessionConfig` fields: + +| Field | Type | +| --- | --- | +| `mode` | `Mode \| None` | +| `autonomy` | `Autonomy \| None` | +| `spec_model` | `str \| None` | +| `spec_reasoning_effort` | `ReasoningEffort \| None` | +| `mcp_servers` | `Sequence[McpServerConfig]` | +| `machine_id` | `str \| None` | +| `tags` | `Sequence[SessionTag]` | +| `session_source` | `SessionSource \| None` | +| `auto_reject_permission_requests` | `bool \| None` | +| `disable_builtin_skills` | `bool \| None` | +| `additional_tools` | `set[str] \| frozenset[str] \| None` | +| `enabled_tools` | `set[str] \| frozenset[str] \| None` | +| `disabled_tools` | `set[str] \| frozenset[str] \| None` | +| `restrict_tools` | `set[str] \| frozenset[str] \| None` | + +`Session.resume(session_id, ...)` accepts only values that can be reattached: + +| Argument | Type | +| --- | --- | +| `session_id` | `str` | +| `interactions` | `InteractionHandlers \| None` | +| `mcp_servers` | `Sequence[McpServerConfig]` | +| `runtime` | `Runtime \| None` | +| `api_key` | `str \| None` | +| `disabled_tools` | `set[str] \| frozenset[str] \| None` | +| `auto_reject_permission_requests` | `bool \| None` | +| `disable_builtin_skills` | `bool \| None` | +| `session_source` | `SessionSource \| None` | + +### Session state schemas + +| Type | Fields | +| --- | --- | +| `SessionSettings` | `model`, `reasoning_effort`, `mode`, `autonomy` | +| `SessionSettings` | `spec_model`, `spec_reasoning_effort`, `tags`, `sandbox` | +| `SessionSettings` | `additional_tools`, `enabled_tools`, `disabled_tools` | +| `SessionSettings` | `restrict_tools` | +| `SessionSettingsUpdate` | `model`, `reasoning_effort`, `mode`, `autonomy` | +| `SessionSettingsUpdate` | `spec_model`, `spec_reasoning_effort`, `tags` | +| `SessionSettingsUpdate` | `additional_tools`, `enabled_tools`, `disabled_tools` | +| `SessionSettingsUpdate` | `restrict_tools`, `compaction_threshold_check_enabled` | +| `SandboxSettings` | `enabled: bool`, `mode: str \| None = None` | +| `SessionTag` | `name`, `metadata` | +| `SavedSession` | `id`, `title`, `owner`, `message_count` | +| `SavedSession` | `modified_at`, `created_at`, `cwd`, `is_favorite` | + +Every `SessionSettingsUpdate` field defaults to `None`: + +| Field | Type | +| --- | --- | +| `model` | `str \| None` | +| `reasoning_effort` | `ReasoningEffort \| None` | +| `mode` | `Mode \| None` | +| `autonomy` | `Autonomy \| None` | +| `spec_model` | `str \| None` | +| `spec_reasoning_effort` | `ReasoningEffort \| None` | +| `tags` | `Sequence[SessionTag] \| None` | +| `additional_tools`, `enabled_tools` | `set[str] \| frozenset[str] \| None` | +| `disabled_tools`, `restrict_tools` | `set[str] \| frozenset[str] \| None` | +| `compaction_threshold_check_enabled` | `bool \| None` | + +`list_sessions()` returns `list[SavedSession]`. Its filters are `cwd`, +`all_workspaces`, and `limit`. + +`on_notification(callback, type=None)` passes +`Mapping[str, object]` to the callback and returns an unsubscribe function. + +`SessionSource` requires `platform: SessionPlatform`; all remaining attribution +fields default to `None`: `delegation_session_id`, `team_id`, `channel`, +`thread_ts`, `user_id`, `automation_id`, `agent_session_id`, `issue_id`, +`issue_url`, `issue_identifier`, `organization_id`, `cloud_id`, `issue_key`, +`site_id`, `project_id`, `comment_id`, `task_id`, `tenant_id`, +`conversation_id`, `service_url`, `conversation_type`, `root_message_id`, +`channel_id`, `aad_object_id`, `report_id`, `repo_url`, `criterion_id`, and +`computer_id`. Required combinations are validated when converted to the +wire protocol. + +### What persists + +| Restored | Attach again | +| --- | --- | +| Conversation history | Interaction handlers | +| Working directory | Session-scoped MCP servers | +| Title | Observability sinks | +| Session settings | Custom transport | + +## Streaming and results + +Use top-level `run()` when only the result matters. Session turns always use +`stream()`. + +`session.stream()` accepts: + +| Argument | Type | +| --- | --- | +| `prompt` | `str` | +| `images` | `Sequence[Image]` | +| `files` | `Sequence[Document]` | +| `output` | `type[BaseModel] \| JsonSchema \| None` | +| `timeout` | `float \| None` | +| `include_partial_messages` | `bool` | + +### Complete messages by default + +```python +from droid_sdk import AssistantMessage + +async with session.stream("Run the tests.") as stream: + async for message in stream: + if isinstance(message, AssistantMessage): + print(message.text) +``` + +### Default stream types + +```python +StreamMessage[T] = ( + UserMessage + | AssistantMessage + | ToolCall + | ToolResult + | HookExecution + | ErrorEvent + | RunResult[T] +) +``` + +`session.stream(prompt)` yields: + +| Type | Fields | +| --- | --- | +| `UserMessage` | Conversation-message fields | +| `AssistantMessage` | Conversation-message fields | +| `ToolCall` | `name`, `tool_use_id`, `input` | +| `ToolResult` | `tool_use_id`, `tool_name`, `content`, `is_error` | +| `HookExecution` | `hook_id`, `event_name`, `matcher`, `tool_call_id` | +| `HookExecution` | `command`, `timeout`, `status`, `exit_code` | +| `HookExecution` | `stdout`, `stderr`, `suppress_output` | +| `ErrorEvent` | `message`, `error_type`, `timestamp` | +| `RunResult[T]` | Terminal result described below | + +Values appear in delivery order. `RunResult[T]` is always last. + +### Include partial events + +```python +from droid_sdk import RunResult, TextDelta + +async with session.stream( + "Explain the failing test.", + include_partial_messages=True, +) as stream: + async for event in stream: + if isinstance(event, TextDelta): + print(event.text, end="", flush=True) + elif isinstance(event, RunResult) and not event.success: + print(f"\nTurn ended: {event.subtype}") +``` + +### Partial stream types + +```python +StreamEvent[T] = ( + StreamMessage[T] + | TextDelta + | TextComplete + | ThinkingDelta + | ThinkingComplete + | ToolCallDelta + | ToolProgress + | TokenUsageUpdate + | WorkingStateChanged + | PermissionResolved + | SettingsUpdated + | SessionTitleUpdated + | SessionWorkingDirectoryChanged + | McpStatusChanged + | McpAuthRequired + | McpAuthCompleted +) +``` + +With `include_partial_messages=True`, the stream yields every +`StreamMessage[T]` plus: + +| Type | Fields | +| --- | --- | +| `TextDelta` | `message_id`, `block_index`, `text` | +| `TextComplete` | `message_id`, `block_index` | +| `ThinkingDelta` | `message_id`, `block_index`, `text` | +| `ThinkingComplete` | `message_id`, `block_index`, `duration` | +| `ToolCallDelta` | `tool_use` | +| `ToolProgress` | `tool_use_id`, `tool_name`, `content`, `update` | +| `TokenUsageUpdate` | Token-usage fields | +| `WorkingStateChanged` | `state` | +| `PermissionResolved` | `request_id`, `tool_use_ids`, `selected_option` | +| `SettingsUpdated` | `settings` | +| `SessionTitleUpdated` | `title` | +| `SessionWorkingDirectoryChanged` | `cwd` | +| `McpStatusChanged` | `servers`, `summary` | +| `McpAuthRequired` | `server_name`, `auth_url`, `message`, `state` | +| `McpAuthCompleted` | `server_name`, `outcome`, `message` | + +Unknown high-level events are ignored. Use `session.on_notification()` when +the application needs raw notifications. + +### Message model + +```python +from droid_sdk import AssistantMessage, ConversationMessage, UserMessage + +completed: list[ConversationMessage] = [] + +async with session.stream("Explain the failing test.") as stream: + async for event in stream: + if isinstance(event, (UserMessage, AssistantMessage)): + completed.append(event) + save(event) +``` + +`ConversationMessage` defines the fields shared by user and assistant +messages: + +| Field | Type | Meaning | +| --- | --- | --- | +| `id` | `str` | Stable message ID | +| `content` | `tuple[ContentBlock, ...]` | Ordered canonical content | +| `text` | `str` | Visible text blocks joined in order | +| `parent_id` | `str \| None` | Parent message, when present | +| `created_at` | `datetime` | Timezone-aware creation time | +| `updated_at` | `datetime` | Timezone-aware update time | + +`ContentBlock` is a typed union for text, thinking, tool use, tool result, +redacted thinking, images, and documents. Narrow blocks with `isinstance()`. + +```python +ContentBlock = ( + TextBlock + | ThinkingBlock + | RedactedThinkingBlock + | ToolUseBlock + | ToolResultBlock + | ImageBlock + | DocumentBlock +) +``` + +| Type | Fields | +| --- | --- | +| `TextBlock` | `id`, `text` | +| `ThinkingBlock` | `id`, `thinking`, `signature`, `signature_provider` | +| `ThinkingBlock` | `duration` | +| `RedactedThinkingBlock` | `id`, `data` | +| `ToolUseBlock` | `id`, `name`, `input`, `thought_signature` | +| `ToolResultBlock` | `id`, `tool_use_id`, `content`, `is_error` | +| `ImageBlock` | `id`, `source`, `generated` | +| `DocumentBlock` | `id`, `source` | + +`Message` is `StreamMessage[T]` without `RunResult[T]`. Partial events are not +messages. + +`TextDelta.message_id` and `block_index` identify the assistant content block +that eventually appears in `AssistantMessage.content`. +`ToolCall.tool_use_id` matches the corresponding `ToolUseBlock.id`. + +A complete message can repeat text already delivered through `TextDelta`. +Use deltas for live rendering and complete messages for persistence. Do not +concatenate both. + +`stream.result.messages` is the ordered tuple of complete `Message` values +emitted before the result. It excludes the result and partial events. + +### Read the result + +The terminal `RunResult` is yielded by the iterator and cached on the stream: + +```python +from droid_sdk import RunResult + +async with session.stream("Run the tests.") as stream: + async for message in stream: + if isinstance(message, RunResult): + print(message.subtype) + +result = stream.result +if result.success: + print(result.text) +``` + +Reading `stream.result` before completion raises `StreamIncompleteError`. + +### Result types + +`RunResult[T]` has the same terminal states as the TypeScript SDK: + +```python +RunResult[T] = RunSuccess[T] | RunInterrupted[T] | RunFailure[T] +``` + +| Type | Subtype | `success` | `interrupted` | +| --- | --- | --- | --- | +| `RunSuccess[T]` | `success` | `True` | `False` | +| `RunInterrupted[T]` | `interrupted` | `False` | `True` | +| `RunFailure[T]` | `error_during_execution` | `False` | `False` | +| `RunFailure[T]` | `error_structured_output` | `False` | `False` | + +| Field | Type | Meaning | +| --- | --- | --- | +| `subtype` | `str` | Terminal state | +| `text` | `str` | Final committed assistant text, with delta fallback | +| `messages` | `tuple[Message, ...]` | Complete messages from the turn | +| `usage` | `Usage \| None` | Per-turn token and credit usage | +| `duration` | `timedelta` | Wall-clock duration | +| `turn_count` | `int` | SDK turn count, currently `1` | +| `session_id` | `str` | Session that ran the turn | +| `output` | `T \| None` | Locally adapted structured output | +| `structured_output` | `FrozenJsonObject \| None` | Immutable raw structured output | +| `output_validation_error` | `ValidationError \| None` | Pydantic failure | +| `structured_output_error` | `StructuredOutputError \| None` | Droid failure | +| `error` | `ErrorEvent \| None` | Terminal execution error | + +All result variants retain partial output. `RunFailure` also exposes `error` +and the server's `structured_output_error` when available. A successful turn +may have no structured output. + +`RunResult` does not define truthiness. Check `success` or `subtype`. + +### Token and context usage + +```python +if result.usage: + print(result.usage.input_tokens) + print(result.usage.output_tokens) + print(result.usage.cache_read_tokens) + print(result.usage.cache_creation_tokens) + print(result.usage.thinking_tokens) + print(result.usage.factory_credits) +``` + +`TokenUsageUpdate` contains cumulative committed session usage. Context +occupancy is separate: + +```python +context = await session.context() +print(context.used, context.remaining, context.limit, context.accuracy) +``` + +`ContextUsage.updated_at` records when Droid measured the value. + +| Type | Fields | +| --- | --- | +| `Usage` | `input_tokens`, `output_tokens`, `cache_creation_tokens` | +| `Usage` | `cache_read_tokens`, `thinking_tokens`, `factory_credits` | +| `ContextUsage` | `used`, `remaining`, `limit`, `accuracy`, `updated_at` | +| `ToolProgressUpdate` | `type`, `tool_name`, `status`, `details`, `text` | +| `ToolProgressUpdate` | `error`, `timestamp`, `parameters`, `value_snippet` | +| `ToolProgressUpdate` | `terminal_id`, `full_output`, `subagent_session_id` | + +`ToolProgressUpdate.type` is `"tool_call"`, `"tool_result"`, `"error"`, +`"status"`, or `"message"`. + +### Failures and exceptions + +```python +async with session.stream("Run the tests.") as stream: + async for _ in stream: + pass + +result = stream.result +if result.subtype == "interrupted": + print("The turn was interrupted.") +elif result.subtype in ("error_during_execution", "error_structured_output"): + print(result.error.message if result.error else result.subtype) +``` + +Setup, connection, process, protocol, and timeout failures raise +`DroidError` subclasses. Python programming errors use normal built-in +exceptions. `asyncio.CancelledError` is never wrapped. + +### Concurrency + +A session may have one active stream. Starting another raises +`SessionBusyError`. + +Different sessions may run concurrently. + +### Timeout + +```python +async with session.stream("Perform a long review.", timeout=60) as stream: + async for event in stream: + handle(event) +``` + +`timeout` is a Python spelling for the TypeScript per-turn abort signal. On +expiry, the SDK interrupts the turn and raises `RunTimeoutError`. + +### Interrupt a turn + +Another task may stop active work: + +```python +await session.interrupt() +``` + +The active stream yields an interrupted result if its consumer remains +attached. The session stays open. + +### Cancellation and early exit + +Cancelling the task running a turn sends a best-effort interrupt, releases the +subscription, then re-raises `asyncio.CancelledError`. + +Use the stream context manager when iteration may stop early: + +```python +async with session.stream("Inspect every test.") as stream: + async for event in stream: + if should_stop(event): + break +``` + +Context exit interrupts unfinished work. A bare async iterator cannot +guarantee immediate cleanup on `break`. +`await stream.aclose()` explicitly interrupts and detaches an unfinished +stream; it is idempotent after release. + +## Inputs and outputs + +### Images and files + +Message options mirror TypeScript's `images` and `files` fields: + +```python +result = await run( + "Compare these files.", + images=[Image.from_path("screenshot.png")], + files=[ + Document.from_path("report.pdf"), + Document.from_text(source, name="auth.py"), + ], +) +``` + +```python +from droid_sdk import Document, Image + +result = await run( + "Review these inputs.", + images=[Image.from_bytes(image_bytes, media_type="image/png")], + files=[Document.from_text(report, name="report.md")], +) +``` + +Path constructors are Python conveniences that produce the same base64 image, +text-document, or base64-document sources accepted by TypeScript. Supported +image types are PNG, JPEG, GIF, and WebP. Invalid local input raises +`InvalidAttachmentError` before the turn starts. Image URLs are unsupported. +`MAX_ATTACHMENT_BYTES` is `5 * 1024 * 1024`; `MAX_PDF_ATTACHMENT_BYTES` is +`3 * 1024 * 1024`. `ImageMediaType` is the literal union `"image/jpeg"`, +`"image/png"`, `"image/gif"`, and `"image/webp"`. + +### Input schemas + +| Type | Fields | +| --- | --- | +| `Image` | `source: Base64ImageSource` | +| `Base64ImageSource` | `data`, `media_type` | +| `Document` | `source: TextDocumentSource \| PdfDocumentSource` | +| `TextDocumentSource` | `data`, `name`, `mime` | +| `PdfDocumentSource` | `data`, `parsed_data`, `name`, `path` | + +| Constructor | Returns | +| --- | --- | +| `Image.from_path(path)` | `Image` | +| `Image.from_bytes(data, media_type=...)` | `Image` | +| `Document.from_path(path)` | `Document` | +| `Document.from_text(text, name=..., mime=...)` | `Document` | +| `Document.from_bytes(data, name=...)` | `Document` | + +`images` accepts `Sequence[Image]`. `files` accepts `Sequence[Document]`. +Wire payloads use canonical `mediaType` fields. The high-level `mime` hint on +text documents is not forwarded as an extra protocol field. + +### Return a Pydantic model + +```python +from typing import Literal + +from pydantic import BaseModel + +from droid_sdk import run + + +class Finding(BaseModel): + severity: Literal["low", "medium", "high"] + message: str + + +class Review(BaseModel): + summary: str + findings: list[Finding] + + +result = await run( + "Review the authentication code.", + output=Review, +) + +if result.output is not None: + print(result.output.summary) +elif result.output_validation_error is not None: + print(result.output_validation_error) +``` + +`output` accepts a `BaseModel` subclass, not an arbitrary class. Unsupported +types raise `TypeError` before the turn starts. With `output=Review`, the +return type is `RunResult[Review]`. + +The adapter validates raw structured output when present. Missing or +Pydantic-invalid output leaves `output` as `None` and populates +`output_validation_error`; it does not change Droid's terminal subtype. +A successful turn can therefore have `output is None`. + +### Use raw JSON Schema + +```python +from droid_sdk import JsonObject, JsonSchema, RunResult, run + +schema = JsonSchema( + { + "type": "object", + "properties": {"summary": {"type": "string"}}, + "required": ["summary"], + } +) + +result: RunResult[JsonObject] = await run( + "Summarize the repository.", + output=schema, +) + +if result.output is not None: + print(result.output["summary"]) +``` + +`JsonSchema` accepts an object-shaped schema. Droid reports unsupported or +invalid schemas through the normal result subtype; the SDK does not invent a +separate local terminal state. + +### Output contract + +| `output` argument | Return type | +| --- | --- | +| Omitted or `None` | `RunResult[None]` | +| `type[BaseModel]` | `RunResult[Model]` | +| `JsonSchema` | `RunResult[JsonObject]` | + +`JsonSchema.schema` is `FrozenJsonObject`. Input mappings are validated as +finite JSON and recursively frozen. Raw schema output remains `JsonObject`. + +```python +JsonValue = ( + bool + | int + | float + | str + | None + | list["JsonValue"] + | dict[str, "JsonValue"] +) +JsonObject = dict[str, JsonValue] +FrozenJsonValue = ( + bool + | int + | float + | str + | None + | tuple["FrozenJsonValue", ...] + | Mapping[str, "FrozenJsonValue"] +) +FrozenJsonObject = Mapping[str, FrozenJsonValue] +``` + +Pydantic adaptation errors use `output_validation_error`. Droid's own +structured-output errors use `structured_output_error`. Neither field changes +the terminal subtype chosen by Droid. + +## Permissions and user input + +### Autonomy + +Autonomy controls which actions require approval in Auto mode: + +| Level | Behavior | +| --- | --- | +| `Autonomy.OFF` | Ask before every action | +| `Autonomy.LOW` | Allow edits and read-only commands | +| `Autonomy.MEDIUM` | Allow reversible commands | +| `Autonomy.HIGH` | Allow commands without approval | + +Configure it through `SessionConfig`: + +```python +config = SessionConfig(autonomy=Autonomy.LOW) +``` + +Autonomy does not select Auto or Spec mode. `Mode` controls that. + +### Handle permission requests + +```python +from droid_sdk import ( + InteractionHandlers, + PermissionRequest, + PermissionResponse, + Session, + ToolConfirmationOutcome, +) +from droid_sdk.permissions import CreateFile + + +def approve(request: PermissionRequest) -> PermissionResponse: + if request.actions and all( + isinstance(action, CreateFile) for action in request.actions + ): + return request.respond(ToolConfirmationOutcome.PROCEED_ONCE) + return request.respond(ToolConfirmationOutcome.CANCEL) + + +session = Session( + interactions=InteractionHandlers(on_permission=approve), +) +``` + +`request.options` is authoritative. `respond()` accepts only an offered +`ToolConfirmationOutcome` and optional `comment` or `edited_spec_content`. +This preserves every TypeScript outcome, including exact-path persistence, +auto-run levels, MCP persistence, edited plans, and new-session handoff. + +An absent handler, an invalid response, or a handler exception cancels the +request. Handler failures appear as `ErrorEvent` values; they do not raise +through the active stream. + +### Answer questions from Droid + +```python +from droid_sdk import QuestionRequest, QuestionResponse + + +def answer(request: QuestionRequest) -> QuestionResponse: + answers = [ + question.answer(question.options[0] if question.options else "none") + for question in request.questions + ] + return request.submit(answers) +``` + +Cancel the questionnaire: + +```python +return request.cancel() +``` + +Question helpers copy the required question index and text. Answers remain +strings, matching the TypeScript wire contract. Without a handler, or when a +handler fails or returns an invalid shape, the questionnaire is cancelled and +the stream receives an `ErrorEvent`. + +`question.answer(value)` answers one value. +`question.answer_multiple(values)` joins multi-select values with `", "` to +produce the wire-compatible string. + +Handlers run inside the active turn. Use async handlers for I/O, and do not +start another turn on the same session from a handler. + +### Interaction contracts + +```python +PermissionHandler = Callable[ + [PermissionRequest], + PermissionResponse | Awaitable[PermissionResponse], +] +QuestionHandler = Callable[ + [QuestionRequest], + QuestionResponse | Awaitable[QuestionResponse], +] +``` + +| Type | Fields | +| --- | --- | +| `InteractionHandlers` | `on_permission`, `on_question` | +| `PermissionRequest` | `actions`, `options` | +| `PermissionRequest` | `associated_session_ids` | +| `PermissionOption` | `label`, `value` | +| `PermissionResponse` | `selected_option`, `comment`, `edited_spec_content` | +| `QuestionRequest` | `tool_call_id`, `questions` | +| `Question` | `index`, `topic`, `question`, `options`, `multi_select` | +| `QuestionAnswer` | `index`, `question`, `answer` | +| `QuestionResponse` | `cancelled`, `answers` | + +`PermissionAction` is a discriminated union: + +```python +PermissionAction = ( + EditAction + | ExecuteAction + | CreateFile + | AskUserAction + | ExitSpecModeAction + | ApplyPatchAction + | McpToolAction + | SandboxViolationAction + | DroidShieldViolationAction +) +``` + +Every action includes its `tool_use`, confirmation type, and typed details: + +| Type | Detail fields | +| --- | --- | +| `EditAction` | `file_path`, `file_name`, `old_content`, `new_content` | +| `ExecuteAction` | `full_command`, `command`, `extracted_commands` | +| `ExecuteAction` | `impact_level`, `risk_level_reason` | +| `CreateFile` | `file_path`, `file_name`, `content` | +| `AskUserAction` | `questionnaire`, `questions`, `parse_error` | +| `ExitSpecModeAction` | `plan`, `title` | +| `ApplyPatchAction` | `file_path`, `file_name`, `patch_content` | +| `ApplyPatchAction` | `old_content`, `new_content`, `files` | +| `ApplyPatchFile` | `file_path`, `file_name`, `operation`, `move_to` | +| `ApplyPatchFile` | `old_content`, `new_content` | +| `McpToolAction` | `tool_name`, `server_name`, `actual_tool_name` | +| `McpToolAction` | `impact_level` | +| `SandboxViolationAction` | `violating_tool_name`, `target`, `operation` | +| `SandboxViolationAction` | `violation_type`, `reason`, `violation_reason` | +| `SandboxViolationAction` | `is_org_deny` | +| `DroidShieldViolationAction` | `command`, `reason` | + +`AskUserParseError(message: str, line: int | None = None)` records malformed +questionnaire details. `ApplyPatchFile` requires `file_path`, `file_name`, and +`operation` (`"create"`, `"update"`, or `"delete"`); `move_to`, +`old_content`, and `new_content` default to `None`. + +`ToolConfirmationOutcome` defines: + +| Outcome | Meaning | +| --- | --- | +| `PROCEED_ONCE` | Approve this request | +| `PROCEED_ALWAYS` | Persist the offered rule | +| `PROCEED_ALWAYS_EXACT_PATH` | Persist the exact file path | +| `PROCEED_AUTO_RUN` | Continue with automatic approvals | +| `PROCEED_AUTO_RUN_LOW` | Continue at low autonomy | +| `PROCEED_AUTO_RUN_MEDIUM` | Continue at medium autonomy | +| `PROCEED_AUTO_RUN_HIGH` | Continue at high autonomy | +| `PROCEED_NEW_SESSION` | Continue in a new session | +| `PROCEED_NEW_SESSION_LOW` | New session at low autonomy | +| `PROCEED_NEW_SESSION_MEDIUM` | New session at medium autonomy | +| `PROCEED_NEW_SESSION_HIGH` | New session at high autonomy | +| `PROCEED_EDIT` | Submit edited plan content | +| `PROCEED_ALWAYS_TOOLS` | Persist approval for MCP tools | +| `PROCEED_ALWAYS_SERVER` | Persist approval for an MCP server | +| `CANCEL` | Reject the request | + +Only outcomes present in `PermissionRequest.options` are valid. + +### Control native tools + +```python +config = SessionConfig( + additional_tools={"CustomTool"}, + enabled_tools={"Read"}, + disabled_tools={"Execute", "Edit"}, + restrict_tools={"Read", "Grep"}, +) +``` + +The four sets preserve TypeScript semantics: + +- `additional_tools` adds IDs to the catalog. +- `enabled_tools` enables otherwise available tools. +- `disabled_tools` removes tools. +- `restrict_tools` is a restrictive allowlist and never elevates permission. + +```python +for tool in await session.list_tools(model="model-id", mode=Mode.AUTO): + print(tool.id, tool.allowed) +``` + +`update_settings()` accepts the same override fields for later turns. +The four override parameters accept `set[str]`, `frozenset[str]`, or `None`. + +`list_tools()` returns `list[ToolInfo]`. + +| Type | Fields | +| --- | --- | +| `ToolInfo` | `id`, `display_name`, `description`, `category` | +| `ToolInfo` | `default_allowed`, `allowed` | +| `ListToolsOptions` | `model`, `mode`, `autonomy`, `spec_model` | +| `ListToolsOptions` | `additional_tools`, `enabled_tools`, `disabled_tools` | +| `ListToolsOptions` | `restrict_tools`, `skip_permissions_unsafe` | + +## Tools and extensions + +| Extension | Use it for | +| --- | --- | +| Skills | Reusable instructions and supporting files | +| In-process MCP tools | Python functions exposed to Droid | +| External MCP servers | Tools from another process or service | +| Hooks | Commands run at Droid lifecycle points | + +### Skills + +```python +skills = await session.list_skills() +for skill in skills.skills: + print(skill.name, skill.enabled) +``` + +`skills.project_available` preserves the TypeScript result metadata. + +Enable or disable a skill: + +```python +await session.enable_skill("review", scope="project") +await session.disable_skill("legacy", scope="user") +``` + +Skills may come from project, personal, built-in, or automation settings. + +#### Skill schemas + +| Type | Fields | +| --- | --- | +| `SkillsResult` | `skills`, `project_available` | +| `SkillInfo` | `name`, `description`, `location`, `file_path`, `enabled` | +| `SkillInfo` | `user_invocable`, `version`, `content`, `resources` | +| `SkillInfo` | `disabled_by` | +| `SkillResource` | `name`, `path`, `type` | +| `SkillMutationResult` | `success` | + +`scope` is `"user"` or `"project"`. `SkillResource.type` is `"reference"` or +`"asset"`. `SkillInfo.location` is `"project"`, `"personal"`, `"builtin"`, or +`"automation"`. + +### In-process MCP tools + +Use `@tool` to expose an annotated Python function: + +```python +from droid_sdk.mcp import create_sdk_mcp_server, tool + + +@tool("lookup_owner", "Return the owner of a repository file.") +async def lookup_owner(path: str) -> str: + return f"Owner for {path}: platform-team" + + +server = create_sdk_mcp_server( + name="review-tools", + tools=[lookup_owner], + version="1.0.0", +) +config = SessionConfig(mcp_servers=[server]) +``` + +The decorator derives JSON Schema from type annotations. Invalid input is +returned to Droid as a tool error and is not passed to the function. + +Tool functions may be synchronous or asynchronous. They may return text or a +typed `ToolResponse`. + +The SDK starts an authenticated loopback server and closes it with the +session. Attach in-process servers again when resuming. + +#### In-process MCP schemas + +| Type | Fields | +| --- | --- | +| `DroidTool` | `name`, `description`, `input_schema`, `handler`, `output_schema` | +| `SdkMcpServer` | `name`, `version`, `tools` | +| `ToolResponse` | `content`, `is_error`, `structured_content` | + +`tool(name, description)` is a decorator. +`tool(name, description, function)` is the equivalent direct-call overload. +It accepts synchronous or asynchronous functions. Parameters and return +annotations form the input and output schemas. Object-shaped typed returns +are validated at invocation time, returned as structured content, and +advertised through the MCP `outputSchema` field. + +`create_sdk_mcp_server(name, tools, version="1.0.0")` returns `SdkMcpServer`. +`SdkMcpServer.config` is the active `HttpMcpServerConfig` or `None`; +`await server.start()` returns that config, and `await server.close()` stops +the server. Sessions normally own these calls. + +### External MCP servers + +```python +from droid_sdk.mcp import HttpMcpServerConfig, StdioMcpServerConfig + +config = SessionConfig( + mcp_servers=[ + HttpMcpServerConfig(name="docs", url="https://example.com/mcp"), + StdioMcpServerConfig( + name="search", + command="python", + args=["-m", "search_server"], + ), + ], +) +``` + +HTTP, SSE, and stdio transports are supported. HTTP and SSE configurations +support headers and OAuth settings. + +Inspect connected servers and tools: + +```python +servers = await session.list_mcp_servers() +tools = await session.list_mcp_tools() + +print(servers.summary) +for server in servers.servers: + print(server.name, server.status) +``` + +Session methods can add, remove, enable, disable, and authenticate external +servers. Configuration mutations affect the user's Droid settings. Servers +passed through `SessionConfig` are session-scoped. + +| Session MCP method | Signature | +| --- | --- | +| `add_mcp_server` | `(config) -> McpMutationResult` | +| `remove_mcp_server` | `(name: str) -> McpMutationResult` | +| `enable_mcp_server` / `disable_mcp_server` | `(name: str) -> McpMutationResult` | +| `enable_mcp_tool` / `disable_mcp_tool` | `(server_name: str, tool_name: str) -> McpMutationResult` | +| `authenticate_mcp_server` | `(name: str) -> McpMutationResult` | +| `cancel_mcp_auth` / `clear_mcp_auth` | `(name: str) -> McpMutationResult` | +| `submit_mcp_auth_code` | `(name: str, *, code: str, state: str) -> McpMutationResult` | +| `submit_mcp_auth_error` | `(name: str, *, error: str, state: str, error_description: str \| None = None) -> McpMutationResult` | + +#### External MCP schemas + +```python +McpServerConfig = ( + StdioMcpServerConfig + | HttpMcpServerConfig + | SseMcpServerConfig + | SdkMcpServer +) +``` + +| Type | Fields | +| --- | --- | +| `StdioMcpServerConfig` | `name`, `command`, `args`, `env` | +| `HttpMcpServerConfig` | `name`, `url`, `headers`, `oauth` | +| `SseMcpServerConfig` | `name`, `url`, `headers`, `oauth` | +| `HttpHeader` | `name`, `value` | +| `McpOAuthOptions` | `scopes`, `resource`, `authorization_server_issuer` | +| `McpOAuthOptions` | `client_metadata_url`, `client_id`, `client_secret` | +| `McpOAuthOptions` | `callback_port`, `token_endpoint_auth_method` | +| `McpServersResult` | `servers`, `summary` | +| `McpServerStatusInfo` | `name`, `status`, `source`, `is_managed`, `error` | +| `McpServerStatusInfo` | `tool_count`, `server_type`, `has_auth_tokens` | +| `McpServerStatusInfo` | `requires_auth`, `pending_auth_url` | +| `McpServerStatusInfo` | `pending_auth_message`, `pending_auth_state` | +| `McpStatusSummary` | `total`, `connected`, `connecting` | +| `McpStatusSummary` | `failed`, `disabled` | +| `McpStatusSummary` | `config_error` | +| `McpConfigError` | `path`, `message` | +| `McpToolInfo` | `server_name`, `name`, `description`, `is_enabled` | +| `McpToolInfo` | `is_read_only`, `input_schema` | +| `McpToolInputSchema` | `type`, `properties`, `required` | +| `McpMutationResult` | `success` | + +`oauth` accepts `McpOAuthOptions` or `False`. + +| Method | Returns | +| --- | --- | +| `list_mcp_servers()` | `McpServersResult` | +| `list_mcp_tools()` | `list[McpToolInfo]` | +| `add_mcp_server(...)` | `McpMutationResult` | +| `remove_mcp_server(...)` | `McpMutationResult` | +| `enable_mcp_server(...)` | `McpMutationResult` | +| `disable_mcp_server(...)` | `McpMutationResult` | +| `authenticate_mcp_server(...)` | `McpMutationResult` | + +Remove, enable, and disable mutate user-scoped MCP configuration only. These +methods do not accept a project-scope argument. + +### Hooks + +Hooks remain configured in `.factory/hooks.json`. Hook execution appears as +`HookExecution` values in the run stream. + +The Python SDK does not define a second programmatic hook system. +`HookExecution.status` is `"started"`, `"completed"`, or `"error"`. +An empty or missing `hookResults` list does not synthesize a phantom terminal +hook event. + +## Session lifecycle + +Fork, compact, and rewind create successor sessions. They return an opened +`Session` that owns the existing Droid connection. + +### Fork + +```python +fork = await session.fork( + title="Alternative approach", + tags=[SessionTag(name="experiment")], +) + +async with fork: + async with fork.stream("Try the other strategy.") as stream: + async for _ in stream: + pass +``` + +### Compact + +```python +outcome = await session.compact( + instructions="Keep decisions and unresolved failures." +) + +async with outcome.session as compacted: + print(outcome.removed_count) +``` + +### Rewind + +```python +info = await session.rewind_info(message_id) + +outcome = await session.rewind( + message_id, + restore=info.available_files, + delete=info.created_files, + title="Before the failed change", +) + +async with outcome.session as rewound: + print(outcome.restored_count, outcome.deleted_count) + print(outcome.failed_restore_count, outcome.failed_delete_count) +``` + +`info.evicted_files` explains files that cannot be restored. + +### Lifecycle contracts + +| Method | Arguments | Returns | +| --- | --- | --- | +| `fork()` | `title`, `tags` | Opened `Session` | +| `compact()` | `instructions` | `CompactOutcome` | +| `rewind_info()` | `message_id` | `RewindInfo` | +| `rewind()` | `message_id`, `restore`, `delete`, `title` | `RewindOutcome` | + +| Type | Fields | +| --- | --- | +| `CompactOutcome` | `session`, `removed_count` | +| `RewindInfo` | `available_files`, `created_files`, `evicted_files` | +| `RewindFileSnapshot` | `file_path`, `content_hash`, `size` | +| `RewindFileCreation` | `file_path` | +| `RewindEvictedFile` | `file_path`, `reason` | +| `RewindOutcome` | `session`, `restored_count`, `deleted_count` | +| `RewindOutcome` | `failed_restore_count`, `failed_delete_count` | + +### Successor ownership + +After a successful replacement: + +- the returned successor owns the connection and runtime resources +- the source session becomes retired +- `id`, `cwd`, and `settings` remain readable on the source +- active methods on the source raise `SessionReplacedError` +- closing the source is a no-op + +Do not replace a session while it has an active turn. + +Only one replacement may run at a time. `open()` and another replacement +raise `SessionBusyError` while replacement is active. `close()` racing a +replacement waits; on success it closes the successor, and on rollback it +closes the source. + +Cancelling a replacement before handoff restores the source to open state. +If cancellation arrives after a successor is created, the SDK reloads the +source with its attached policies and retires the detached successor. If +source restoration fails, the SDK closes the connection rather than leaving +an ambiguous owner. + +## Modes + +### Spec mode + +Spec mode lets Droid inspect a codebase and propose a plan without changing +files. + +#### Enter Spec mode + +```python +await session.enter_spec( + model="model-id", + reasoning_effort=ReasoningEffort.HIGH, +) +``` + +Start directly in Spec mode with `SessionConfig(mode=Mode.SPEC)`. + +#### Leave without approving + +```python +await session.leave_spec() +``` + +This changes the mode only. It does not approve the plan or start +implementation. + +#### Approve a plan + +Plan approval arrives through the permission handler: + +```python +def approve(request: PermissionRequest) -> PermissionResponse: + if request.plan: + print(request.plan.text) + return request.respond(ToolConfirmationOutcome.PROCEED_ONCE) + return request.respond(ToolConfirmationOutcome.CANCEL) +``` + +Return any offered `PROCEED_NEW_SESSION*` outcome to hand implementation to a +new session. Return `PROCEED_EDIT` with `edited_spec_content` to revise the +plan. `CANCEL` ends the turn with an interrupted result. + +### Mode contract + +| API | Arguments | Returns | +| --- | --- | --- | +| `SessionConfig(mode=...)` | `Mode.AUTO` or `Mode.SPEC` | `SessionConfig` | +| `enter_spec()` | `model`, `reasoning_effort` | `UpdateSettingsResult` | +| `leave_spec()` | None | `UpdateSettingsResult` | + +Entering or leaving Spec mode only changes settings. Plan approval is an +`ExitSpecModeAction` permission request, and only an offered +`ToolConfirmationOutcome` is valid. + +## Operations + +### Observability + +```python +from droid_sdk import Runtime +from droid_sdk.observability import Observability + +runtime = Runtime( + observability=Observability(logger=logger, metrics=metrics), +) + +result = await run("Check repository status.", runtime=runtime) +``` + +Logger, metric, and trace-context sinks are synchronous and best-effort. Sink +failures never fail a Droid operation. + +Events exclude prompts, messages, thinking, tool inputs and results, file +contents, raw process output, stack traces, and credentials. + +#### Observability schemas + +| Type | Fields or methods | +| --- | --- | +| `Observability` | `logger`, `metrics`, `tracing` | +| `Logger` | `log(event: LogEvent) -> None` | +| `LogEvent` | `level`, `name`, `message`, `attributes`, `error` | +| `SerializedError` | `name`, `message`, `code` | +| `MetricSink` | `record(event: MetricEvent) -> None` | +| `MetricEvent` | `name`, `kind`, `value`, `unit`, `attributes` | +| `TraceContextProvider` | `inject(carrier: TraceContext) -> None` | +| `TraceContext` | `traceparent`, `tracestate` | + +`attributes` is `Mapping[str, str | int | float | bool | None]`. Log levels are +`"debug"`, `"info"`, `"warn"`, and `"error"`. Metric kinds are `"counter"` +and `"histogram"`. + +### Custom runtime + +`Runtime` holds process and transport configuration: + +```python +runtime = Runtime( + executable=Path("/opt/factory/bin/droid"), + args=["--flag"], + env={"EXAMPLE": "value"}, +) +``` + +A supplied transport must already be connected. It takes precedence over +process and API-key options, and the session closes it. Environment entries +extend the current process environment when the SDK starts Droid. + +#### Runtime schema + +| Field | Type | +| --- | --- | +| `executable` | `str \| Path \| None` | +| `args` | `Sequence[str]` | +| `env` | `Mapping[str, str]` | +| `transport` | `Transport \| None` | +| `observability` | `Observability \| None` | + +`Runtime.uses_supplied_transport` is `True` when `transport` is not `None`. + +### Low-level API + +Applications that own JSON-RPC or transport lifecycle may import: + +```python +from droid_sdk.low_level import DroidClient, ProcessTransport +``` + +The low-level package exposes protocol models and request methods. It does not +provide high-level ordering or cleanup guarantees. Prefer +`session.on_notification()` when an existing session needs raw notifications. + +| Type | Purpose | +| --- | --- | +| `DroidClient` | Typed JSON-RPC requests, callbacks, and notifications | +| `ProcessTransport` | Start and connect to a local Droid process | +| `Transport` | Async framed-message transport protocol | +| Protocol request models | Typed request parameters | +| Protocol response models | Success and failure envelopes | +| Protocol notification models | Raw session notifications | + +Low-level request and response models preserve protocol field names. The +high-level types documented above provide Python naming and lifecycle +guarantees. + +`droid_sdk.low_level.__all__` is the authoritative machine-readable API +index. It consists of the constants and runtime types shown above plus every +name in `droid_sdk.schemas.__all__`. This includes Mission wire schemas for +protocol compatibility; Mission and daemon APIs are not exposed at package +root. + +## API index + +### Root constants and supporting types + +| Export | Contract | +| --- | --- | +| `__version__` | Installed package version as `str` | +| `MAX_ATTACHMENT_BYTES` | General attachment limit, `5 * 1024 * 1024` | +| `MAX_PDF_ATTACHMENT_BYTES` | PDF limit, `3 * 1024 * 1024` | +| `ImageMediaType` | Supported image MIME literal union | +| `JsonValue`, `JsonObject` | Mutable JSON input/output aliases | +| `FrozenJsonValue`, `FrozenJsonObject` | Recursively immutable JSON aliases | +| `ApplyPatchFile` | Per-file patch details documented above | +| `AskUserParseError` | `message`, `line` | +| `SandboxSettings` | `enabled`, `mode` | +| `SessionSettingsUpdate` | Partial settings notification documented above | + +### Top-level functions + +| API | Returns | Purpose | +| --- | --- | --- | +| `run(prompt, **options)` | `RunResult[T]` | Run one turn | +| `list_sessions(**filters)` | `list[SavedSession]` | List saved sessions | + +| `run()` argument | Type | +| --- | --- | +| `prompt` | `str` | +| `cwd` | `str \| Path \| None` | +| `model` | `str \| None` | +| `reasoning_effort` | `ReasoningEffort \| None` | +| `images` | `Sequence[Image]` | +| `files` | `Sequence[Document]` | +| `output` | `type[BaseModel] \| JsonSchema \| None` | +| `timeout` | `float \| None` | +| `config` | `SessionConfig \| None` | +| `interactions` | `InteractionHandlers \| None` | +| `runtime` | `Runtime \| None` | +| `api_key` | `str \| None` | + +### `Session` + +| Member | Returns | +| --- | --- | +| `Session(...)` | Lazy `Session` | +| `Session.resume(id, ...)` | Lazy `Session` | +| `open()` | `None` | +| `close()` | `None` | +| `id` | `str` | +| `cwd` | `Path \| None` | +| `settings` | `SessionSettings` | +| `stream()` | `RunStream[T, E]` | +| `interrupt()` | `None` | +| `update_settings()` | `UpdateSettingsResult` | +| `rename()` | `None` | +| `on_notification()` | `Callable[[], None]` | +| `list_tools()` | `list[ToolInfo]` | +| `list_skills()` | `SkillsResult` | +| `enable_skill()` / `disable_skill()` | `SkillMutationResult` | +| `list_mcp_servers()` | `McpServersResult` | +| `list_mcp_tools()` | `list[McpToolInfo]` | +| MCP mutation methods | `McpMutationResult` | +| `context()` | `ContextUsage` | +| `fork()` | Opened `Session` | +| `compact()` | `CompactOutcome` | +| `rewind_info()` | `RewindInfo` | +| `rewind()` | `RewindOutcome` | +| `enter_spec()` / `leave_spec()` | `UpdateSettingsResult` | + +### `RunStream` + +| Member | Returns | +| --- | --- | +| Async iteration | `StreamMessage[T]` or `StreamEvent[T]` values | +| `result` | Cached `RunResult[T]` | +| `aclose()` | `None` | + +### Main enums + +| Enum | Values | +| --- | --- | +| `Mode` | `AUTO`, `SPEC` | +| `Autonomy` | `OFF`, `LOW`, `MEDIUM`, `HIGH` | +| `ReasoningEffort` | See supported values below | +| `ToolCategory` | `READ`, `EDIT`, `EXECUTE`, `OTHER` | +| `ToolConfirmationType` | `EDIT`, `EXECUTE`, `CREATE`, `ASK_USER` | +| `ToolConfirmationType` | `EXIT_SPEC_MODE`, `APPLY_PATCH`, `MCP_TOOL` | +| `ToolConfirmationType` | `SANDBOX_VIOLATION`, `DROID_SHIELD_VIOLATION` | +| `ToolConfirmationOutcome` | Permission outcomes offered by Droid | +| `WorkingState` | `IDLE`, `THINKING`, `STREAMING_ASSISTANT_MESSAGE` | +| `WorkingState` | `WAITING_FOR_TOOL_CONFIRMATION`, `EXECUTING_TOOL` | +| `WorkingState` | `COMPACTING_CONVERSATION` | +| `ContextAccuracy` | `EXACT`, `ESTIMATED` | +| `McpServerType` | `STDIO`, `HTTP`, `SSE` | +| `McpServerStatus` | `CONNECTING`, `CONNECTED`, `DISCONNECTED` | +| `McpServerStatus` | `FAILED`, `DISABLED` | +| `McpAuthOutcome` | `SUCCESS`, `CANCELLED`, `FAILED` | +| `OAuthTokenEndpointAuthMethod` | `NONE`, `CLIENT_SECRET_BASIC`, `CLIENT_SECRET_POST` | +| `SessionPlatform` | `SLACK`, `WEB`, `API`, `SESSIONS_API`, `JIRA`, `LINEAR` | +| `SessionPlatform` | `MICROSOFT_TEAMS`, `READINESS_REMEDIATION`, `READINESS_EVALUATION` | +| `SessionPlatform` | `AUTOMATION`, `WIKI_GENERATION`, `WIKI_CI_SETUP`, `TUI` | +| `SessionPlatform` | `DESKTOP`, `ACP`, `UNKNOWN` | +| `SandboxOperation` | `READ`, `WRITE`, `NETWORK`, `TOOL` | +| `SandboxViolationType` | `FILESYSTEM_READ`, `FILESYSTEM_WRITE`, `NETWORK`, `TOOL` | +| `SandboxViolationReason` | `DENY_LIST`, `NOT_ALLOWED` | +| `ErrorType` | `CONNECTION_ERROR`, `PROTOCOL_ERROR`, `SESSION_ERROR` | +| `ErrorType` | `TIMEOUT_ERROR`, `DROID_CLIENT_ERROR`, `PROCESS_EXIT_ERROR` | +| `ErrorType` | `ERROR` | + +`ReasoningEffort` defines `NONE`, `DYNAMIC`, `OFF`, `MINIMAL`, `LOW`, +`MEDIUM`, `HIGH`, `EXTRA_HIGH`, and `MAX`. Model and tool IDs remain strings. + +Additional root enum wire values are: + +```text +ToolCategory: read, edit, execute, other +ToolConfirmationType: edit, exec, create, ask_user, exit_spec_mode, + apply_patch, mcp_tool, sandbox_violation, droid_shield_violation +OAuthTokenEndpointAuthMethod: none, client_secret_basic, client_secret_post +SandboxOperation: read, write, network, tool +SandboxViolationType: filesystem-read, filesystem-write, network, tool +SandboxViolationReason: deny-list, not-allowed +SessionPlatform: slack, web, api, sessions_api, jira, linear, + microsoft-teams, readiness-remediation, readiness-evaluation, automation, + wiki-generation, wiki-ci-setup, tui, desktop, acp, unknown +``` + +### Exceptions + +All SDK-defined exceptions derive from `DroidError`. Python built-ins and +`asyncio.CancelledError` do not. + +| Exception | Meaning | +| --- | --- | +| `RunTimeoutError` | The turn exceeded its deadline | +| `StreamIncompleteError` | A stream result was read before completion | +| `InvalidAttachmentError` | A local attachment was invalid | +| `SessionNotOpenError` | An operation required an opened session | +| `SessionBusyError` | The session already had an active turn | +| `SessionClosedError` | The session was closed | +| `SessionReplacedError` | A successor retired the source session | +| `SessionReplacementError` | Successor load or source restore failed | +| `SessionNotFoundError` | A saved session ID was not found | +| `InvalidWorkingDirectoryError` | A working directory is unavailable | +| `DroidConnectionError` | The local connection failed | +| `DroidProcessError` | The Droid process exited unexpectedly | +| `DroidProtocolError` | Protocol negotiation or validation failed | + +`SessionError` is the compatibility base exported by `droid_sdk.errors`; it +is intentionally absent from the package root. Exception metadata is public: + +| Exception | Additional constructor fields | +| --- | --- | +| `RunTimeoutError(message, ...)` | `request_id`, `method`, `timeout_duration` | +| `SessionReplacedError(session_id, replacement_session_id)` | both session IDs | +| `SessionReplacementError(session_id, replacement_session_id, ...)` | both IDs, `rollback_error`, `rollback_failed` | +| `SessionNotFoundError(session_id)` | `session_id` | +| `InvalidWorkingDirectoryError(cwd, message=None)` | `cwd` | +| `DroidConnectionError(message, ...)` | `cwd`, `exec_path` | +| `DroidProcessError(message, ...)` | `exit_code`, `signal` | +| `DroidProtocolError(message, ...)` | `code`, `data` | + +## Runnable examples + +Run commands from the repository root: + +| Example | Command | Expected result | +| --- | --- | --- | +| Attachments | `uv run python examples/attachments.py --run` | Live image, text, and PDF turn | +| Interaction helpers | `uv run python examples/interaction_helpers.py` | Offline typed responses | +| Interactions | `uv run python examples/interactions.py --run` | Live permission/question turn | +| Interactive session | `uv run python examples/interactive_session.py --run` | Two live turns sharing history | +| Saved sessions | `uv run python examples/list_saved_sessions.py` | Local saved-session count | +| Low-level session | `uv run python examples/low_level_session.py [--droid PATH] [--cwd PATH]` | Initialize and list tools | +| Observability | `uv run python examples/observability.py` | Offline isolated sink counts | +| One-shot run | `uv run python examples/one_shot.py --run` | Live one-turn result | +| Resume | `uv run python examples/resume_session.py --session-id ID` | Live resumed turn | +| SDK MCP | `uv run python examples/sdk_mcp.py --run` | Live in-process MCP result | +| Session operations | `uv run python examples/session_operations.py --run` | Live settings, discovery, fork, and compact | +| Structured output | `uv run python examples/structured_output_model.py --run` | Live validated model output | + +Omitting `--run` from the seven flagged examples performs their offline +self-test instead of a model call. Live examples require an authenticated +local Droid CLI or `FACTORY_API_KEY`; every model call uses a finite timeout. + +## Known limitations + +- The high-level API runs local Droid subprocess sessions only. +- The API is asyncio-only. +- Hooks are configured through Droid files, not Python callbacks. +- Image URLs are not supported by the local runtime. +- One session can run one turn at a time. diff --git a/examples/attachments.py b/examples/attachments.py new file mode 100644 index 0000000..319a7a0 --- /dev/null +++ b/examples/attachments.py @@ -0,0 +1,96 @@ +"""Load local attachments without starting Droid.""" + +from __future__ import annotations + +import argparse +import asyncio +import base64 +import tempfile +from pathlib import Path + +from droid_sdk import ( + Document, + Image, + PdfDocumentSource, + TextDocumentSource, + run, +) + + +def minimal_pdf() -> bytes: + content = b"BT /F1 12 Tf 72 720 Td (Offline PDF example.) Tj ET" + objects = ( + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + ( + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] " + b"/Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>" + ), + b"<< /Length " + + str(len(content)).encode() + + b" >>\nstream\n" + + content + + b"\nendstream", + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", + ) + data = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n") + offsets = [0] + for number, value in enumerate(objects, start=1): + offsets.append(len(data)) + data.extend(f"{number} 0 obj\n".encode()) + data.extend(value) + data.extend(b"\nendobj\n") + xref = len(data) + data.extend(f"xref\n0 {len(objects) + 1}\n".encode()) + data.extend(b"0000000000 65535 f \n") + for offset in offsets[1:]: + data.extend(f"{offset:010} 00000 n \n".encode()) + data.extend( + ( + f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\n" + f"startxref\n{xref}\n%%EOF\n" + ).encode() + ) + return bytes(data) + + +async def main(run_turn: bool = False) -> None: + png = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAQ0lEQVR4AcXB" + "AQEAAAiDMKR/5xuD7QYjJDGJSUxiEpOYxCQmMYlJTGISk5jEJCYxiUlMYhKT" + "mMQkJjGJSUxiEpOYxB4w4wI+9B/igQAAAABJRU5ErkJggg==" + ) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + text_path = root / "notes.txt" + pdf_path = root / "report.pdf" + image_path = root / "pixel.png" + text_path.write_text("Offline attachment example.\n", encoding="utf-8") + pdf_path.write_bytes(minimal_pdf()) + image_path.write_bytes(png) + + image = Image.from_path(image_path) + text = Document.from_path(text_path) + pdf = Document.from_path(pdf_path) + + assert isinstance(text.source, TextDocumentSource) + assert isinstance(pdf.source, PdfDocumentSource) + if run_turn: + result = await run( + "Describe the attached red square and summarize both files.", + images=[image], + files=[text, pdf], + timeout=60, + ) + assert result.success, result.error + assert result.text + print(result.text) + print(f"image: {image.source.media_type}") + print(f"text: {text.source.name} ({text.source.mime})") + print(f"pdf: {pdf.source.name} ({len(pdf.source.data)} base64 chars)") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--run", action="store_true") + asyncio.run(main(parser.parse_args().run)) diff --git a/examples/interaction_helpers.py b/examples/interaction_helpers.py new file mode 100644 index 0000000..750e5d6 --- /dev/null +++ b/examples/interaction_helpers.py @@ -0,0 +1,62 @@ +"""Exercise interaction response helpers without starting Droid.""" + +from droid_sdk import ( + PermissionOption, + PermissionRequest, + Question, + QuestionRequest, + ToolConfirmationOutcome, +) + + +def main() -> None: + permission = PermissionRequest( + actions=(), + options=( + PermissionOption( + label="Proceed once", + value=ToolConfirmationOutcome.PROCEED_ONCE, + ), + PermissionOption( + label="Cancel", + value=ToolConfirmationOutcome.CANCEL, + ), + ), + ) + response = permission.respond( + ToolConfirmationOutcome.PROCEED_ONCE, + comment="Approved by the offline example.", + ) + + single = Question( + index=1, + topic="Language", + question="Which language?", + options=("Python", "TypeScript"), + ) + multiple = Question( + index=2, + topic="Checks", + question="Which checks?", + options=("tests", "lint", "types"), + multi_select=True, + ) + questionnaire = QuestionRequest( + tool_call_id="offline-tool-call", + questions=(single, multiple), + ) + answers = questionnaire.submit( + ( + single.answer("Python"), + multiple.answer_multiple(("tests", "types")), + ) + ) + cancelled = questionnaire.cancel() + + print(response) + print(answers) + print(cancelled) + + +if __name__ == "__main__": + main() diff --git a/examples/interactions.py b/examples/interactions.py new file mode 100644 index 0000000..78be06e --- /dev/null +++ b/examples/interactions.py @@ -0,0 +1,53 @@ +"""Permission and question handlers with safe cancellation defaults.""" + +from __future__ import annotations + +import argparse +import asyncio + +from droid_sdk import ( + InteractionHandlers, + PermissionRequest, + PermissionResponse, + QuestionRequest, + QuestionResponse, + Session, + ToolConfirmationOutcome, +) + + +def permission(request: PermissionRequest) -> PermissionResponse: + return request.respond(ToolConfirmationOutcome.CANCEL) + + +async def question(request: QuestionRequest) -> QuestionResponse: + answers = [ + item.answer(item.options[0] if item.options else "none") + for item in request.questions + ] + return request.submit(answers) + + +async def main(run_turn: bool = False) -> None: + handlers = InteractionHandlers( + on_permission=permission, + on_question=question, + ) + if not run_turn: + assert handlers.on_permission is permission + print("self-test: interaction handlers ready") + return + async with Session(interactions=handlers) as session: + async with session.stream( + "Ask one multiple-choice question, then stop.", + timeout=60, + ) as stream: + async for _ in stream: + pass + print(stream.result.subtype) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--run", action="store_true") + asyncio.run(main(parser.parse_args().run)) diff --git a/examples/interactive_session.py b/examples/interactive_session.py index eed251c..ef39ac6 100644 --- a/examples/interactive_session.py +++ b/examples/interactive_session.py @@ -1,433 +1,42 @@ -#!/usr/bin/env python3 -"""Interactive session example for the Factory Droid Python SDK. - -Demonstrates the SDK's full capabilities by rendering ALL intermediate activity -from a Droid session with ANSI-colored output: - - - Assistant text deltas (streamed char-by-char) - - Thinking text deltas (gray, with [Thinking] prefix) - - Tool calls (yellow: tool name + input summary) - - Tool results (green for success, red for errors) - - Tool progress updates - - Token usage updates - - Error events (red) - - Permission requests (auto-approve or prompt user) - - Turn completion with final token stats - - MCP status changes - - Session title updates - -Usage: - python examples/interactive_session.py [--cwd /path/to/project] - -Requires the ``droid`` CLI to be installed and available on PATH -(or at ``~/.local/bin/droid``). - -Simpler alternative using query(): - - import asyncio - from droid_sdk import query, AssistantTextDelta, TurnComplete - - async def main() -> None: - async for msg in query("Hello!", cwd="."): - if isinstance(msg, AssistantTextDelta): - print(msg.text, end="", flush=True) - elif isinstance(msg, TurnComplete): - print() - - asyncio.run(main()) -""" +"""Multi-turn complete and partial streaming with public v5 APIs.""" from __future__ import annotations import argparse import asyncio -import json -import os -import sys - -from droid_sdk import ( - AssistantTextDelta, - ConnectionError, - DroidClient, - DroidClientError, - ErrorEvent, - ProcessExitError, - ProcessTransport, - StreamMessage, - ThinkingTextDelta, - TimeoutError, - TokenUsageUpdate, - ToolConfirmationOutcome, - ToolProgress, - ToolResult, - ToolUse, - TurnComplete, - WorkingStateChanged, -) - -# --------------------------------------------------------------------------- -# ANSI color helpers -# --------------------------------------------------------------------------- - -# Standard ANSI escape codes -_RESET = "\033[0m" -_BOLD = "\033[1m" -_DIM = "\033[2m" -_RED = "\033[31m" -_GREEN = "\033[32m" -_YELLOW = "\033[33m" -_BLUE = "\033[34m" -_MAGENTA = "\033[35m" -_CYAN = "\033[36m" -_GRAY = "\033[90m" - - -def _colored(text: str, *codes: str) -> str: - """Wrap text in ANSI escape codes.""" - prefix = "".join(codes) - return f"{prefix}{text}{_RESET}" - - -# --------------------------------------------------------------------------- -# Tracking state for deduplication and clean output -# --------------------------------------------------------------------------- - -# Track whether we're in the middle of streaming text (to manage newlines) -_streaming_text = False - -# Track the last MCP summary string to deduplicate notifications -_last_mcp_summary: str | None = None - -# Track the last token usage to only print at turn end -_last_token_usage: TokenUsageUpdate | None = None - - -def _ensure_newline() -> None: - """Print a newline if we were streaming text inline.""" - global _streaming_text - if _streaming_text: - print() - _streaming_text = False - - -# --------------------------------------------------------------------------- -# Message rendering -# --------------------------------------------------------------------------- - - -def render_message(msg: StreamMessage) -> None: - """Render a single StreamMessage with ANSI colors.""" - global _streaming_text, _last_token_usage - - if isinstance(msg, AssistantTextDelta): - # Stream assistant text char-by-char (inline, no newline) - print(msg.text, end="", flush=True) - _streaming_text = True - - elif isinstance(msg, ThinkingTextDelta): - # Thinking text in gray with prefix (inline, no newline) - if not _streaming_text: - print(_colored("[thinking] ", _GRAY, _DIM), end="", flush=True) - _streaming_text = True - print(_colored(msg.text, _GRAY, _DIM), end="", flush=True) - - elif isinstance(msg, ToolUse): - _ensure_newline() - print() # blank line before tool call - input_summary = json.dumps(msg.tool_input, ensure_ascii=False) - if len(input_summary) > 120: - input_summary = input_summary[:117] + "..." - print(_colored("[tool] ", _YELLOW, _BOLD) + _colored(msg.tool_name, _YELLOW)) - print(_colored(f" {input_summary}", _DIM)) - - elif isinstance(msg, ToolResult): - _ensure_newline() - content_preview = _content_preview(msg.content) - if msg.is_error: - tag = "[error] " - name = msg.tool_name or "unknown" - print(_colored(tag, _RED, _BOLD) + _colored(f"{name} (error)", _RED)) - print(_colored(f" {content_preview}", _RED)) - else: - tag = "[result] " - name = msg.tool_name or "unknown" - print(_colored(tag, _GREEN, _BOLD) + _colored(f"{name} (success)", _GREEN)) - print(_colored(f" {content_preview}", _DIM)) - print() # blank line after tool result - - elif isinstance(msg, ToolProgress): - _ensure_newline() - print(_colored("[progress] ", _CYAN, _BOLD) + _colored(msg.tool_name, _CYAN)) - print(_colored(f" {msg.content}", _CYAN)) - - elif isinstance(msg, WorkingStateChanged): - # Suppress state changes entirely — tool calls and results already - # indicate what's happening, and "Streaming Assistant Message" is - # obvious from the text appearing on screen. - pass - - elif isinstance(msg, TokenUsageUpdate): - # Stash the latest token usage; we only print it at turn end. - _last_token_usage = msg - - elif isinstance(msg, ErrorEvent): - _ensure_newline() - print() - print(_colored(f"[error] {msg.error_type}: {msg.message}", _RED, _BOLD)) - print() - - elif isinstance(msg, TurnComplete): - _ensure_newline() - print() - # Print token usage (from stashed update or TurnComplete payload) - tu = msg.token_usage - if tu is not None: - total = tu.input_tokens + tu.output_tokens - print( - _colored( - f"[tokens] {total:,} total " - f"(in={tu.input_tokens:,}, out={tu.output_tokens:,}, " - f"cache_read={tu.cache_read_tokens:,}, " - f"cache_write={tu.cache_write_tokens:,})", - _DIM, - ) - ) - elif _last_token_usage is not None: - t = _last_token_usage - total = t.input_tokens + t.output_tokens - print( - _colored( - f"[tokens] {total:,} total " - f"(in={t.input_tokens:,}, out={t.output_tokens:,}, " - f"cache_read={t.cache_read_tokens:,}, " - f"cache_write={t.cache_write_tokens:,})", - _DIM, - ) - ) - print(_colored("[done] Turn complete", _GREEN, _BOLD)) - print() # blank line before next prompt - # Reset stashed token usage for next turn - _last_token_usage = None - - else: - # Future-proof: render unknown message types - _ensure_newline() - print(_colored(f" [?] {type(msg).__name__}: {msg}", _DIM)) +from droid_sdk import AssistantMessage, Session, TextDelta -def _content_preview(content: str | list[object], max_len: int = 100) -> str: - """Create a truncated preview of tool result content.""" - if isinstance(content, list): - text = json.dumps(content, ensure_ascii=False) - else: - text = str(content) - # Collapse whitespace for display - text = " ".join(text.split()) - if len(text) > max_len: - return text[: max_len - 3] + "..." - return text - -# --------------------------------------------------------------------------- -# Notification listener for events not in receive_response() -# --------------------------------------------------------------------------- - - -def on_raw_notification(notification: dict[str, object]) -> None: - """Handle notifications not covered by receive_response(). - - Renders MCP status changes, session title updates, and other - notification types that are not mapped to StreamMessage. - """ - global _last_mcp_summary - - params = notification.get("params") - if not isinstance(params, dict): +async def main(run_turns: bool = False) -> None: + if not run_turns: + session = Session() + assert session.cwd is not None + print("self-test: lazy session configured") return - inner = params.get("notification") - if not isinstance(inner, dict): - return - - notif_type = inner.get("type") - - if notif_type == "mcp_status_changed": - servers = inner.get("servers", []) - summary = inner.get("summary", {}) - connected = summary.get("connected", 0) - total = summary.get("total", 0) - - # Build a summary string to detect duplicates - server_lines: list[str] = [] - if isinstance(servers, list): - for srv in servers: - if isinstance(srv, dict): - name = srv.get("name", "?") - status = srv.get("status", "?") - server_lines.append(f" {name}: {status}") - current_summary = f"{connected}/{total}|" + "|".join(server_lines) - - # Only print if the summary actually changed - if current_summary == _last_mcp_summary: - return - _last_mcp_summary = current_summary - - print() - print( - _colored( - f"[mcp] servers ({connected}/{total} connected):", - _MAGENTA, - ) - ) - for line in server_lines: - print(_colored(line, _DIM)) - - elif notif_type == "session_title_updated": - title = inner.get("title", "") - print(_colored(f"[title] {title}", _BLUE, _BOLD)) - - elif notif_type == "mcp_auth_required": - server_name = inner.get("serverName", "?") - auth_url = inner.get("authUrl", "?") - print(_colored(f"[mcp] auth required for {server_name}", _YELLOW, _BOLD)) - print(_colored(f" URL: {auth_url}", _DIM)) - - elif notif_type == "mcp_auth_completed": - server_name = inner.get("serverName", "?") - outcome = inner.get("outcome", "?") - print(_colored(f"[mcp] auth {outcome} for {server_name}", _YELLOW)) - - elif notif_type == "mission_state_changed": - state = inner.get("state", "?") - print(_colored(f"[state] mission: {state}", _MAGENTA, _BOLD)) - - elif notif_type == "permission_resolved": - option = inner.get("selectedOption", "?") - print(_colored(f"[state] permission resolved: {option}", _DIM)) - - -# --------------------------------------------------------------------------- -# Main session loop -# --------------------------------------------------------------------------- - -async def main(cwd: str, exec_path: str) -> None: - """Run an interactive Droid session with full activity rendering.""" - transport = ProcessTransport(exec_path=exec_path, cwd=cwd) - - async with DroidClient(transport=transport) as client: - # Register raw notification listener for events outside receive_response() - client.on_notification(on_raw_notification) - - # Register permission handler (auto-approve all) - def handle_permission(params: dict[str, object]) -> str: - """Auto-approve all permission requests.""" - tool_uses = params.get("toolUses") - if isinstance(tool_uses, list): - for tool in tool_uses: - if isinstance(tool, dict): - tool_use = tool.get("toolUse") - if isinstance(tool_use, dict): - name = tool_use.get("name", "unknown") - print( - _colored( - f"[state] auto-approving: {name}", - _YELLOW, - _BOLD, - ) - ) - return ToolConfirmationOutcome.ProceedOnce.value - - client.set_permission_handler(handle_permission) - - # Initialize session - print(f"Executable: {exec_path}") - print(f"Working directory: {cwd}") + async with Session() as session: + async with session.stream( + "Reply with one short sentence.", timeout=60 + ) as first: + async for event in first: + if isinstance(event, AssistantMessage): + print(event.text) + assert first.result.session_id == session.id + + async with session.stream( + "Reply with three words.", + include_partial_messages=True, + timeout=60, + ) as second: + async for event in second: + if isinstance(event, TextDelta): + print(event.text, end="", flush=True) print() - - try: - result = await client.initialize_session( - machine_id="interactive-example", - cwd=cwd, - ) - print(f"Session ID: {result.session_id}") - print(f"Model: {result.settings.model_id}") - if result.available_models: - print(f"Available models: {len(result.available_models)}") - except TimeoutError: - print(_colored("ERROR: Session initialization timed out.", _RED, _BOLD)) - return - except ConnectionError as e: - print(_colored(f"ERROR: Could not connect: {e}", _RED, _BOLD)) - return - - # Brief pause to let MCP notifications arrive before first prompt - await asyncio.sleep(1.0) - - # Interactive loop - print() - print("Type your messages below. Press Ctrl+C or type 'exit' to quit.") - - while True: - try: - # Small delay for pending notification flush - await asyncio.sleep(0.1) - user_input = await asyncio.get_event_loop().run_in_executor( - None, lambda: input(_colored("\n> ", _CYAN, _BOLD)) - ) - except (EOFError, KeyboardInterrupt): - print("\nGoodbye!") - break - - user_input = user_input.strip() - if not user_input: - continue - if user_input.lower() in ("exit", "quit", ":q"): - print("Goodbye!") - break - - try: - await client.add_user_message(text=user_input) - - # Stream the response using receive_response() - async for msg in client.receive_response(): - render_message(msg) - - except ProcessExitError as e: - print(_colored(f"\n[error] Droid process exited: {e}", _RED, _BOLD)) - break - except DroidClientError as e: - print(_colored(f"\n[error] {e}", _RED, _BOLD)) - break - - print(_colored("\nSession closed.", _DIM)) - - -# --------------------------------------------------------------------------- -# CLI entry point -# --------------------------------------------------------------------------- - - -def parse_args() -> argparse.Namespace: - """Parse command-line arguments.""" - parser = argparse.ArgumentParser( - description="Interactive Factory Droid session with full activity rendering", - ) - parser.add_argument( - "--cwd", - default=os.getcwd(), - help="Working directory for the droid session (default: current directory)", - ) - parser.add_argument( - "--exec-path", - default="droid", - help="Path to the droid executable (default: 'droid')", - ) - return parser.parse_args() + assert second.result.turn_count == 1 if __name__ == "__main__": - args = parse_args() - try: - asyncio.run(main(cwd=args.cwd, exec_path=args.exec_path)) - except KeyboardInterrupt: - sys.exit(0) + parser = argparse.ArgumentParser() + parser.add_argument("--run", action="store_true") + asyncio.run(main(parser.parse_args().run)) diff --git a/examples/list_saved_sessions.py b/examples/list_saved_sessions.py new file mode 100644 index 0000000..05f697e --- /dev/null +++ b/examples/list_saved_sessions.py @@ -0,0 +1,23 @@ +"""List local saved sessions without starting Droid.""" + +from __future__ import annotations + +import asyncio +import tempfile +from pathlib import Path + +from droid_sdk import list_sessions + + +async def main() -> None: + with tempfile.TemporaryDirectory() as directory: + sessions = await list_sessions( + cwd=Path(directory), + limit=10, + ) + assert sessions == [] + print("saved sessions:", len(sessions)) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/low_level_session.py b/examples/low_level_session.py new file mode 100644 index 0000000..af07e80 --- /dev/null +++ b/examples/low_level_session.py @@ -0,0 +1,47 @@ +"""Initialize a local Droid session and list its available tools.""" + +from __future__ import annotations + +import argparse +import asyncio +import os +import socket +from pathlib import Path + +from droid_sdk.low_level import DroidClient, ListToolsResult + + +async def run_session( + client: DroidClient, + *, + cwd: str, + machine_id: str, +) -> ListToolsResult: + """Run the example flow with a caller-provided low-level client.""" + await client.connect() + try: + initialized = await client.initialize_session( + machine_id=machine_id, + cwd=cwd, + ) + tools = await client.list_tools() + print(f"Session: {initialized.session_id}") + print(f"Available tools: {len(tools.tools)}") + return tools + finally: + await client.close() + + +async def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--droid", default="droid", help="Path to the Droid CLI") + parser.add_argument("--cwd", default=os.getcwd(), help="Session working directory") + args = parser.parse_args() + + cwd = str(Path(args.cwd).resolve()) + client = DroidClient(exec_path=args.droid, cwd=cwd) + await run_session(client, cwd=cwd, machine_id=socket.gethostname()) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/observability.py b/examples/observability.py new file mode 100644 index 0000000..eeb3450 --- /dev/null +++ b/examples/observability.py @@ -0,0 +1,99 @@ +"""Observe a deterministic Session operation without a model turn.""" + +from __future__ import annotations + +import asyncio +import json +from typing import Any + +from droid_sdk import Runtime, Session +from droid_sdk.observability import ( + LogEvent, + MetricEvent, + Observability, + TraceContext, +) + + +class Sinks: + def __init__(self) -> None: + self.logs = 0 + self.metrics = 0 + self.traces = 0 + + def log(self, event: LogEvent) -> None: + self.logs += 1 + raise RuntimeError("a throwing logger must not break SDK operations") + + def record(self, event: MetricEvent) -> None: + self.metrics += 1 + + def inject(self, carrier: TraceContext) -> None: + self.traces += 1 + carrier.traceparent = "00-" + ("1" * 32) + "-" + ("2" * 16) + "-01" + + +class LoopbackTransport: + """Minimal connected transport for an offline Session lifecycle.""" + + def __init__(self) -> None: + self.is_connected = True + self._messages: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue() + + async def connect(self) -> None: + self.is_connected = True + + async def send(self, message: str) -> None: + request = json.loads(message) + method = request["method"] + if method == "droid.initialize_session": + result: dict[str, Any] = { + "sessionId": "offline-session", + "session": { + "id": "offline-session", + "createdAt": "2025-01-01T00:00:00Z", + "settings": {}, + "messages": [], + }, + "settings": { + "modelId": "offline-model", + "reasoningEffort": "medium", + }, + } + else: + result = {} + await self._messages.put( + {"jsonrpc": "2.0", "id": request["id"], "result": result} + ) + + async def read_messages(self) -> Any: + while (message := await self._messages.get()) is not None: + yield message + + async def close(self) -> None: + if self.is_connected: + self.is_connected = False + await self._messages.put(None) + + +async def main() -> None: + sinks = Sinks() + observability = Observability(logger=sinks, metrics=sinks, tracing=sinks) + runtime = Runtime( + transport=LoopbackTransport(), + observability=observability, + ) + + async with Session(runtime=runtime) as session: + assert session.id == "offline-session" + + assert sinks.logs >= 4 + assert sinks.metrics >= 2 + assert sinks.traces >= 2 + print( + f"logs={sinks.logs} metrics={sinks.metrics} traces={sinks.traces} isolated=True" + ) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/one_shot.py b/examples/one_shot.py new file mode 100644 index 0000000..454c559 --- /dev/null +++ b/examples/one_shot.py @@ -0,0 +1,23 @@ +"""One bounded turn with automatic cleanup.""" + +from __future__ import annotations + +import argparse +import asyncio + +from droid_sdk import run + + +async def main(run_turn: bool = False) -> None: + if not run_turn: + print("self-test: import and event loop ready") + return + result = await run("Reply with exactly: SDK ready", timeout=60) + print(result.text) + assert result.session_id + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--run", action="store_true") + asyncio.run(main(parser.parse_args().run)) diff --git a/examples/resume_session.py b/examples/resume_session.py new file mode 100644 index 0000000..5a7e12e --- /dev/null +++ b/examples/resume_session.py @@ -0,0 +1,25 @@ +"""Resume a persisted session by ID.""" + +from __future__ import annotations + +import argparse +import asyncio + +from droid_sdk import Session + + +async def main(session_id: str | None) -> None: + if session_id is None: + print("self-test: pass --session-id to resume") + return + async with Session.resume(session_id) as session: + async with session.stream("Reply with: resumed", timeout=60) as stream: + async for _ in stream: + pass + print(stream.result.text) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--session-id") + asyncio.run(main(parser.parse_args().session_id)) diff --git a/examples/sdk_mcp.py b/examples/sdk_mcp.py new file mode 100644 index 0000000..209e2c0 --- /dev/null +++ b/examples/sdk_mcp.py @@ -0,0 +1,56 @@ +"""Authenticated local SDK MCP tool configuration.""" + +from __future__ import annotations + +import argparse +import asyncio + +from droid_sdk import ( + InteractionHandlers, + PermissionRequest, + PermissionResponse, + Session, + SessionConfig, + ToolConfirmationOutcome, +) +from droid_sdk.mcp import ToolResponse, create_sdk_mcp_server, tool + + +@tool("lookup_owner", "Return a deterministic file owner.") +def lookup_owner(path: str) -> ToolResponse: + return ToolResponse( + content=f"Owner for {path}: platform-team", + structured_content={"owner": "platform-team"}, + ) + + +def allow_example_tool(request: PermissionRequest) -> PermissionResponse: + return request.respond(ToolConfirmationOutcome.PROCEED_ONCE) + + +async def main(run_turn: bool = False) -> None: + server = create_sdk_mcp_server("example-tools", [lookup_owner]) + if not run_turn: + config = await server.start() + assert config.url.startswith("http://127.0.0.1:") + await server.close() + assert server.config is None + print("self-test: MCP started and stopped") + return + async with Session( + config=SessionConfig(mcp_servers=[server]), + interactions=InteractionHandlers(on_permission=allow_example_tool), + ) as session: + async with session.stream( + "Use lookup_owner for README.md and report its answer.", + timeout=60, + ) as stream: + async for _ in stream: + pass + print(stream.result.text) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--run", action="store_true") + asyncio.run(main(parser.parse_args().run)) diff --git a/examples/session_operations.py b/examples/session_operations.py new file mode 100644 index 0000000..c569ab7 --- /dev/null +++ b/examples/session_operations.py @@ -0,0 +1,50 @@ +"""Settings, context, tools, skills, spec, and replacement ownership.""" + +from __future__ import annotations + +import argparse +import asyncio +import contextlib + +from droid_sdk import Autonomy, Mode, Session, SessionReplacedError + + +async def main(run_operations: bool = False) -> None: + if not run_operations: + assert Mode.AUTO.value == "auto" + assert Autonomy.LOW.value == "low" + print("self-test: operation types ready") + return + + session = Session() + await session.open() + try: + await session.update_settings(autonomy=Autonomy.LOW) + print(await session.context()) + print([tool.id for tool in await session.list_tools()]) + print([skill.name for skill in (await session.list_skills()).skills]) + await session.enter_spec() + await session.leave_spec() + + successor = await session.fork(title="SDK example fork") + with contextlib.suppress(SessionReplacedError): + await session.context() + async with successor: + async with successor.stream( + "Reply with exactly: ready to compact", + timeout=60, + ) as stream: + async for _ in stream: + pass + print(stream.result.text) + compacted = await successor.compact(instructions="Keep decisions.") + async with compacted.session: + print(compacted.removed_count) + finally: + await session.close() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--run", action="store_true") + asyncio.run(main(parser.parse_args().run)) diff --git a/examples/structured_output_model.py b/examples/structured_output_model.py new file mode 100644 index 0000000..d5aa697 --- /dev/null +++ b/examples/structured_output_model.py @@ -0,0 +1,41 @@ +"""Pydantic structured output from one bounded turn.""" + +from __future__ import annotations + +import argparse +import asyncio +from typing import Literal + +from pydantic import BaseModel + +from droid_sdk import run + + +class Finding(BaseModel): + severity: Literal["low", "medium", "high"] + message: str + + +class Review(BaseModel): + summary: str + findings: list[Finding] + + +async def main(run_turn: bool = False) -> None: + if not run_turn: + assert Review.model_json_schema()["type"] == "object" + print("self-test: output schema ready") + return + result = await run( + "Return a short repository summary and zero or more findings.", + output=Review, + timeout=60, + ) + assert result.output is not None, result.output_validation_error + print(result.output.summary) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--run", action="store_true") + asyncio.run(main(parser.parse_args().run)) diff --git a/pyproject.toml b/pyproject.toml index 3980cd4..0b5b8ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,10 @@ readme = "README.md" license = {text = "Apache-2.0"} requires-python = ">=3.10" dependencies = [ + "mcp>=1.27,<2", "pydantic>=2.0", + "starlette>=0.40", + "uvicorn>=0.31,<1", ] [dependency-groups] @@ -14,6 +17,7 @@ dev = [ "pytest", "pytest-asyncio", "mypy", + "pyright", "ruff", "pytest-cov", ] @@ -25,6 +29,9 @@ build-backend = "hatchling.build" [tool.hatch.build.targets.wheel] packages = ["src/droid_sdk"] +[tool.hatch.build.targets.sdist] +exclude = ["/tests"] + [tool.pytest.ini_options] asyncio_mode = "strict" testpaths = ["tests"] @@ -32,6 +39,7 @@ testpaths = ["tests"] [tool.mypy] strict = true plugins = ["pydantic.mypy"] +files = ["src", "tests/typing/positive.py"] [tool.pydantic-mypy] init_forbid_extra = true @@ -39,6 +47,11 @@ init_typed = true warn_required_dynamic_aliases = true warn_untyped_fields = true +[tool.pyright] +typeCheckingMode = "strict" +include = ["src", "tests/typing/positive.py"] +pythonVersion = "3.10" + [tool.ruff] target-version = "py310" src = ["src", "tests"] diff --git a/src/droid_sdk/__init__.py b/src/droid_sdk/__init__.py index bf8033f..8eaa682 100644 --- a/src/droid_sdk/__init__.py +++ b/src/droid_sdk/__init__.py @@ -4,82 +4,333 @@ subprocess via JSON-RPC 2.0 over JSONL (newline-delimited JSON). """ +# ruff: noqa: RUF022 + from __future__ import annotations import importlib.metadata -from droid_sdk.client import DroidClient -from droid_sdk.errors import ( - ConnectionError, - DroidClientError, - ProcessExitError, - ProtocolError, - SessionError, - SessionNotFoundError, - TimeoutError, +from droid_sdk._high_level._immutable import ( + FrozenJsonObject, + FrozenJsonValue, + JsonObject, + JsonValue, +) +from droid_sdk._high_level.attachments import ( + MAX_ATTACHMENT_BYTES, + MAX_PDF_ATTACHMENT_BYTES, + Base64ImageSource, + Document, + DocumentSource, + Image, + ImageMediaType, + PdfDocumentSource, + TextDocumentSource, +) +from droid_sdk._high_level.config import ( + JsonSchema, + SandboxSettings, + SavedSession, + SessionConfig, + SessionSettings, + SessionSettingsUpdate, + SessionSource, + SessionTag, + UpdateSettingsResult, ) -from droid_sdk.query import DroidQueryOptions, query -from droid_sdk.schemas.enums import ( - DroidWorkingState, +from droid_sdk._high_level.discovery import list_sessions +from droid_sdk._high_level.enums import ( + Autonomy, + ContextAccuracy, + ErrorType, + McpAuthOutcome, McpServerStatus, - MissionState, - SessionNotificationType, + McpServerType, + Mode, + OAuthTokenEndpointAuthMethod, + ReasoningEffort, + SandboxOperation, + SandboxViolationReason, + SandboxViolationType, + SessionPlatform, + ToolCategory, ToolConfirmationOutcome, ToolConfirmationType, + WorkingState, ) -from droid_sdk.stream import ( - AssistantTextDelta, +from droid_sdk._high_level.extensions import ( + CompactOutcome, + DroidTool, + HttpHeader, + HttpMcpServerConfig, + ListToolsOptions, + McpConfigError, + McpMutationResult, + McpOAuthOptions, + McpServerConfig, + McpServersResult, + McpServerStatusInfo, + McpStatusSummary, + McpToolInfo, + McpToolInputSchema, + RewindEvictedFile, + RewindFileCreation, + RewindFileSnapshot, + RewindInfo, + RewindOutcome, + SdkMcpServer, + SkillInfo, + SkillMutationResult, + SkillResource, + SkillsResult, + SseMcpServerConfig, + StdioMcpServerConfig, + ToolInfo, + ToolResponse, +) +from droid_sdk._high_level.interactions import ( + ApplyPatchAction, + ApplyPatchFile, + AskUserAction, + AskUserParseError, + CreateFile, + DroidShieldViolationAction, + EditAction, + ExecuteAction, + ExitSpecModeAction, + InteractionHandlers, + McpToolAction, + PermissionAction, + PermissionHandler, + PermissionOption, + PermissionRequest, + PermissionResponse, + Plan, + Question, + QuestionAnswer, + QuestionHandler, + QuestionRequest, + QuestionResponse, + SandboxViolationAction, +) +from droid_sdk._high_level.messages import ( + AssistantMessage, + ContentBlock, + ContextUsage, + ConversationMessage, + DocumentBlock, ErrorEvent, + HookExecution, + ImageBlock, + McpAuthCompleted, + McpAuthRequired, + McpStatusChanged, + Message, + PermissionResolved, + RedactedThinkingBlock, + RunFailure, + RunInterrupted, + RunResult, + RunSuccess, + SessionTitleUpdated, + SessionWorkingDirectoryChanged, + SettingsUpdated, + StreamEvent, StreamMessage, - ThinkingTextDelta, + StructuredOutputError, + TextBlock, + TextComplete, + TextDelta, + ThinkingBlock, + ThinkingComplete, + ThinkingDelta, TokenUsageUpdate, + ToolCall, + ToolCallDelta, ToolProgress, + ToolProgressUpdate, ToolResult, - ToolUse, - TurnComplete, + ToolResultBlock, + ToolUseBlock, + Usage, + UserMessage, WorkingStateChanged, ) -from droid_sdk.transport import ProcessTransport -from droid_sdk.types import DroidClientTransport +from droid_sdk._high_level.runtime import Runtime, Transport +from droid_sdk._high_level.session import Session, run +from droid_sdk._high_level.streaming import RunStream +from droid_sdk.errors import ( + DroidConnectionError, + DroidError, + DroidProcessError, + DroidProtocolError, + InvalidAttachmentError, + InvalidWorkingDirectoryError, + RunTimeoutError, + SessionBusyError, + SessionClosedError, + SessionNotFoundError, + SessionNotOpenError, + SessionReplacedError, + SessionReplacementError, + StreamIncompleteError, +) __version__: str = importlib.metadata.version("droid-sdk") __all__: list[str] = [ - # Stream message types - "AssistantTextDelta", - "ConnectionError", - # Client - "DroidClient", - # Errors - "DroidClientError", - "DroidClientTransport", - # Query convenience API - "DroidQueryOptions", - "DroidWorkingState", + "MAX_ATTACHMENT_BYTES", + "MAX_PDF_ATTACHMENT_BYTES", + "ApplyPatchAction", + "ApplyPatchFile", + "AskUserAction", + "AskUserParseError", + "AssistantMessage", + "Autonomy", + "Base64ImageSource", + "CompactOutcome", + "ContentBlock", + "ContextAccuracy", + "ContextUsage", + "ConversationMessage", + "CreateFile", + "Document", + "DocumentBlock", + "DocumentSource", + "DroidConnectionError", + "DroidError", + "DroidProcessError", + "DroidProtocolError", + "DroidShieldViolationAction", + "DroidTool", + "EditAction", "ErrorEvent", + "ErrorType", + "ExecuteAction", + "ExitSpecModeAction", + "FrozenJsonObject", + "FrozenJsonValue", + "HookExecution", + "HttpHeader", + "HttpMcpServerConfig", + "Image", + "ImageBlock", + "ImageMediaType", + "InteractionHandlers", + "InvalidAttachmentError", + "InvalidWorkingDirectoryError", + "JsonObject", + "JsonSchema", + "JsonValue", + "ListToolsOptions", + "McpAuthCompleted", + "McpAuthOutcome", + "McpAuthRequired", + "McpConfigError", + "McpMutationResult", + "McpOAuthOptions", + "McpServerConfig", "McpServerStatus", - "MissionState", - "ProcessExitError", - # Transport - "ProcessTransport", - "ProtocolError", - "SessionError", + "McpServerStatusInfo", + "McpServerType", + "McpServersResult", + "McpStatusChanged", + "McpStatusSummary", + "McpToolAction", + "McpToolInfo", + "McpToolInputSchema", + "Message", + "Mode", + "OAuthTokenEndpointAuthMethod", + "PdfDocumentSource", + "PermissionAction", + "PermissionHandler", + "PermissionOption", + "PermissionRequest", + "PermissionResolved", + "PermissionResponse", + "Plan", + "Question", + "QuestionAnswer", + "QuestionHandler", + "QuestionRequest", + "QuestionResponse", + "ReasoningEffort", + "RedactedThinkingBlock", + "RewindEvictedFile", + "RewindFileCreation", + "RewindFileSnapshot", + "RewindInfo", + "RewindOutcome", + "RunFailure", + "RunInterrupted", + "RunResult", + "RunStream", + "RunSuccess", + "RunTimeoutError", + "Runtime", + "SandboxOperation", + "SandboxSettings", + "SandboxViolationAction", + "SandboxViolationReason", + "SandboxViolationType", + "SavedSession", + "SdkMcpServer", + "SessionBusyError", + "SessionClosedError", + "SessionConfig", "SessionNotFoundError", - "SessionNotificationType", + "SessionNotOpenError", + "Session", + "SessionPlatform", + "SessionReplacedError", + "SessionReplacementError", + "SessionSettings", + "SessionSettingsUpdate", + "SessionSource", + "SessionTag", + "SessionTitleUpdated", + "SessionWorkingDirectoryChanged", + "SettingsUpdated", + "SkillInfo", + "SkillMutationResult", + "SkillResource", + "SkillsResult", + "SseMcpServerConfig", + "StdioMcpServerConfig", + "StreamEvent", + "StreamIncompleteError", "StreamMessage", - "ThinkingTextDelta", - "TimeoutError", + "StructuredOutputError", + "TextBlock", + "TextComplete", + "TextDelta", + "TextDocumentSource", + "ThinkingBlock", + "ThinkingComplete", + "ThinkingDelta", "TokenUsageUpdate", + "ToolCall", + "ToolCallDelta", + "ToolCategory", # Key enums "ToolConfirmationOutcome", "ToolConfirmationType", + "ToolInfo", "ToolProgress", + "ToolProgressUpdate", + "ToolResponse", "ToolResult", - "ToolUse", - "TurnComplete", + "ToolResultBlock", + "ToolUseBlock", + "Transport", + "UpdateSettingsResult", + "Usage", + "UserMessage", + "WorkingState", "WorkingStateChanged", + "list_sessions", + "run", # Version "__version__", - # Query function - "query", ] diff --git a/src/droid_sdk/_high_level/__init__.py b/src/droid_sdk/_high_level/__init__.py new file mode 100644 index 0000000..bc0e30a --- /dev/null +++ b/src/droid_sdk/_high_level/__init__.py @@ -0,0 +1 @@ +"""Implementation modules for the stable high-level API.""" diff --git a/src/droid_sdk/_high_level/_immutable.py b/src/droid_sdk/_high_level/_immutable.py new file mode 100644 index 0000000..29720bd --- /dev/null +++ b/src/droid_sdk/_high_level/_immutable.py @@ -0,0 +1,111 @@ +"""Small normalization helpers shared by the public immutable models.""" + +from __future__ import annotations + +import math +from collections.abc import Iterator, Mapping, Sequence +from types import MappingProxyType +from typing import TypeAlias, cast + +JsonValue: TypeAlias = ( + bool | int | float | str | None | list["JsonValue"] | dict[str, "JsonValue"] +) +JsonObject: TypeAlias = dict[str, JsonValue] +Scalar: TypeAlias = str | int | float | bool | None +FrozenJsonValue: TypeAlias = ( + bool + | int + | float + | str + | None + | tuple["FrozenJsonValue", ...] + | Mapping[str, "FrozenJsonValue"] +) +FrozenJsonObject: TypeAlias = Mapping[str, FrozenJsonValue] + + +class RedactedStrMapping(Mapping[str, str]): + """Immutable string mapping whose representation never exposes values.""" + + __slots__ = ("_values",) + + def __init__(self, values: Mapping[str, str]) -> None: + self._values = MappingProxyType(dict(values)) + + def __getitem__(self, key: str) -> str: + return self._values[key] + + def __iter__(self) -> Iterator[str]: + return iter(self._values) + + def __len__(self) -> int: + return len(self._values) + + def __repr__(self) -> str: + entries = ", ".join(f"{key!r}: ''" for key in self._values) + return f"{{{entries}}}" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Mapping): + return False + return self._values == other + + +def freeze_json(value: object, *, where: str = "value") -> FrozenJsonValue: + """Validate a JSON value and recursively replace mutable containers.""" + if value is None or isinstance(value, (str, bool)): + return value + if isinstance(value, int): + return value + if isinstance(value, float): + if not math.isfinite(value): + raise ValueError(f"{where} must contain only finite JSON numbers") + return value + if isinstance(value, Mapping): + source = cast("Mapping[object, object]", value) + frozen: dict[str, FrozenJsonValue] = {} + for key, item in source.items(): + if not isinstance(key, str): + raise TypeError(f"{where} must have string object keys") + frozen[key] = freeze_json(item, where=where) + return MappingProxyType(frozen) + if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)): + source_sequence = cast("Sequence[object]", value) + return tuple(freeze_json(item, where=where) for item in source_sequence) + raise TypeError(f"{where} contains a non-JSON value of type {type(value).__name__}") + + +def freeze_json_object( + value: Mapping[str, object], *, where: str = "value" +) -> FrozenJsonObject: + frozen = freeze_json(value, where=where) + if not isinstance(frozen, Mapping): + raise TypeError(f"{where} must be a JSON object") + return frozen + + +def thaw_json(value: FrozenJsonValue) -> JsonValue: + """Return ordinary list/dict containers suitable for a JSON boundary.""" + if isinstance(value, Mapping): + return {key: thaw_json(item) for key, item in value.items()} + if isinstance(value, Sequence) and not isinstance(value, str): + return [thaw_json(item) for item in value] + return value + + +def freeze_secret_mapping(value: Mapping[str, str]) -> Mapping[str, str]: + return RedactedStrMapping(value) + + +def freeze_scalar_mapping( + value: Mapping[str, object] | None, +) -> Mapping[str, Scalar]: + if value is None: + return MappingProxyType({}) + result: dict[str, Scalar] = {} + for key, item in value.items(): + if item is None or isinstance(item, (str, int, float, bool)): + if isinstance(item, float) and not math.isfinite(item): + continue + result[key] = item + return MappingProxyType(result) diff --git a/src/droid_sdk/_high_level/attachments.py b/src/droid_sdk/_high_level/attachments.py new file mode 100644 index 0000000..5c4c1ed --- /dev/null +++ b/src/droid_sdk/_high_level/attachments.py @@ -0,0 +1,276 @@ +"""Safe, immutable local attachment values.""" + +from __future__ import annotations + +import base64 +import os +import stat +from dataclasses import dataclass +from pathlib import Path +from typing import Literal + +from droid_sdk.errors import InvalidAttachmentError + +ImageMediaType = Literal["image/jpeg", "image/png", "image/gif", "image/webp"] +MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024 +MAX_PDF_ATTACHMENT_BYTES = 3 * 1024 * 1024 + + +def _oversize_error() -> InvalidAttachmentError: + return InvalidAttachmentError( + f"Attachment exceeds the {MAX_ATTACHMENT_BYTES}-byte limit" + ) + + +def _pdf_oversize_error() -> InvalidAttachmentError: + return InvalidAttachmentError( + f"PDF attachment exceeds the {MAX_PDF_ATTACHMENT_BYTES}-byte limit" + ) + + +def _read_regular_file( + path: str | Path, + *, + max_bytes: int | None = None, +) -> tuple[Path, bytes]: + resolved = Path(path) + limit = MAX_ATTACHMENT_BYTES if max_bytes is None else max_bytes + try: + path_stat = resolved.stat() + if not stat.S_ISREG(path_stat.st_mode): + raise InvalidAttachmentError( + f"Attachment is not a regular file: {resolved}" + ) + if path_stat.st_size > limit: + raise _oversize_error() + + with resolved.open("rb") as file: + before = os.fstat(file.fileno()) + if not stat.S_ISREG(before.st_mode): + raise InvalidAttachmentError( + f"Attachment is not a regular file: {resolved}" + ) + if ( + before.st_dev != path_stat.st_dev + or before.st_ino != path_stat.st_ino + or before.st_size != path_stat.st_size + or before.st_mtime_ns != path_stat.st_mtime_ns + ): + raise InvalidAttachmentError("Attachment changed before it was read") + if before.st_size > limit: + raise _oversize_error() + + data = file.read(limit + 1) + after = os.fstat(file.fileno()) + + if len(data) > limit or after.st_size > limit: + raise _oversize_error() + if ( + after.st_size != before.st_size + or after.st_mtime_ns != before.st_mtime_ns + or len(data) != after.st_size + ): + raise InvalidAttachmentError("Attachment changed while it was read") + return resolved, data + except InvalidAttachmentError: + raise + except FileNotFoundError: + raise InvalidAttachmentError(f"Attachment does not exist: {resolved}") from None + except PermissionError: + raise InvalidAttachmentError( + f"Attachment is not readable: {resolved}" + ) from None + except (OSError, ValueError) as exc: + raise InvalidAttachmentError( + f"Could not read attachment {resolved}: {type(exc).__name__}" + ) from None + + +def _detect_image_type(data: bytes) -> ImageMediaType | None: + if data.startswith(b"\x89PNG\r\n\x1a\n"): + return "image/png" + if data.startswith(b"\xff\xd8\xff"): + return "image/jpeg" + if data.startswith((b"GIF87a", b"GIF89a")): + return "image/gif" + if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP": + return "image/webp" + return None + + +def _utf8_exceeds_limit(value: str, limit: int) -> bool: + size = 0 + for start in range(0, len(value), 64 * 1024): + size += len(value[start : start + 64 * 1024].encode("utf-8")) + if size > limit: + return True + return False + + +@dataclass(frozen=True, slots=True) +class Base64ImageSource: + data: str + media_type: ImageMediaType + + def __post_init__(self) -> None: + if len(self.data) > 4 * ((MAX_ATTACHMENT_BYTES + 2) // 3): + raise _oversize_error() + if self.media_type not in { + "image/jpeg", + "image/png", + "image/gif", + "image/webp", + }: + raise InvalidAttachmentError( + f"Unsupported image media type: {self.media_type}" + ) + try: + decoded = base64.b64decode(self.data, validate=True) + except (ValueError, TypeError): + raise InvalidAttachmentError("Image data is not valid base64") from None + if len(decoded) > MAX_ATTACHMENT_BYTES: + raise _oversize_error() + detected = _detect_image_type(decoded) + if detected is None: + raise InvalidAttachmentError("Image data has an unsupported signature") + if detected != self.media_type: + raise InvalidAttachmentError( + f"Image data is {detected}, not {self.media_type}" + ) + + +def _image_source_from_validated_bytes( + data: bytes, + media_type: ImageMediaType, +) -> Base64ImageSource: + source = object.__new__(Base64ImageSource) + object.__setattr__(source, "data", base64.b64encode(data).decode("ascii")) + object.__setattr__(source, "media_type", media_type) + return source + + +@dataclass(frozen=True, slots=True) +class Image: + source: Base64ImageSource + + @classmethod + def from_path(cls, path: str | Path) -> Image: + _, data = _read_regular_file(path) + media_type = _detect_image_type(data) + if media_type is None: + raise InvalidAttachmentError("Unsupported or invalid image file") + return cls.from_bytes(data, media_type=media_type) + + @classmethod + def from_bytes(cls, data: bytes, *, media_type: ImageMediaType) -> Image: + if len(data) > MAX_ATTACHMENT_BYTES: + raise _oversize_error() + detected = _detect_image_type(data) + if detected is None: + raise InvalidAttachmentError("Unsupported or invalid image data") + if detected != media_type: + raise InvalidAttachmentError(f"Image data is {detected}, not {media_type}") + return cls(_image_source_from_validated_bytes(data, media_type)) + + +@dataclass(frozen=True, slots=True) +class TextDocumentSource: + data: str + name: str | None = None + mime: str | None = None + + def __post_init__(self) -> None: + if _utf8_exceeds_limit(self.data, MAX_ATTACHMENT_BYTES): + raise _oversize_error() + + +@dataclass(frozen=True, slots=True) +class PdfDocumentSource: + data: str + parsed_data: str | None = None + name: str | None = None + path: str | None = None + + def __post_init__(self) -> None: + if len(self.data) > 4 * ((MAX_PDF_ATTACHMENT_BYTES + 2) // 3): + raise _pdf_oversize_error() + try: + decoded = base64.b64decode(self.data, validate=True) + except (ValueError, TypeError): + raise InvalidAttachmentError("PDF data is not valid base64") from None + if len(decoded) > MAX_PDF_ATTACHMENT_BYTES: + raise _pdf_oversize_error() + if not decoded.startswith(b"%PDF-"): + raise InvalidAttachmentError("Document data is not a valid PDF") + + +def _pdf_source_from_validated_bytes( + data: bytes, + *, + name: str | None, + path: str | None, +) -> PdfDocumentSource: + source = object.__new__(PdfDocumentSource) + object.__setattr__(source, "data", base64.b64encode(data).decode("ascii")) + object.__setattr__(source, "parsed_data", None) + object.__setattr__(source, "name", name) + object.__setattr__(source, "path", path) + return source + + +DocumentSource = TextDocumentSource | PdfDocumentSource + + +@dataclass(frozen=True, slots=True) +class Document: + source: DocumentSource + + @classmethod + def from_path(cls, path: str | Path) -> Document: + file_path, data = _read_regular_file(path) + if data.startswith(b"%PDF-"): + if len(data) > MAX_PDF_ATTACHMENT_BYTES: + raise _pdf_oversize_error() + return cls( + _pdf_source_from_validated_bytes( + data, + name=file_path.name, + path=str(file_path), + ) + ) + try: + text = data.decode("utf-8") + except UnicodeDecodeError: + raise InvalidAttachmentError( + "Document is neither a PDF nor valid UTF-8 text" + ) from None + return cls.from_text(text, name=file_path.name, mime="text/plain") + + @classmethod + def from_text( + cls, + text: str, + *, + name: str | None = None, + mime: str | None = None, + ) -> Document: + return cls(TextDocumentSource(data=text, name=name, mime=mime)) + + @classmethod + def from_bytes( + cls, + data: bytes, + *, + name: str | None = None, + ) -> Document: + if len(data) > MAX_PDF_ATTACHMENT_BYTES: + raise _pdf_oversize_error() + if not data.startswith(b"%PDF-"): + raise InvalidAttachmentError("Document bytes are not a valid PDF") + return cls( + _pdf_source_from_validated_bytes( + data, + name=name, + path=None, + ) + ) diff --git a/src/droid_sdk/_high_level/config.py b/src/droid_sdk/_high_level/config.py new file mode 100644 index 0000000..c208caf --- /dev/null +++ b/src/droid_sdk/_high_level/config.py @@ -0,0 +1,198 @@ +"""Immutable session configuration and discovery snapshots.""" + +# ruff: noqa: TC001, TC003 + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from types import MappingProxyType +from typing import TYPE_CHECKING + +from droid_sdk._high_level._immutable import FrozenJsonObject, freeze_json_object +from droid_sdk._high_level.enums import ( + Autonomy, + Mode, + ReasoningEffort, + SessionPlatform, +) + +if TYPE_CHECKING: + from droid_sdk._high_level.extensions import McpServerConfig + +_TOOL_SET_FIELDS = ( + "additional_tools", + "enabled_tools", + "disabled_tools", + "restrict_tools", +) + + +def _aware(value: datetime, name: str) -> None: + if value.tzinfo is None or value.utcoffset() is None: + raise ValueError(f"{name} must be timezone-aware") + + +def _freeze_tool_sets(value: object) -> None: + for name in _TOOL_SET_FIELDS: + items = getattr(value, name) + if items is not None: + object.__setattr__(value, name, frozenset(items)) + + +@dataclass(frozen=True, slots=True) +class SessionTag: + name: str + metadata: Mapping[str, str] | None = None + + def __post_init__(self) -> None: + if self.metadata is not None: + object.__setattr__(self, "metadata", MappingProxyType(dict(self.metadata))) + + +@dataclass(frozen=True, slots=True) +class SessionSource: + """Authority source attribution. + + Fields not used by a platform remain ``None``. Validation of required + platform-specific fields occurs when the value is adapted to the wire. + """ + + platform: SessionPlatform + delegation_session_id: str | None = None + team_id: str | None = None + channel: str | None = None + thread_ts: str | None = None + user_id: str | None = None + automation_id: str | None = None + agent_session_id: str | None = None + issue_id: str | None = None + issue_url: str | None = None + issue_identifier: str | None = None + organization_id: str | None = None + cloud_id: str | None = None + issue_key: str | None = None + site_id: str | None = None + project_id: str | None = None + comment_id: str | None = None + task_id: str | None = None + tenant_id: str | None = None + conversation_id: str | None = None + service_url: str | None = None + conversation_type: str | None = None + root_message_id: str | None = None + channel_id: str | None = None + aad_object_id: str | None = None + report_id: str | None = None + repo_url: str | None = None + criterion_id: str | None = None + computer_id: str | None = None + + +@dataclass(frozen=True, slots=True) +class SandboxSettings: + enabled: bool + mode: str | None = None + + +@dataclass(frozen=True, slots=True) +class SessionConfig: + mode: Mode | None = None + autonomy: Autonomy | None = None + spec_model: str | None = None + spec_reasoning_effort: ReasoningEffort | None = None + mcp_servers: Sequence[McpServerConfig] = () + machine_id: str | None = None + tags: Sequence[SessionTag] = () + session_source: SessionSource | None = None + auto_reject_permission_requests: bool | None = None + disable_builtin_skills: bool | None = None + additional_tools: set[str] | frozenset[str] | None = None + enabled_tools: set[str] | frozenset[str] | None = None + disabled_tools: set[str] | frozenset[str] | None = None + restrict_tools: set[str] | frozenset[str] | None = None + + def __post_init__(self) -> None: + object.__setattr__(self, "mcp_servers", tuple(self.mcp_servers)) + object.__setattr__(self, "tags", tuple(self.tags)) + _freeze_tool_sets(self) + + +@dataclass(frozen=True, slots=True) +class SessionSettings: + model: str + reasoning_effort: ReasoningEffort + mode: Mode | None = None + autonomy: Autonomy | None = None + spec_model: str | None = None + spec_reasoning_effort: ReasoningEffort | None = None + tags: Sequence[SessionTag] = () + sandbox: SandboxSettings | None = None + additional_tools: set[str] | frozenset[str] | None = None + enabled_tools: set[str] | frozenset[str] | None = None + disabled_tools: set[str] | frozenset[str] | None = None + restrict_tools: set[str] | frozenset[str] | None = None + + def __post_init__(self) -> None: + object.__setattr__(self, "tags", tuple(self.tags)) + _freeze_tool_sets(self) + + +@dataclass(frozen=True, slots=True) +class SessionSettingsUpdate: + """Partial settings carried by a settings-updated notification.""" + + model: str | None = None + reasoning_effort: ReasoningEffort | None = None + mode: Mode | None = None + autonomy: Autonomy | None = None + spec_model: str | None = None + spec_reasoning_effort: ReasoningEffort | None = None + tags: Sequence[SessionTag] | None = None + additional_tools: set[str] | frozenset[str] | None = None + enabled_tools: set[str] | frozenset[str] | None = None + disabled_tools: set[str] | frozenset[str] | None = None + restrict_tools: set[str] | frozenset[str] | None = None + compaction_threshold_check_enabled: bool | None = None + + def __post_init__(self) -> None: + if self.tags is not None: + object.__setattr__(self, "tags", tuple(self.tags)) + _freeze_tool_sets(self) + + +@dataclass(frozen=True, slots=True) +class UpdateSettingsResult: + pass + + +@dataclass(frozen=True, slots=True) +class SavedSession: + id: str + title: str + owner: str + message_count: int + modified_at: datetime + created_at: datetime + cwd: Path | None = None + is_favorite: bool = False + + def __post_init__(self) -> None: + _aware(self.modified_at, "modified_at") + _aware(self.created_at, "created_at") + if self.cwd is not None: + object.__setattr__(self, "cwd", Path(self.cwd)) + + +@dataclass(frozen=True, slots=True, init=False) +class JsonSchema: + schema: FrozenJsonObject + + def __init__(self, schema: Mapping[str, object]) -> None: + object.__setattr__( + self, + "schema", + freeze_json_object(schema, where="schema"), + ) diff --git a/src/droid_sdk/_high_level/discovery.py b/src/droid_sdk/_high_level/discovery.py new file mode 100644 index 0000000..e03e155 --- /dev/null +++ b/src/droid_sdk/_high_level/discovery.py @@ -0,0 +1,178 @@ +"""Deterministic local saved-session discovery.""" + +from __future__ import annotations + +import asyncio +import contextlib +import json +import os +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, cast + +from droid_sdk._high_level.config import SavedSession + + +def _sessions_root() -> Path: + return Path.home() / ".factory" / "sessions" + + +def _project_directory_name(cwd: Path) -> str: + try: + normalized = cwd.expanduser().resolve(strict=True) + except OSError: + normalized = cwd.expanduser().resolve(strict=False) + value = str(normalized).rstrip("/\\") + if os.name == "nt": + drive, tail = os.path.splitdrive(value) + value = f"{drive.rstrip(':')}{tail}" + return "-" + value.lstrip("/\\").replace("\\", "-").replace("/", "-") + + +async def list_sessions( + *, + cwd: str | Path | None = None, + all_workspaces: bool = False, + limit: int | None = None, +) -> list[SavedSession]: + """Read local session metadata without starting Droid.""" + if limit is not None and limit < 0: + raise ValueError("limit must be non-negative") + selected_cwd = Path(Path.cwd() if cwd is None else cwd).resolve() + root = _sessions_root() + return await asyncio.to_thread( + _list_sessions_sync, + root, + selected_cwd, + all_workspaces, + limit, + ) + + +def _list_sessions_sync( + root: Path, + cwd: Path, + all_workspaces: bool, + limit: int | None, +) -> list[SavedSession]: + favorites = _favorites(root) + directories = [root] + if all_workspaces: + with contextlib.suppress(OSError): + directories.extend( + item + for item in root.iterdir() + if item.is_dir() and item.name.startswith("-") + ) + else: + directories.append(root / _project_directory_name(cwd)) + + candidates: list[tuple[int, str, Path, bool]] = [] + for directory in directories: + try: + for path in directory.iterdir(): + if path.is_file() and path.suffix == ".jsonl": + try: + stat = path.stat() + except OSError: + continue + candidates.append( + ( + stat.st_mtime_ns, + path.stem, + path, + directory == root, + ) + ) + except OSError: + continue + candidates.sort(key=lambda item: (-item[0], item[1], str(item[2]))) + + by_id: dict[str, SavedSession] = {} + for _, session_id, path, legacy in candidates: + parsed = _parse_session( + path, + session_id, + favorites, + required_cwd=None if all_workspaces or not legacy else cwd, + ) + if parsed is None: + continue + previous = by_id.get(parsed.id) + if previous is None or parsed.modified_at > previous.modified_at: + by_id[parsed.id] = parsed + values = sorted( + by_id.values(), + key=lambda item: (-item.modified_at.timestamp(), item.id), + ) + return values if limit is None else values[:limit] + + +def _favorites(root: Path) -> set[str]: + try: + value = json.loads((root / ".favorites").read_text(encoding="utf-8")) + except (OSError, ValueError): + return set() + return ( + {item for item in cast("list[object]", value) if isinstance(item, str)} + if isinstance(value, list) + else set() + ) + + +def _parse_session( + path: Path, + session_id: str, + favorites: set[str], + *, + required_cwd: Path | None, +) -> SavedSession | None: + try: + stat = path.stat() + with path.open("rb") as handle: + first = handle.readline() + if not first.strip(): + return None + summary = json.loads(first) + count = sum(1 for line in handle if line.strip()) + if not isinstance(summary, dict): + return None + summary_dict = cast("dict[str, Any]", summary) + if summary_dict.get("type") != "session_start": + return None + title = summary_dict.get("title") + if not isinstance(title, str): + return None + raw_cwd = summary_dict.get("cwd") + parsed_cwd = Path(raw_cwd).resolve() if isinstance(raw_cwd, str) else None + if required_cwd is not None and parsed_cwd != required_cwd: + return None + settings_path = path.with_name(f"{session_id}.settings.json") + try: + settings = json.loads(settings_path.read_text(encoding="utf-8")) + if isinstance(settings, dict): + settings_object = cast("dict[str, object]", settings) + if settings_object.get("archivedAt"): + return None + except (OSError, ValueError): + pass + created = getattr(stat, "st_birthtime", stat.st_ctime) + return SavedSession( + id=session_id, + title=title, + owner=( + summary_dict["owner"] + if isinstance(summary_dict.get("owner"), str) + else "" + ), + message_count=count, + modified_at=datetime.fromtimestamp(stat.st_mtime, timezone.utc), + created_at=datetime.fromtimestamp(created, timezone.utc), + cwd=parsed_cwd, + is_favorite=session_id in favorites, + ) + except (OSError, ValueError, TypeError): + return None + + +__all__ = ["list_sessions"] diff --git a/src/droid_sdk/_high_level/enums.py b/src/droid_sdk/_high_level/enums.py new file mode 100644 index 0000000..9b02173 --- /dev/null +++ b/src/droid_sdk/_high_level/enums.py @@ -0,0 +1,154 @@ +"""Enums on the stable high-level SDK surface.""" + +from __future__ import annotations + +from enum import Enum + + +class Mode(str, Enum): + AUTO = "auto" + SPEC = "spec" + + +class Autonomy(str, Enum): + OFF = "off" + LOW = "low" + MEDIUM = "medium" + HIGH = "high" + + +class ReasoningEffort(str, Enum): + NONE = "none" + DYNAMIC = "dynamic" + OFF = "off" + MINIMAL = "minimal" + LOW = "low" + MEDIUM = "medium" + HIGH = "high" + EXTRA_HIGH = "xhigh" + MAX = "max" + + +class ToolConfirmationOutcome(str, Enum): + PROCEED_ONCE = "proceed_once" + PROCEED_ALWAYS = "proceed_always" + PROCEED_ALWAYS_EXACT_PATH = "proceed_always_file" + PROCEED_AUTO_RUN = "proceed_auto_run" + PROCEED_AUTO_RUN_LOW = "proceed_auto_run_low" + PROCEED_AUTO_RUN_MEDIUM = "proceed_auto_run_medium" + PROCEED_AUTO_RUN_HIGH = "proceed_auto_run_high" + PROCEED_NEW_SESSION = "proceed_new_session" + PROCEED_NEW_SESSION_LOW = "proceed_new_session_low" + PROCEED_NEW_SESSION_MEDIUM = "proceed_new_session_medium" + PROCEED_NEW_SESSION_HIGH = "proceed_new_session_high" + PROCEED_EDIT = "proceed_edit" + PROCEED_ALWAYS_TOOLS = "proceed_always_tools" + PROCEED_ALWAYS_SERVER = "proceed_always_server" + CANCEL = "cancel" + + +class ToolConfirmationType(str, Enum): + EDIT = "edit" + EXECUTE = "exec" + CREATE = "create" + ASK_USER = "ask_user" + EXIT_SPEC_MODE = "exit_spec_mode" + APPLY_PATCH = "apply_patch" + MCP_TOOL = "mcp_tool" + SANDBOX_VIOLATION = "sandbox_violation" + DROID_SHIELD_VIOLATION = "droid_shield_violation" + + +class WorkingState(str, Enum): + IDLE = "idle" + THINKING = "thinking" + STREAMING_ASSISTANT_MESSAGE = "streaming_assistant_message" + WAITING_FOR_TOOL_CONFIRMATION = "waiting_for_tool_confirmation" + EXECUTING_TOOL = "executing_tool" + COMPACTING_CONVERSATION = "compacting_conversation" + + +class ContextAccuracy(str, Enum): + EXACT = "exact" + ESTIMATED = "estimated" + + +class ToolCategory(str, Enum): + READ = "read" + EDIT = "edit" + EXECUTE = "execute" + OTHER = "other" + + +class McpServerType(str, Enum): + STDIO = "stdio" + HTTP = "http" + SSE = "sse" + + +class McpServerStatus(str, Enum): + CONNECTING = "connecting" + CONNECTED = "connected" + DISCONNECTED = "disconnected" + FAILED = "failed" + DISABLED = "disabled" + + +class McpAuthOutcome(str, Enum): + SUCCESS = "success" + CANCELLED = "cancelled" + FAILED = "failed" + + +class ErrorType(str, Enum): + CONNECTION_ERROR = "ConnectionError" + PROTOCOL_ERROR = "ProtocolError" + SESSION_ERROR = "SessionError" + TIMEOUT_ERROR = "TimeoutError" + DROID_CLIENT_ERROR = "DroidClientError" + PROCESS_EXIT_ERROR = "ProcessExitError" + ERROR = "Error" + + +class SessionPlatform(str, Enum): + SLACK = "slack" + WEB = "web" + API = "api" + SESSIONS_API = "sessions_api" + JIRA = "jira" + LINEAR = "linear" + MICROSOFT_TEAMS = "microsoft-teams" + READINESS_REMEDIATION = "readiness-remediation" + READINESS_EVALUATION = "readiness-evaluation" + AUTOMATION = "automation" + WIKI_GENERATION = "wiki-generation" + WIKI_CI_SETUP = "wiki-ci-setup" + TUI = "tui" + DESKTOP = "desktop" + ACP = "acp" + UNKNOWN = "unknown" + + +class SandboxOperation(str, Enum): + READ = "read" + WRITE = "write" + NETWORK = "network" + TOOL = "tool" + + +class SandboxViolationType(str, Enum): + FILESYSTEM_READ = "filesystem-read" + FILESYSTEM_WRITE = "filesystem-write" + NETWORK = "network" + TOOL = "tool" + + +class SandboxViolationReason(str, Enum): + DENY_LIST = "deny-list" + NOT_ALLOWED = "not-allowed" + + +class OAuthTokenEndpointAuthMethod(str, Enum): + NONE = "none" + CLIENT_SECRET_BASIC = "client_secret_basic" + CLIENT_SECRET_POST = "client_secret_post" diff --git a/src/droid_sdk/_high_level/extensions.py b/src/droid_sdk/_high_level/extensions.py new file mode 100644 index 0000000..203ee7a --- /dev/null +++ b/src/droid_sdk/_high_level/extensions.py @@ -0,0 +1,363 @@ +"""Immutable tool, skill, MCP, and lifecycle result values.""" + +# ruff: noqa: TC001, TC003 + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Literal, TypeAlias + +from droid_sdk._high_level._immutable import ( + freeze_json_object, + freeze_secret_mapping, +) +from droid_sdk._high_level.enums import ( + Autonomy, + McpServerStatus, + McpServerType, + Mode, + OAuthTokenEndpointAuthMethod, + ToolCategory, +) + +if TYPE_CHECKING: + from droid_sdk._high_level.session import Session + + +def _empty_str_mapping() -> Mapping[str, str]: + return {} + + +@dataclass(frozen=True, slots=True) +class ToolInfo: + id: str + display_name: str + description: str + category: ToolCategory + default_allowed: bool + allowed: bool + + +@dataclass(frozen=True, slots=True) +class ListToolsOptions: + model: str | None = None + mode: Mode | None = None + autonomy: Autonomy | None = None + spec_model: str | None = None + additional_tools: set[str] | frozenset[str] | None = None + enabled_tools: set[str] | frozenset[str] | None = None + disabled_tools: set[str] | frozenset[str] | None = None + restrict_tools: set[str] | frozenset[str] | None = None + skip_permissions_unsafe: bool | None = None + + def __post_init__(self) -> None: + for name in ( + "additional_tools", + "enabled_tools", + "disabled_tools", + "restrict_tools", + ): + value = getattr(self, name) + if value is not None: + object.__setattr__(self, name, frozenset(value)) + + +@dataclass(frozen=True, slots=True) +class SkillResource: + name: str + path: str + type: Literal["reference", "asset"] + + +@dataclass(frozen=True, slots=True) +class SkillInfo: + name: str + location: Literal["project", "personal", "builtin", "automation"] + file_path: str + description: str | None = None + enabled: bool | None = None + user_invocable: bool | None = None + version: str | None = None + content: str | None = None + resources: Sequence[SkillResource] = () + disabled_by: Mapping[str, object] | None = None + + def __post_init__(self) -> None: + object.__setattr__(self, "resources", tuple(self.resources)) + if self.disabled_by is not None: + object.__setattr__( + self, + "disabled_by", + freeze_json_object(self.disabled_by, where="disabled_by"), + ) + + +@dataclass(frozen=True, slots=True) +class SkillsResult: + skills: Sequence[SkillInfo] + project_available: bool | None = None + + def __post_init__(self) -> None: + object.__setattr__(self, "skills", tuple(self.skills)) + + +@dataclass(frozen=True, slots=True) +class SkillMutationResult: + success: bool + + +@dataclass(frozen=True, slots=True) +class HttpHeader: + name: str + value: str = field(repr=False) + + +@dataclass(frozen=True, slots=True) +class McpOAuthOptions: + scopes: Sequence[str] | None = None + resource: str | Literal[False] | None = None + authorization_server_issuer: str | None = None + client_metadata_url: str | None = None + client_id: str | None = None + client_secret: str | None = field(default=None, repr=False) + callback_port: int | None = None + token_endpoint_auth_method: OAuthTokenEndpointAuthMethod | None = None + + def __post_init__(self) -> None: + if self.scopes is not None: + object.__setattr__(self, "scopes", tuple(self.scopes)) + if self.callback_port is not None and not 1 <= self.callback_port <= 65535: + raise ValueError("callback_port must be between 1 and 65535") + + +@dataclass(frozen=True, slots=True) +class StdioMcpServerConfig: + name: str + command: str + args: Sequence[str] = () + env: Mapping[str, str] = field(default_factory=_empty_str_mapping) + + def __post_init__(self) -> None: + object.__setattr__(self, "args", tuple(self.args)) + object.__setattr__(self, "env", freeze_secret_mapping(self.env)) + + +@dataclass(frozen=True, slots=True) +class HttpMcpServerConfig: + name: str + url: str + headers: Sequence[HttpHeader] = () + oauth: McpOAuthOptions | Literal[False] | None = None + + def __post_init__(self) -> None: + object.__setattr__(self, "headers", tuple(self.headers)) + + +@dataclass(frozen=True, slots=True) +class SseMcpServerConfig: + name: str + url: str + headers: Sequence[HttpHeader] = () + oauth: McpOAuthOptions | Literal[False] | None = None + + def __post_init__(self) -> None: + object.__setattr__(self, "headers", tuple(self.headers)) + + +@dataclass(frozen=True, slots=True) +class DroidTool: + name: str + description: str + input_schema: Mapping[str, object] + handler: Callable[..., object] = field(repr=False, compare=False) + output_schema: Mapping[str, object] | None = None + + def __post_init__(self) -> None: + object.__setattr__( + self, + "input_schema", + freeze_json_object(self.input_schema, where="input_schema"), + ) + if self.output_schema is not None: + object.__setattr__( + self, + "output_schema", + freeze_json_object(self.output_schema, where="output_schema"), + ) + + +@dataclass(frozen=True, slots=True) +class SdkMcpServer: + name: str + version: str + tools: Sequence[DroidTool] + _runtime: object | None = field( + default=None, + init=False, + repr=False, + compare=False, + ) + _lifecycle: object | None = field( + default=None, + init=False, + repr=False, + compare=False, + ) + + def __post_init__(self) -> None: + object.__setattr__(self, "tools", tuple(self.tools)) + + @property + def config(self) -> HttpMcpServerConfig | None: + from droid_sdk.mcp import sdk_server_config + + return sdk_server_config(self) + + async def start(self) -> HttpMcpServerConfig: + from droid_sdk.mcp import start_sdk_server + + return await start_sdk_server(self) + + async def close(self) -> None: + from droid_sdk.mcp import close_sdk_server + + await close_sdk_server(self) + + +McpServerConfig: TypeAlias = ( + StdioMcpServerConfig | HttpMcpServerConfig | SseMcpServerConfig | SdkMcpServer +) + + +@dataclass(frozen=True, slots=True) +class ToolResponse: + content: str + is_error: bool = False + structured_content: Mapping[str, object] | None = None + + def __post_init__(self) -> None: + if self.structured_content is not None: + object.__setattr__( + self, + "structured_content", + freeze_json_object(self.structured_content, where="structured_content"), + ) + + +@dataclass(frozen=True, slots=True) +class McpConfigError: + path: str + message: str + + +@dataclass(frozen=True, slots=True) +class McpStatusSummary: + total: int + connected: int + connecting: int + failed: int + disabled: int | None = None + config_error: McpConfigError | None = None + + +@dataclass(frozen=True, slots=True) +class McpServerStatusInfo: + name: str + status: McpServerStatus + source: str + is_managed: bool + server_type: McpServerType + error: str | None = None + tool_count: int | None = None + has_auth_tokens: bool | None = None + requires_auth: bool | None = None + pending_auth_url: str | None = None + pending_auth_message: str | None = None + pending_auth_state: str | None = None + + +@dataclass(frozen=True, slots=True) +class McpServersResult: + servers: Sequence[McpServerStatusInfo] + summary: McpStatusSummary + + def __post_init__(self) -> None: + object.__setattr__(self, "servers", tuple(self.servers)) + + +@dataclass(frozen=True, slots=True) +class McpToolInputSchema: + type: str | None = None + properties: Mapping[str, object] | None = None + required: Sequence[str] | None = None + + def __post_init__(self) -> None: + if self.properties is not None: + object.__setattr__( + self, + "properties", + freeze_json_object(self.properties, where="properties"), + ) + if self.required is not None: + object.__setattr__(self, "required", tuple(self.required)) + + +@dataclass(frozen=True, slots=True) +class McpToolInfo: + server_name: str + name: str + is_enabled: bool + description: str | None = None + is_read_only: bool | None = None + input_schema: McpToolInputSchema | None = None + + +@dataclass(frozen=True, slots=True) +class McpMutationResult: + success: bool + + +@dataclass(frozen=True, slots=True) +class RewindFileSnapshot: + file_path: str + content_hash: str + size: int + + +@dataclass(frozen=True, slots=True) +class RewindFileCreation: + file_path: str + + +@dataclass(frozen=True, slots=True) +class RewindEvictedFile: + file_path: str + reason: str + + +@dataclass(frozen=True, slots=True) +class RewindInfo: + available_files: Sequence[RewindFileSnapshot] + created_files: Sequence[RewindFileCreation] + evicted_files: Sequence[RewindEvictedFile] + + def __post_init__(self) -> None: + object.__setattr__(self, "available_files", tuple(self.available_files)) + object.__setattr__(self, "created_files", tuple(self.created_files)) + object.__setattr__(self, "evicted_files", tuple(self.evicted_files)) + + +@dataclass(frozen=True, slots=True) +class CompactOutcome: + session: Session + removed_count: int + + +@dataclass(frozen=True, slots=True) +class RewindOutcome: + session: Session + restored_count: int + deleted_count: int + failed_restore_count: int + failed_delete_count: int diff --git a/src/droid_sdk/_high_level/interaction_adapter.py b/src/droid_sdk/_high_level/interaction_adapter.py new file mode 100644 index 0000000..1b30b11 --- /dev/null +++ b/src/droid_sdk/_high_level/interaction_adapter.py @@ -0,0 +1,330 @@ +"""Adapters between canonical server requests and public interaction values.""" + +from __future__ import annotations + +import asyncio +import contextlib +import inspect +from collections.abc import Callable, Mapping +from datetime import datetime, timezone +from typing import Any, cast + +from droid_sdk._high_level.enums import ( + ErrorType, + SandboxOperation, + SandboxViolationReason, + SandboxViolationType, + ToolConfirmationOutcome, +) +from droid_sdk._high_level.interactions import ( + ApplyPatchAction, + ApplyPatchFile, + AskUserAction, + AskUserParseError, + CreateFile, + DroidShieldViolationAction, + EditAction, + ExecuteAction, + ExitSpecModeAction, + InteractionHandlers, + McpToolAction, + PermissionAction, + PermissionOption, + PermissionRequest, + PermissionResponse, + Question, + QuestionRequest, + QuestionResponse, + SandboxViolationAction, +) +from droid_sdk._high_level.messages import ErrorEvent, ToolUseBlock +from droid_sdk.schemas.cli import ( + ApplyPatchToolConfirmationDetails, + AskUserConfirmationDetails, + AskUserRequestParams, + CreateToolConfirmationDetails, + DroidShieldViolationConfirmationDetails, + EditToolConfirmationDetails, + ExecuteToolConfirmationDetails, + ExitSpecModeConfirmationDetails, + McpToolConfirmationDetails, + RequestPermissionRequestParams, + SandboxViolationConfirmationDetails, +) + +ErrorSink = Callable[[ErrorEvent], None] + + +def _permission_response(value: object) -> PermissionResponse: + if not isinstance(value, PermissionResponse): + raise TypeError("invalid permission response") + return value + + +def _question_response(value: object) -> QuestionResponse: + if not isinstance(value, QuestionResponse): + raise TypeError("invalid question response") + return value + + +def _tool_use(value: Any) -> ToolUseBlock: + return ToolUseBlock( + id=value.id, + name=value.name, + input=value.input, + thought_signature=value.thought_signature, + ) + + +def _permission_action(value: Any) -> PermissionAction: + tool_use = _tool_use(value.tool_use) + details = value.details.root + if isinstance(details, EditToolConfirmationDetails): + return EditAction( + tool_use=tool_use, + file_path=details.file_path, + file_name=details.file_name, + old_content=details.old_content, + new_content=details.new_content, + ) + if isinstance(details, ExecuteToolConfirmationDetails): + return ExecuteAction( + tool_use=tool_use, + full_command=details.full_command, + command=details.command, + extracted_commands=details.extracted_commands, + impact_level=details.impact_level, + risk_level_reason=details.risk_level_reason, + ) + if isinstance(details, CreateToolConfirmationDetails): + return CreateFile( + tool_use=tool_use, + file_path=details.file_path, + file_name=details.file_name, + content=details.content, + ) + if isinstance(details, AskUserConfirmationDetails): + parsed = details.parsed + return AskUserAction( + tool_use=tool_use, + questionnaire=details.questionnaire, + questions=( + () + if parsed is None + else tuple( + Question( + index=question.index, + topic=question.topic, + question=question.question, + options=question.options, + multi_select=question.multi_select, + ) + for question in parsed.questions + ) + ), + parse_error=( + None + if details.parse_error is None + else AskUserParseError( + message=details.parse_error.message, + line=details.parse_error.line, + ) + ), + ) + if isinstance(details, ExitSpecModeConfirmationDetails): + return ExitSpecModeAction( + tool_use=tool_use, + plan=details.plan, + title=details.title, + ) + if isinstance(details, ApplyPatchToolConfirmationDetails): + files = None + if details.files is not None: + files = tuple( + ApplyPatchFile( + file_path=str(file["filePath"]), + file_name=str(file["fileName"]), + operation=file["operation"], + move_to=cast("str | None", file.get("moveTo")), + old_content=cast("str | None", file.get("oldContent")), + new_content=cast("str | None", file.get("newContent")), + ) + for file in details.files + ) + return ApplyPatchAction( + tool_use=tool_use, + file_path=details.file_path, + file_name=details.file_name, + patch_content=details.patch_content, + old_content=details.old_content, + new_content=details.new_content, + files=files, + ) + if isinstance(details, McpToolConfirmationDetails): + return McpToolAction( + tool_use=tool_use, + tool_name=details.tool_name, + impact_level=details.impact_level, + server_name=details.server_name, + actual_tool_name=details.actual_tool_name, + ) + if isinstance(details, SandboxViolationConfirmationDetails): + return SandboxViolationAction( + tool_use=tool_use, + violating_tool_name=details.violating_tool_name, + target=details.target, + operation=SandboxOperation(details.operation_type.value), + violation_type=SandboxViolationType(details.violation_type.value), + reason=details.reason, + is_org_deny=details.is_org_deny, + violation_reason=( + None + if details.violation_reason is None + else SandboxViolationReason(details.violation_reason.value) + ), + ) + if isinstance(details, DroidShieldViolationConfirmationDetails): + return DroidShieldViolationAction( + tool_use=tool_use, + command=details.command, + reason=details.reason, + ) + raise ValueError("unsupported permission action") + + +def permission_request_from_wire( + params: RequestPermissionRequestParams | Mapping[str, object], +) -> PermissionRequest: + parsed = RequestPermissionRequestParams.model_validate(params) + return PermissionRequest( + actions=tuple(_permission_action(item) for item in parsed.tool_uses), + options=tuple( + PermissionOption( + label=option.label, + value=ToolConfirmationOutcome(option.value.value), + ) + for option in parsed.options + ), + associated_session_ids=parsed.associated_session_ids or (), + ) + + +def question_request_from_wire( + params: AskUserRequestParams | Mapping[str, object], +) -> QuestionRequest: + parsed = AskUserRequestParams.model_validate(params) + return QuestionRequest( + tool_call_id=parsed.tool_call_id, + questions=tuple( + Question( + index=question.index, + topic=question.topic, + question=question.question, + options=question.options, + multi_select=question.multi_select, + ) + for question in parsed.questions + ), + ) + + +class InteractionDispatcher: + """Invoke public handlers and always return a safe wire response.""" + + def __init__( + self, + handlers: InteractionHandlers | None = None, + *, + error_sink: ErrorSink | None = None, + ) -> None: + self.handlers = handlers or InteractionHandlers() + self.error_sink = error_sink + + def _report(self, interaction: str) -> None: + if self.error_sink is not None: + with contextlib.suppress(Exception): + self.error_sink( + ErrorEvent( + message=f"{interaction} interaction handler failed", + error_type=ErrorType.DROID_CLIENT_ERROR, + timestamp=datetime.now(timezone.utc), + ) + ) + + async def handle_permission(self, raw: Mapping[str, object]) -> dict[str, object]: + fallback: dict[str, object] = {"selectedOption": "cancel"} + try: + request = permission_request_from_wire(raw) + handler = self.handlers.on_permission + if handler is None: + raise ValueError("missing permission handler") + value = handler(request) + if inspect.isawaitable(value): + value = await value + value = _permission_response(value) + offered = {option.value for option in request.options} + if value.selected_option not in offered: + raise ValueError("permission option was not offered") + if ( + value.selected_option is ToolConfirmationOutcome.PROCEED_EDIT + and value.edited_spec_content is None + ): + raise ValueError("edited spec content is required") + result: dict[str, object] = {"selectedOption": value.selected_option.value} + if value.comment is not None: + result["comment"] = value.comment + if value.edited_spec_content is not None: + result["editedSpecContent"] = value.edited_spec_content + return result + except asyncio.CancelledError: + raise + except Exception: + self._report("Permission") + return fallback + + async def handle_question(self, raw: Mapping[str, object]) -> dict[str, object]: + fallback: dict[str, object] = {"cancelled": True, "answers": []} + try: + request = question_request_from_wire(raw) + handler = self.handlers.on_question + if handler is None: + raise ValueError("missing question handler") + value = handler(request) + if inspect.isawaitable(value): + value = await value + value = _question_response(value) + expected = { + (question.index, question.question) for question in request.questions + } + if value.cancelled and value.answers: + raise ValueError("cancelled response cannot contain answers") + if any( + (answer.index, answer.question) not in expected + for answer in value.answers + ): + raise ValueError("question answer does not match request") + if len({answer.index for answer in value.answers}) != len(value.answers): + raise ValueError("duplicate question answer") + return { + "cancelled": value.cancelled, + "answers": [ + { + "index": answer.index, + "question": answer.question, + "answer": answer.answer, + } + for answer in value.answers + ], + } + except asyncio.CancelledError: + raise + except Exception: + self._report("Question") + return fallback + + +__all__ = [ + "InteractionDispatcher", + "permission_request_from_wire", + "question_request_from_wire", +] diff --git a/src/droid_sdk/_high_level/interactions.py b/src/droid_sdk/_high_level/interactions.py new file mode 100644 index 0000000..4d6162f --- /dev/null +++ b/src/droid_sdk/_high_level/interactions.py @@ -0,0 +1,301 @@ +"""Immutable interaction request and response values.""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable, Sequence +from dataclasses import dataclass, field +from typing import Literal, TypeAlias + +from droid_sdk._high_level.enums import ( + SandboxOperation, + SandboxViolationReason, + SandboxViolationType, + ToolConfirmationOutcome, + ToolConfirmationType, +) +from droid_sdk._high_level.messages import ToolUseBlock # noqa: TC001 + + +@dataclass(frozen=True, slots=True) +class PermissionOption: + label: str + value: ToolConfirmationOutcome + + +@dataclass(frozen=True, slots=True) +class EditAction: + tool_use: ToolUseBlock + file_path: str + file_name: str + old_content: str | None = None + new_content: str | None = None + confirmation_type: Literal[ToolConfirmationType.EDIT] = field( + default=ToolConfirmationType.EDIT, init=False + ) + + +@dataclass(frozen=True, slots=True) +class ExecuteAction: + tool_use: ToolUseBlock + full_command: str + command: str + extracted_commands: Sequence[str] | None = None + impact_level: str | None = None + risk_level_reason: str | None = None + confirmation_type: Literal[ToolConfirmationType.EXECUTE] = field( + default=ToolConfirmationType.EXECUTE, init=False + ) + + def __post_init__(self) -> None: + if self.extracted_commands is not None: + object.__setattr__( + self, "extracted_commands", tuple(self.extracted_commands) + ) + + +@dataclass(frozen=True, slots=True) +class CreateFile: + tool_use: ToolUseBlock + file_path: str + file_name: str + content: str + confirmation_type: Literal[ToolConfirmationType.CREATE] = field( + default=ToolConfirmationType.CREATE, init=False + ) + + +@dataclass(frozen=True, slots=True) +class AskUserParseError: + message: str + line: int | None = None + + +@dataclass(frozen=True, slots=True) +class AskUserAction: + tool_use: ToolUseBlock + questionnaire: str + questions: Sequence[Question] = () + parse_error: AskUserParseError | None = None + confirmation_type: Literal[ToolConfirmationType.ASK_USER] = field( + default=ToolConfirmationType.ASK_USER, init=False + ) + + def __post_init__(self) -> None: + object.__setattr__(self, "questions", tuple(self.questions)) + + +@dataclass(frozen=True, slots=True) +class ExitSpecModeAction: + tool_use: ToolUseBlock + plan: str + title: str | None = None + confirmation_type: Literal[ToolConfirmationType.EXIT_SPEC_MODE] = field( + default=ToolConfirmationType.EXIT_SPEC_MODE, init=False + ) + + +@dataclass(frozen=True, slots=True) +class ApplyPatchAction: + tool_use: ToolUseBlock + file_path: str + file_name: str + patch_content: str + old_content: str | None = None + new_content: str | None = None + files: Sequence[ApplyPatchFile] | None = None + confirmation_type: Literal[ToolConfirmationType.APPLY_PATCH] = field( + default=ToolConfirmationType.APPLY_PATCH, init=False + ) + + def __post_init__(self) -> None: + if self.files is not None: + object.__setattr__(self, "files", tuple(self.files)) + + +@dataclass(frozen=True, slots=True) +class ApplyPatchFile: + file_path: str + file_name: str + operation: Literal["create", "update", "delete"] + move_to: str | None = None + old_content: str | None = None + new_content: str | None = None + + +@dataclass(frozen=True, slots=True) +class McpToolAction: + tool_use: ToolUseBlock + tool_name: str + impact_level: str + server_name: str | None = None + actual_tool_name: str | None = None + confirmation_type: Literal[ToolConfirmationType.MCP_TOOL] = field( + default=ToolConfirmationType.MCP_TOOL, init=False + ) + + +@dataclass(frozen=True, slots=True) +class SandboxViolationAction: + tool_use: ToolUseBlock + violating_tool_name: str + target: str + operation: SandboxOperation + violation_type: SandboxViolationType + reason: str + is_org_deny: bool + violation_reason: SandboxViolationReason | None = None + confirmation_type: Literal[ToolConfirmationType.SANDBOX_VIOLATION] = field( + default=ToolConfirmationType.SANDBOX_VIOLATION, init=False + ) + + +@dataclass(frozen=True, slots=True) +class Plan: + text: str + title: str | None = None + + +@dataclass(frozen=True, slots=True) +class DroidShieldViolationAction: + tool_use: ToolUseBlock + command: str + reason: str + confirmation_type: Literal[ToolConfirmationType.DROID_SHIELD_VIOLATION] = field( + default=ToolConfirmationType.DROID_SHIELD_VIOLATION, init=False + ) + + +PermissionAction: TypeAlias = ( + EditAction + | ExecuteAction + | CreateFile + | AskUserAction + | ExitSpecModeAction + | ApplyPatchAction + | McpToolAction + | SandboxViolationAction + | DroidShieldViolationAction +) + + +@dataclass(frozen=True, slots=True) +class PermissionResponse: + selected_option: ToolConfirmationOutcome + comment: str | None = None + edited_spec_content: str | None = None + + def __post_init__(self) -> None: + if ( + self.selected_option is ToolConfirmationOutcome.PROCEED_EDIT + and self.edited_spec_content is None + ): + raise ValueError("edited_spec_content is required for PROCEED_EDIT") + + +@dataclass(frozen=True, slots=True) +class PermissionRequest: + actions: Sequence[PermissionAction] + options: Sequence[PermissionOption] + associated_session_ids: Sequence[str] = () + + def __post_init__(self) -> None: + object.__setattr__(self, "actions", tuple(self.actions)) + object.__setattr__(self, "options", tuple(self.options)) + object.__setattr__( + self, "associated_session_ids", tuple(self.associated_session_ids) + ) + + @property + def plan(self) -> Plan | None: + action = next( + (item for item in self.actions if isinstance(item, ExitSpecModeAction)), + None, + ) + if action is None: + return None + return Plan(text=action.plan, title=action.title) + + def respond( + self, + selected_option: ToolConfirmationOutcome, + *, + comment: str | None = None, + edited_spec_content: str | None = None, + ) -> PermissionResponse: + if selected_option not in {option.value for option in self.options}: + raise ValueError("selected_option was not offered by Droid") + return PermissionResponse( + selected_option=selected_option, + comment=comment, + edited_spec_content=edited_spec_content, + ) + + +@dataclass(frozen=True, slots=True) +class QuestionAnswer: + index: int + question: str + answer: str + + +@dataclass(frozen=True, slots=True) +class Question: + index: int + topic: str + question: str + options: Sequence[str] = () + multi_select: bool | None = None + + def __post_init__(self) -> None: + object.__setattr__(self, "options", tuple(self.options)) + + def answer(self, answer: str) -> QuestionAnswer: + return QuestionAnswer(index=self.index, question=self.question, answer=answer) + + def answer_multiple(self, answers: Sequence[str]) -> QuestionAnswer: + """Create the wire-compatible comma-separated multi-select answer.""" + return self.answer(", ".join(answers)) + + +@dataclass(frozen=True, slots=True) +class QuestionResponse: + cancelled: bool + answers: Sequence[QuestionAnswer] = () + + def __post_init__(self) -> None: + object.__setattr__(self, "answers", tuple(self.answers)) + + +@dataclass(frozen=True, slots=True) +class QuestionRequest: + tool_call_id: str + questions: Sequence[Question] + + def __post_init__(self) -> None: + object.__setattr__(self, "questions", tuple(self.questions)) + + def submit(self, answers: Sequence[QuestionAnswer]) -> QuestionResponse: + submitted = tuple(answers) + expected = {(item.index, item.question) for item in self.questions} + if any((item.index, item.question) not in expected for item in submitted): + raise ValueError("answer does not match a requested question") + if len({item.index for item in submitted}) != len(submitted): + raise ValueError("a question may only be answered once") + return QuestionResponse(cancelled=False, answers=submitted) + + def cancel(self) -> QuestionResponse: + return QuestionResponse(cancelled=True) + + +PermissionHandler: TypeAlias = Callable[ + [PermissionRequest], PermissionResponse | Awaitable[PermissionResponse] +] +QuestionHandler: TypeAlias = Callable[ + [QuestionRequest], QuestionResponse | Awaitable[QuestionResponse] +] + + +@dataclass(frozen=True, slots=True) +class InteractionHandlers: + on_permission: PermissionHandler | None = None + on_question: QuestionHandler | None = None diff --git a/src/droid_sdk/_high_level/messages.py b/src/droid_sdk/_high_level/messages.py new file mode 100644 index 0000000..1804fcf --- /dev/null +++ b/src/droid_sdk/_high_level/messages.py @@ -0,0 +1,535 @@ +"""Immutable complete messages, partial events, and terminal results.""" + +# ruff: noqa: TC001, TC002, TC003 + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from datetime import datetime, timedelta, timezone +from typing import Generic, Literal, TypeAlias, TypeVar + +from pydantic import ValidationError + +from droid_sdk._high_level._immutable import ( + FrozenJsonObject, + FrozenJsonValue, + JsonValue, + freeze_json, + freeze_json_object, +) +from droid_sdk._high_level.attachments import ( + Base64ImageSource, + DocumentSource, +) +from droid_sdk._high_level.config import SessionSettingsUpdate +from droid_sdk._high_level.enums import ( + ContextAccuracy, + ErrorType, + McpAuthOutcome, + ToolConfirmationOutcome, + WorkingState, +) +from droid_sdk._high_level.extensions import McpServerStatusInfo, McpStatusSummary + +T = TypeVar("T") + + +def _aware(value: datetime, name: str) -> None: + if value.tzinfo is None or value.utcoffset() is None: + raise ValueError(f"{name} must be timezone-aware") + + +@dataclass(frozen=True, slots=True) +class TextBlock: + id: str | None = field(default=None, kw_only=True) + text: str + + +@dataclass(frozen=True, slots=True) +class ThinkingBlock: + id: str | None = field(default=None, kw_only=True) + thinking: str + signature: str + signature_provider: str | None = None + duration: timedelta | None = None + + +@dataclass(frozen=True, slots=True) +class RedactedThinkingBlock: + id: str | None = field(default=None, kw_only=True) + data: str + + +@dataclass(frozen=True, slots=True) +class ToolUseBlock: + id: str + name: str + input: Mapping[str, object] + thought_signature: str | None = None + + def __post_init__(self) -> None: + object.__setattr__( + self, "input", freeze_json_object(self.input, where="tool input") + ) + + +@dataclass(frozen=True, slots=True, init=False) +class ToolResultBlock: + id: str | None = field(default=None, kw_only=True) + tool_use_id: str + content: str | Sequence[ToolResultStoredContent] | None = None + is_error: bool | None = None + + def __init__( + self, + tool_use_id: str, + content: str | Sequence[ToolResultContent] | None = None, + is_error: bool | None = None, + *, + id: str | None = None, + ) -> None: + object.__setattr__(self, "id", id) + object.__setattr__(self, "tool_use_id", tool_use_id) + object.__setattr__(self, "is_error", is_error) + if content is None or isinstance(content, str): + object.__setattr__(self, "content", content) + return + object.__setattr__( + self, + "content", + tuple( + item + if isinstance(item, (TextBlock, ImageBlock, DocumentBlock)) + else freeze_json(item, where="tool result block") + for item in content + ), + ) + + +@dataclass(frozen=True, slots=True) +class ImageBlock: + id: str | None = field(default=None, kw_only=True) + source: Base64ImageSource + generated: bool | None = None + + +@dataclass(frozen=True, slots=True) +class DocumentBlock: + id: str | None = field(default=None, kw_only=True) + source: DocumentSource + + +ContentBlock: TypeAlias = ( + TextBlock + | ThinkingBlock + | RedactedThinkingBlock + | ToolUseBlock + | ToolResultBlock + | ImageBlock + | DocumentBlock +) +ToolResultContentBlock: TypeAlias = TextBlock | ImageBlock | DocumentBlock +ToolResultContent: TypeAlias = ToolResultContentBlock | JsonValue +ToolResultStoredContent: TypeAlias = ToolResultContentBlock | FrozenJsonValue + + +@dataclass(frozen=True, slots=True) +class ConversationMessage: + id: str + content: tuple[ContentBlock, ...] + text: str + parent_id: str | None = field(default=None, kw_only=True) + created_at: datetime + updated_at: datetime + + def __post_init__(self) -> None: + object.__setattr__(self, "content", tuple(self.content)) + _aware(self.created_at, "created_at") + _aware(self.updated_at, "updated_at") + + +@dataclass(frozen=True, slots=True) +class UserMessage(ConversationMessage): + pass + + +@dataclass(frozen=True, slots=True) +class AssistantMessage(ConversationMessage): + pass + + +@dataclass(frozen=True, slots=True) +class ToolCall: + name: str + tool_use_id: str + input: Mapping[str, object] + + def __post_init__(self) -> None: + object.__setattr__( + self, "input", freeze_json_object(self.input, where="tool input") + ) + + +@dataclass(frozen=True, slots=True, init=False) +class ToolResult: + tool_use_id: str + tool_name: str + content: str | Sequence[FrozenJsonValue] + is_error: bool + + def __init__( + self, + tool_use_id: str, + tool_name: str, + content: str | Sequence[JsonValue], + is_error: bool, + ) -> None: + object.__setattr__(self, "tool_use_id", tool_use_id) + object.__setattr__(self, "tool_name", tool_name) + object.__setattr__(self, "is_error", is_error) + object.__setattr__( + self, + "content", + content + if isinstance(content, str) + else tuple(freeze_json(item, where="tool result") for item in content), + ) + + +@dataclass(frozen=True, slots=True) +class HookExecution: + hook_id: str + event_name: str | None = None + matcher: str | None = None + tool_call_id: str | None = None + command: str | None = None + timeout: timedelta | None = None + status: Literal["started", "completed", "error"] = "started" + exit_code: int | None = None + stdout: str | None = None + stderr: str | None = None + suppress_output: bool | None = None + + +@dataclass(frozen=True, slots=True) +class ErrorEvent: + message: str + error_type: ErrorType + timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) + + def __post_init__(self) -> None: + _aware(self.timestamp, "timestamp") + + +Message: TypeAlias = ( + UserMessage | AssistantMessage | ToolCall | ToolResult | HookExecution | ErrorEvent +) + + +@dataclass(frozen=True, slots=True) +class TextDelta: + message_id: str + block_index: int + text: str + + +@dataclass(frozen=True, slots=True) +class TextComplete: + message_id: str + block_index: int + + +@dataclass(frozen=True, slots=True) +class ThinkingDelta: + message_id: str + block_index: int + text: str + + +@dataclass(frozen=True, slots=True) +class ThinkingComplete: + message_id: str + block_index: int + duration: timedelta | None = None + + +@dataclass(frozen=True, slots=True) +class ToolCallDelta: + tool_use: ToolUseBlock + + +@dataclass(frozen=True, slots=True) +class ToolProgressUpdate: + type: Literal["tool_call", "tool_result", "error", "status", "message"] + tool_name: str | None = None + status: str | None = None + details: str | None = None + text: str | None = None + error: str | None = None + timestamp: datetime | None = None + parameters: Mapping[str, object] | None = None + value_snippet: str | None = None + terminal_id: str | None = None + full_output: str | None = None + subagent_session_id: str | None = None + + def __post_init__(self) -> None: + if self.timestamp is not None: + _aware(self.timestamp, "timestamp") + if self.parameters is not None: + object.__setattr__( + self, + "parameters", + freeze_json_object(self.parameters, where="tool progress parameters"), + ) + + +@dataclass(frozen=True, slots=True) +class ToolProgress: + tool_use_id: str + tool_name: str + content: str + update: ToolProgressUpdate + + +@dataclass(frozen=True, slots=True) +class Usage: + input_tokens: int + output_tokens: int + cache_creation_tokens: int + cache_read_tokens: int + thinking_tokens: int + factory_credits: float | None = None + + +@dataclass(frozen=True, slots=True) +class TokenUsageUpdate(Usage): + pass + + +@dataclass(frozen=True, slots=True) +class ContextUsage: + used: int + remaining: int + limit: int + accuracy: ContextAccuracy + updated_at: datetime + + def __post_init__(self) -> None: + _aware(self.updated_at, "updated_at") + + +@dataclass(frozen=True, slots=True) +class WorkingStateChanged: + state: WorkingState + + +@dataclass(frozen=True, slots=True) +class PermissionResolved: + request_id: str + tool_use_ids: Sequence[str] + selected_option: ToolConfirmationOutcome + + def __post_init__(self) -> None: + object.__setattr__(self, "tool_use_ids", tuple(self.tool_use_ids)) + + +@dataclass(frozen=True, slots=True) +class SettingsUpdated: + settings: SessionSettingsUpdate + + +@dataclass(frozen=True, slots=True) +class SessionTitleUpdated: + title: str + + +@dataclass(frozen=True, slots=True) +class SessionWorkingDirectoryChanged: + cwd: str + + +@dataclass(frozen=True, slots=True) +class McpStatusChanged: + servers: Sequence[McpServerStatusInfo] + summary: McpStatusSummary + + def __post_init__(self) -> None: + object.__setattr__(self, "servers", tuple(self.servers)) + + +@dataclass(frozen=True, slots=True) +class McpAuthRequired: + server_name: str + auth_url: str + message: str + state: str + + +@dataclass(frozen=True, slots=True) +class McpAuthCompleted: + server_name: str + outcome: McpAuthOutcome + message: str + + +@dataclass(frozen=True, slots=True, init=False) +class StructuredOutputError: + code: str + message: str + details: FrozenJsonValue | None = None + + def __init__( + self, + code: str, + message: str, + details: JsonValue | None = None, + ) -> None: + object.__setattr__(self, "code", code) + object.__setattr__(self, "message", message) + object.__setattr__( + self, + "details", + None if details is None else freeze_json(details, where="details"), + ) + + +def _freeze_structured_output( + value: Mapping[str, object] | None, +) -> FrozenJsonObject | None: + if value is None: + return None + return freeze_json_object(value, where="structured_output") + + +@dataclass(frozen=True, slots=True) +class RunResult(Generic[T]): + """Runtime base class shared by all terminal result dataclasses.""" + + subtype: Literal[ + "success", + "interrupted", + "error_during_execution", + "error_structured_output", + ] = field(init=False) + text: str = field(init=False) + messages: tuple[Message, ...] = field(init=False) + usage: Usage | None = field(init=False) + duration: timedelta = field(init=False) + turn_count: int = field(init=False) + session_id: str = field(init=False) + success: bool = field(init=False) + interrupted: bool = field(init=False) + output: T | None = field(init=False) + structured_output: FrozenJsonObject | None = field(init=False) + output_validation_error: ValidationError | None = field(init=False) + structured_output_error: StructuredOutputError | None = field(init=False) + error: ErrorEvent | None = field(init=False) + + def __post_init__(self) -> None: + raise TypeError("RunResult is an abstract terminal result base") + + +@dataclass(frozen=True, slots=True) +class RunSuccess(RunResult[T]): + text: str + messages: tuple[Message, ...] + usage: Usage | None + duration: timedelta + turn_count: int + session_id: str + output: T | None = None + structured_output: FrozenJsonObject | None = None + output_validation_error: ValidationError | None = None + structured_output_error: None = field(default=None, init=False) + error: None = field(default=None, init=False) + subtype: Literal["success"] = field(default="success", init=False) + success: Literal[True] = field(default=True, init=False) + interrupted: Literal[False] = field(default=False, init=False) + + def __post_init__(self) -> None: + object.__setattr__(self, "messages", tuple(self.messages)) + object.__setattr__( + self, + "structured_output", + _freeze_structured_output(self.structured_output), + ) + + +@dataclass(frozen=True, slots=True) +class RunInterrupted(RunResult[T]): + text: str + messages: tuple[Message, ...] + usage: Usage | None + duration: timedelta + turn_count: int + session_id: str + output: T | None = None + structured_output: FrozenJsonObject | None = None + output_validation_error: ValidationError | None = None + structured_output_error: None = field(default=None, init=False) + error: None = field(default=None, init=False) + subtype: Literal["interrupted"] = field(default="interrupted", init=False) + success: Literal[False] = field(default=False, init=False) + interrupted: Literal[True] = field(default=True, init=False) + + def __post_init__(self) -> None: + object.__setattr__(self, "messages", tuple(self.messages)) + object.__setattr__( + self, + "structured_output", + _freeze_structured_output(self.structured_output), + ) + + +@dataclass(frozen=True, slots=True) +class RunFailure(RunResult[T]): + subtype: Literal["error_during_execution", "error_structured_output"] + text: str + messages: tuple[Message, ...] + usage: Usage | None + duration: timedelta + turn_count: int + session_id: str + output: T | None = None + structured_output: FrozenJsonObject | None = None + output_validation_error: ValidationError | None = None + structured_output_error: StructuredOutputError | None = None + error: ErrorEvent | None = None + success: Literal[False] = field(default=False, init=False) + interrupted: Literal[False] = field(default=False, init=False) + + def __post_init__(self) -> None: + if self.subtype not in { + "error_during_execution", + "error_structured_output", + }: + raise ValueError(f"invalid failure subtype: {self.subtype!r}") + object.__setattr__(self, "messages", tuple(self.messages)) + object.__setattr__( + self, + "structured_output", + _freeze_structured_output(self.structured_output), + ) + + +StreamMessage: TypeAlias = Message | RunSuccess[T] | RunInterrupted[T] | RunFailure[T] +StreamEvent: TypeAlias = ( + StreamMessage[T] + | TextDelta + | TextComplete + | ThinkingDelta + | ThinkingComplete + | ToolCallDelta + | ToolProgress + | TokenUsageUpdate + | WorkingStateChanged + | PermissionResolved + | SettingsUpdated + | SessionTitleUpdated + | SessionWorkingDirectoryChanged + | McpStatusChanged + | McpAuthRequired + | McpAuthCompleted +) diff --git a/src/droid_sdk/_high_level/output.py b/src/droid_sdk/_high_level/output.py new file mode 100644 index 0000000..fa5d883 --- /dev/null +++ b/src/droid_sdk/_high_level/output.py @@ -0,0 +1,116 @@ +"""Structured-output preparation and local adaptation.""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Generic, TypeVar, cast, overload + +from pydantic import BaseModel, ValidationError + +from droid_sdk._high_level._immutable import ( + FrozenJsonObject, + JsonObject, + freeze_json_object, + thaw_json, +) +from droid_sdk._high_level.config import JsonSchema +from droid_sdk.schemas.client import OutputFormat + +T = TypeVar("T") +T_co = TypeVar("T_co", covariant=True) +ModelT = TypeVar("ModelT", bound=BaseModel) + + +@dataclass(frozen=True, slots=True) +class OutputAdaptation(Generic[T_co]): + output: T_co | None + structured_output: FrozenJsonObject | None + validation_error: ValidationError | None + + +class OutputAdapter(Generic[T_co]): + """Prepared wire schema plus a local output validator.""" + + __slots__ = ("_model", "output_format") + + def __init__( + self, + output_format: OutputFormat | None, + model: type[BaseModel] | None = None, + ) -> None: + self.output_format = output_format + self._model = model + + def adapt(self, raw: object | None) -> OutputAdaptation[T_co]: + if self.output_format is None: + return OutputAdaptation(None, None, None) + + if self._model is not None: + try: + value = self._model.model_validate(raw) + except ValidationError as exc: + return OutputAdaptation(None, _raw_object(raw), exc) + return OutputAdaptation(cast("T_co", value), _raw_object(raw), None) + + raw_value = _validate_json_object(raw) + return OutputAdaptation( + cast("T_co", thaw_json(raw_value)), + raw_value, + None, + ) + + +@overload +def prepare_output_adapter(output: None = None) -> OutputAdapter[None]: ... + + +@overload +def prepare_output_adapter(output: type[ModelT]) -> OutputAdapter[ModelT]: ... + + +@overload +def prepare_output_adapter(output: JsonSchema) -> OutputAdapter[JsonObject]: ... + + +def prepare_output_adapter( + output: object = None, +) -> OutputAdapter[object]: + if output is None: + return OutputAdapter(None) + if isinstance(output, JsonSchema): + _ensure_object_schema(output.schema) + schema: JsonObject = { + key: thaw_json(value) for key, value in output.schema.items() + } + return OutputAdapter( + OutputFormat.model_validate({"type": "json_schema", "schema": schema}) + ) + if isinstance(output, type) and issubclass(output, BaseModel): + schema = output.model_json_schema(mode="validation") + _ensure_object_schema(schema) + return OutputAdapter( + OutputFormat.model_validate({"type": "json_schema", "schema": schema}), + output, + ) + raise TypeError("output must be None, JsonSchema, or a Pydantic BaseModel class") + + +def _ensure_object_schema(schema: Mapping[str, object]) -> None: + if schema.get("type") != "object": + raise TypeError("structured output schema must describe a top-level object") + + +def _raw_object(raw: object | None) -> FrozenJsonObject | None: + try: + return _validate_json_object(raw) + except (TypeError, ValueError): + return None + + +def _validate_json_object(raw: object | None) -> FrozenJsonObject: + if not isinstance(raw, Mapping): + raise TypeError("structured output must be a JSON object") + return freeze_json_object( + cast("Mapping[str, object]", raw), where="structured output" + ) diff --git a/src/droid_sdk/_high_level/runtime.py b/src/droid_sdk/_high_level/runtime.py new file mode 100644 index 0000000..6f6d2be --- /dev/null +++ b/src/droid_sdk/_high_level/runtime.py @@ -0,0 +1,39 @@ +"""Immutable custom-runtime configuration.""" + +# ruff: noqa: TC001, TC003 + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path + +from droid_sdk._high_level._immutable import freeze_secret_mapping +from droid_sdk.observability import Observability +from droid_sdk.types import DroidClientTransport + +Transport = DroidClientTransport + + +def _empty_str_mapping() -> Mapping[str, str]: + return {} + + +@dataclass(frozen=True, slots=True) +class Runtime: + executable: str | Path | None = None + args: Sequence[str] = () + env: Mapping[str, str] = field(default_factory=_empty_str_mapping) + transport: Transport | None = None + observability: Observability | None = None + + def __post_init__(self) -> None: + if self.executable is not None: + object.__setattr__(self, "executable", Path(self.executable)) + object.__setattr__(self, "args", tuple(self.args)) + object.__setattr__(self, "env", freeze_secret_mapping(self.env)) + + @property + def uses_supplied_transport(self) -> bool: + """Whether transport takes precedence over process configuration.""" + return self.transport is not None diff --git a/src/droid_sdk/_high_level/session.py b/src/droid_sdk/_high_level/session.py new file mode 100644 index 0000000..36566ce --- /dev/null +++ b/src/droid_sdk/_high_level/session.py @@ -0,0 +1,1998 @@ +"""Lazy high-level session lifecycle and one-shot run helper.""" + +# ruff: noqa: TC001 + +from __future__ import annotations + +import asyncio +import contextlib +import importlib.metadata +import os +import uuid +from collections.abc import Callable, Mapping, Sequence +from datetime import datetime +from enum import Enum +from pathlib import Path +from typing import Any, Literal, TypeVar, cast, overload + +from pydantic import BaseModel, ValidationError + +from droid_sdk._high_level._immutable import JsonObject +from droid_sdk._high_level.attachments import ( + Document, + Image, + PdfDocumentSource, + TextDocumentSource, +) +from droid_sdk._high_level.config import ( + JsonSchema, + SandboxSettings, + SessionConfig, + SessionSettings, + SessionSource, + SessionTag, + UpdateSettingsResult, +) +from droid_sdk._high_level.enums import ( + Autonomy, + ContextAccuracy, + McpServerStatus, + McpServerType, + Mode, + ReasoningEffort, + ToolCategory, +) +from droid_sdk._high_level.extensions import ( + CompactOutcome, + HttpMcpServerConfig, + McpConfigError, + McpMutationResult, + McpServerConfig, + McpServersResult, + McpServerStatusInfo, + McpStatusSummary, + McpToolInfo, + McpToolInputSchema, + RewindEvictedFile, + RewindFileCreation, + RewindFileSnapshot, + RewindInfo, + RewindOutcome, + SdkMcpServer, + SkillInfo, + SkillMutationResult, + SkillResource, + SkillsResult, + SseMcpServerConfig, + StdioMcpServerConfig, + ToolInfo, +) +from droid_sdk._high_level.interactions import InteractionHandlers +from droid_sdk._high_level.messages import ( + ContextUsage, + RunResult, + StreamEvent, + StreamMessage, +) +from droid_sdk._high_level.output import prepare_output_adapter +from droid_sdk._high_level.runtime import Runtime +from droid_sdk._high_level.streaming import RunStream +from droid_sdk.client import DroidClient +from droid_sdk.errors import ( + DroidConnectionError, + DroidError, + InvalidWorkingDirectoryError, + SessionBusyError, + SessionClosedError, + SessionNotOpenError, + SessionReplacedError, + SessionReplacementError, +) +from droid_sdk.observability import ObservabilityAdapter +from droid_sdk.schemas.client import ( + AddUserMessageRequestParams, + HttpMcpConfig, + SseMcpConfig, + StdioMcpConfig, +) +from droid_sdk.schemas.client import ( + HttpHeader as WireHttpHeader, +) +from droid_sdk.schemas.client import ( + McpOAuthOptions as WireMcpOAuthOptions, +) +from droid_sdk.schemas.enums import ( + AutonomyLevel as WireAutonomy, +) +from droid_sdk.schemas.enums import ( + DroidInteractionMode, + SettingsLevel, +) +from droid_sdk.schemas.enums import ( + McpServerType as WireMcpServerType, +) +from droid_sdk.schemas.enums import ( + ReasoningEffort as WireReasoningEffort, +) +from droid_sdk.transport import ProcessTransport + +ModelT = TypeVar("ModelT", bound=BaseModel) + + +class _Unset: + pass + + +_UNSET = _Unset() + + +class _State(Enum): + LAZY = "lazy" + OPENING = "opening" + OPEN = "open" + BUSY = "busy" + REPLACING = "replacing" + RETIRED = "retired" + CLOSING = "closing" + CLOSED = "closed" + + +def _wire_reasoning(value: ReasoningEffort | None) -> WireReasoningEffort | None: + return None if value is None else WireReasoningEffort(value.value) + + +def _wire_source(value: SessionSource | None) -> dict[str, object] | None: + if value is None: + return None + return { + key: item.value if isinstance(item, Enum) else item + for key, item in ( + (field, getattr(value, field)) for field in value.__dataclass_fields__ + ) + if item is not None + } + + +def _wire_tags(values: Sequence[SessionTag]) -> list[dict[str, Any]]: + return [ + { + "name": value.name, + **({} if value.metadata is None else {"metadata": dict(value.metadata)}), + } + for value in values + ] + + +def _settings(value: Any) -> SessionSettings: + mode = ( + None + if value.interaction_mode is None + or value.interaction_mode.value not in {"auto", "spec"} + else Mode(value.interaction_mode.value) + ) + autonomy = ( + None if value.autonomy_level is None else Autonomy(value.autonomy_level.value) + ) + sandbox = ( + None + if value.sandbox is None + else SandboxSettings( + enabled=value.sandbox.enabled, + mode=None if value.sandbox.mode is None else value.sandbox.mode.value, + ) + ) + return SessionSettings( + model=value.model_id, + reasoning_effort=ReasoningEffort(value.reasoning_effort.value), + mode=mode, + autonomy=autonomy, + spec_model=value.spec_mode_model_id, + spec_reasoning_effort=( + None + if value.spec_mode_reasoning_effort is None + else ReasoningEffort(value.spec_mode_reasoning_effort.value) + ), + tags=tuple( + SessionTag(name=tag.name, metadata=tag.metadata) + for tag in (value.tags or ()) + ), + sandbox=sandbox, + additional_tools=value.additional_tool_ids, + enabled_tools=value.enabled_tool_ids, + disabled_tools=value.disabled_tool_ids, + restrict_tools=value.restrict_tool_ids, + ) + + +def _mcp_config(value: McpServerConfig) -> dict[str, Any]: + if isinstance(value, SdkMcpServer): + raise TypeError("SDK MCP servers must be started before serialization") + try: + if isinstance(value, StdioMcpServerConfig): + model: BaseModel = StdioMcpConfig( + name=value.name, + command=value.command, + args=list(value.args), + env=dict(value.env), + ) + else: + oauth: WireMcpOAuthOptions | Literal[False] | None + if value.oauth is None or value.oauth is False: + oauth = value.oauth + else: + oauth = WireMcpOAuthOptions.model_validate( + { + field: (item.value if isinstance(item, Enum) else item) + for field, item in ( + (field, getattr(value.oauth, field)) + for field in value.oauth.__dataclass_fields__ + ) + if item is not None + } + ) + headers = [ + WireHttpHeader(name=header.name, value=header.value) + for header in value.headers + ] + if isinstance(value, HttpMcpServerConfig): + model = HttpMcpConfig( + type="http", + name=value.name, + url=value.url, + headers=headers, + oauth=oauth, + ) + else: + model = SseMcpConfig( + type="sse", + name=value.name, + url=value.url, + headers=headers, + oauth=oauth, + ) + except (ValidationError, ValueError): + raise ValueError("Invalid MCP server configuration") from None + return model.model_dump(by_alias=True, exclude_none=True) + + +class Session: + """A lazy, single-turn-at-a-time Droid session.""" + + def __init__( + self, + *, + cwd: str | Path | None = None, + model: str | None = None, + reasoning_effort: ReasoningEffort | None = None, + config: SessionConfig | None = None, + interactions: InteractionHandlers | None = None, + runtime: Runtime | None = None, + api_key: str | None = None, + ) -> None: + self._requested_cwd: Path | None = Path.cwd() if cwd is None else Path(cwd) + self._model = model + self._reasoning_effort = reasoning_effort + self._config = config or SessionConfig() + self._interactions = interactions or InteractionHandlers() + self._runtime_config = runtime or Runtime() + self._observability = ObservabilityAdapter(self._runtime_config.observability) + self._api_key = api_key + self._resume_id: str | None = None + self._resume_options: dict[str, object] = {} + self._state = _State.LAZY + self._client: DroidClient | None = None + self._id: str | None = None + self._cwd: Path | None = self._requested_cwd + self._settings: SessionSettings | None = None + self._active_stream: RunStream[Any, Any] | None = None + self._subscriptions: set[Callable[[], None]] = set() + self._sdk_servers: list[SdkMcpServer] = [] + self._replacement_id: str | None = None + self._replacement_successor: Session | None = None + self._lifecycle_lock = asyncio.Lock() + self._open_task: asyncio.Task[None] | None = None + self._open_cleanup_task: asyncio.Task[None] | None = None + self._open_waiters = 0 + self._close_task: asyncio.Task[None] | None = None + self._close_requested = False + self._replacement_task: asyncio.Task[tuple[Any, Session]] | None = None + self._replacement_close_requested = False + self._load_mcp_configs: list[dict[str, Any]] = [] + self._load_options: dict[str, object] = { + "additional_tools": self._config.additional_tools, + "enabled_tools": self._config.enabled_tools, + "disabled_tools": self._config.disabled_tools, + "restrict_tools": self._config.restrict_tools, + "auto_reject_permission_requests": ( + self._config.auto_reject_permission_requests + ), + "disable_builtin_skills": self._config.disable_builtin_skills, + "session_source": self._config.session_source, + } + + @classmethod + def resume( + cls, + session_id: str, + *, + interactions: InteractionHandlers | None = None, + mcp_servers: Sequence[McpServerConfig] = (), + runtime: Runtime | None = None, + api_key: str | None = None, + disabled_tools: set[str] | frozenset[str] | None = None, + auto_reject_permission_requests: bool | None = None, + disable_builtin_skills: bool | None = None, + session_source: SessionSource | None = None, + ) -> Session: + value = cls( + interactions=interactions, + runtime=runtime, + api_key=api_key, + ) + value._resume_id = session_id + value._requested_cwd = None + value._cwd = None + value._resume_options = { + "mcp_servers": tuple(mcp_servers), + "disabled_tools": disabled_tools, + "auto_reject_permission_requests": auto_reject_permission_requests, + "disable_builtin_skills": disable_builtin_skills, + "session_source": session_source, + } + value._load_options = { + "additional_tools": None, + "enabled_tools": None, + "disabled_tools": disabled_tools, + "restrict_tools": None, + "auto_reject_permission_requests": auto_reject_permission_requests, + "disable_builtin_skills": disable_builtin_skills, + "session_source": session_source, + } + return value + + @property + def id(self) -> str: + if self._id is None: + raise SessionNotOpenError("The session has not been opened") + return self._id + + @property + def cwd(self) -> Path | None: + return self._cwd + + @property + def settings(self) -> SessionSettings: + if self._settings is None: + raise SessionNotOpenError("The session has not been opened") + return self._settings + + async def __aenter__(self) -> Session: + await self.open() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + traceback: object, + ) -> None: + await self.close() + + async def open(self) -> None: + task: asyncio.Task[None] | None = None + while task is None: + cleanup_task: asyncio.Task[None] | None = None + async with self._lifecycle_lock: + cleanup_task = self._open_cleanup_task + if cleanup_task is None: + if self._close_requested: + raise SessionClosedError("A closed session cannot be reopened") + if self._state in {_State.OPEN, _State.BUSY}: + return + if self._state is _State.OPENING: + task = self._open_task + assert task is not None + elif self._state is _State.REPLACING: + raise SessionBusyError("The session is being replaced") + elif self._state in {_State.CLOSING, _State.CLOSED}: + raise SessionClosedError("A closed session cannot be reopened") + elif self._state is _State.RETIRED: + self._raise_replaced() + else: + self._state = _State.OPENING + task = asyncio.create_task(self._open_impl()) + self._open_task = task + self._open_waiters += 1 + if cleanup_task is not None: + await asyncio.shield(cleanup_task) + assert task is not None + cancelled = False + try: + await asyncio.shield(task) + except asyncio.CancelledError: + cancelled = True + raise + finally: + if cancelled: + await self._cancel_open_waiter(task) + else: + self._open_waiters -= 1 + + async def _cancel_open_waiter(self, task: asyncio.Task[None]) -> None: + self._open_waiters -= 1 + if self._open_waiters != 0 or self._open_task is not task: + return + cleanup_task = asyncio.create_task(self._finish_cancelled_open(task)) + self._open_cleanup_task = cleanup_task + await asyncio.shield(cleanup_task) + + async def _finish_cancelled_open(self, task: asyncio.Task[None]) -> None: + cleanup_task: asyncio.Task[None] | None = None + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + async with self._lifecycle_lock: + if self._state is _State.OPEN: + self._state = _State.CLOSING + cleanup_task = asyncio.create_task(self._close_impl()) + self._close_task = cleanup_task + elif self._state is _State.CLOSING: + cleanup_task = self._close_task + if cleanup_task is not None: + await asyncio.gather(cleanup_task, return_exceptions=True) + async with self._lifecycle_lock: + if ( + self._state is _State.CLOSED + and self._close_task is cleanup_task + and not self._close_requested + ): + self._reset_to_lazy() + elif self._open_cleanup_task is asyncio.current_task(): + self._open_cleanup_task = None + + async def _open_impl(self) -> None: + if self._requested_cwd is not None: + try: + if not self._requested_cwd.is_dir(): + raise InvalidWorkingDirectoryError(str(self._requested_cwd)) + requested_cwd = self._requested_cwd.resolve() + except OSError as exc: + raise InvalidWorkingDirectoryError(str(self._requested_cwd)) from exc + else: + requested_cwd = Path.cwd() + + client: DroidClient | None = None + started: list[SdkMcpServer] = [] + session_start_attempted = False + self._observability.log( + level="info", + name="droid.sdk.session.open", + message="Opening Droid session", + attributes={"status": "starting"}, + ) + try: + mcp_values = ( + cast("Sequence[McpServerConfig]", self._resume_options["mcp_servers"]) + if self._resume_id is not None + else self._config.mcp_servers + ) + configs: list[dict[str, Any]] = [] + for server in mcp_values: + if isinstance(server, SdkMcpServer): + started.append(server) + config = await server.start() + configs.append(_mcp_config(config)) + else: + configs.append(_mcp_config(server)) + self._load_mcp_configs = configs + + runtime = self._runtime_config + adapter = self._observability + if runtime.transport is not None: + if not runtime.transport.is_connected: + raise DroidError("A supplied transport must already be connected") + transport = runtime.transport + else: + key = self._api_key or os.environ.get("FACTORY_API_KEY") + env = dict(runtime.env) + if key: + env["FACTORY_API_KEY"] = key + executable = ( + "droid" if runtime.executable is None else str(runtime.executable) + ) + transport = ProcessTransport( + exec_path=executable, + exec_args=[ + "exec", + "--input-format", + "stream-jsonrpc", + "--output-format", + "stream-jsonrpc", + *runtime.args, + ], + cwd=str(requested_cwd), + env=env, + ) + client = DroidClient( + transport=transport, + trace_meta_injector=adapter.trace_meta_injector, + timing_callback=adapter.timing_callback, + ) + try: + await client.connect() + except FileNotFoundError as exc: + raise DroidConnectionError( + "Droid executable was not found", + exec_path=( + None if runtime.executable is None else str(runtime.executable) + ), + cwd=str(requested_cwd), + ) from exc + client.set_interaction_handlers(self._interactions) + + if self._resume_id is not None: + session_start_attempted = True + load_result = await client.load_session( + session_id=self._resume_id, + mcp_servers=configs or None, + disabled_tool_ids=_list_or_none( + self._resume_options["disabled_tools"] + ), + auto_reject_permission_requests=cast( + "bool | None", + self._resume_options["auto_reject_permission_requests"], + ), + disable_builtin_skills=cast( + "bool | None", + self._resume_options["disable_builtin_skills"], + ), + session_source=_wire_source( + cast( + "SessionSource | None", + self._resume_options["session_source"], + ) + ), + ) + session_id = self._resume_id + cwd_value = _load_cwd(load_result, requested_cwd) + wire_settings = load_result.settings + else: + sdk_tag = SessionTag( + name="sdk", + metadata={ + "language": "python", + "version": importlib.metadata.version("droid-sdk"), + }, + ) + tags = tuple(tag for tag in self._config.tags if tag.name != "sdk") + tags += (sdk_tag,) + session_start_attempted = True + initialize_result = await client.initialize_session( + machine_id=self._config.machine_id or "default", + cwd=str(requested_cwd), + mcp_servers=configs or None, + interaction_mode=( + None + if self._config.mode is None + else DroidInteractionMode(self._config.mode.value) + ), + autonomy_level=( + None + if self._config.autonomy is None + else WireAutonomy(self._config.autonomy.value) + ), + model_id=self._model, + reasoning_effort=_wire_reasoning(self._reasoning_effort), + spec_mode_model_id=self._config.spec_model, + spec_mode_reasoning_effort=_wire_reasoning( + self._config.spec_reasoning_effort + ), + additional_tool_ids=_list_or_none(self._config.additional_tools), + enabled_tool_ids=_list_or_none(self._config.enabled_tools), + disabled_tool_ids=_list_or_none(self._config.disabled_tools), + restrict_tool_ids=_list_or_none(self._config.restrict_tools), + session_source=_wire_source(self._config.session_source), + tags=cast("Any", _wire_tags(tags)), + auto_reject_permission_requests=( + self._config.auto_reject_permission_requests + ), + disable_builtin_skills=self._config.disable_builtin_skills, + ) + session_id = initialize_result.session_id + cwd_value = requested_cwd + wire_settings = initialize_result.settings + + self._client = client + self._id = session_id + self._cwd = cwd_value + self._settings = _settings(wire_settings) + self._sdk_servers = started + self._bind_metadata() + if self._state is _State.OPENING: + self._state = _State.OPEN + self._observability.log( + level="info", + name="droid.sdk.session.open", + message="Droid session opened", + attributes={ + "session_id": session_id, + "status": "success", + }, + ) + except BaseException as exc: + self._observability.log( + level="error", + name="droid.sdk.session.open", + message="Droid session failed to open", + attributes={"status": "error"}, + error=exc, + ) + if client is not None: + if session_start_attempted: + with contextlib.suppress(BaseException): + await client.close_session(reason="other") + with contextlib.suppress(BaseException): + await client.close() + await asyncio.gather( + *(server.close() for server in started), return_exceptions=True + ) + for unsubscribe in tuple(self._subscriptions): + with contextlib.suppress(BaseException): + unsubscribe() + self._subscriptions.clear() + if self._client is client: + self._client = None + self._id = None + self._settings = None + self._sdk_servers.clear() + if self._state is _State.OPENING: + self._state = _State.LAZY + raise + + async def close(self) -> None: + task: asyncio.Task[None] | None = None + state_at_entry = self._state + replacement = self._replacement_task + replacement_at_entry = replacement is not None and not replacement.done() + if state_at_entry is _State.RETIRED and not replacement_at_entry: + return + self._close_requested = True + if replacement_at_entry: + self._replacement_close_requested = True + async with self._lifecycle_lock: + if replacement_at_entry: + assert replacement is not None + if self._close_task is None: + self._state = _State.CLOSING + task = asyncio.create_task( + self._close_after_replacement(replacement) + ) + self._close_task = task + else: + task = self._close_task + elif self._state is _State.CLOSED: + task = self._close_task + if task is None: + return + elif self._state is _State.RETIRED: + return + elif self._state is _State.CLOSING: + task = self._close_task + if task is None: + return + elif self._state is _State.REPLACING: + replacement = self._replacement_task + assert replacement is not None + self._state = _State.CLOSING + task = asyncio.create_task(self._close_after_replacement(replacement)) + self._close_task = task + elif self._state is _State.OPENING: + opening = self._open_task + assert opening is not None + self._state = _State.CLOSING + task = asyncio.create_task(self._close_after_open(opening)) + self._close_task = task + elif self._state is _State.LAZY: + self._state = _State.CLOSED + return + else: + self._state = _State.CLOSING + task = asyncio.create_task(self._close_impl()) + self._close_task = task + await asyncio.shield(task) + + async def _close_after_open(self, opening: asyncio.Task[None]) -> None: + try: + await opening + except BaseException: + self._state = _State.CLOSED + return + await self._close_impl() + + async def _close_after_replacement( + self, + replacement: asyncio.Task[tuple[Any, Session]], + ) -> None: + try: + _, successor = await replacement + except BaseException: + if self._client is None: + self._state = _State.CLOSED + return + await self._close_impl() + return + await successor.close() + self._state = _State.RETIRED + + async def _close_impl(self) -> None: + session_id = self._id + self._observability.log( + level="info", + name="droid.sdk.session.close", + message="Closing Droid session", + attributes={ + "session_id": session_id, + "status": "starting", + }, + ) + errors: list[BaseException] = [] + stream = self._active_stream + if stream is not None: + try: + await stream.aclose() + except BaseException as exc: + errors.append(exc) + for unsubscribe in tuple(self._subscriptions): + try: + unsubscribe() + except BaseException as exc: + errors.append(exc) + self._subscriptions.clear() + client = self._client + if client is not None: + try: + await client.close_session(reason="other") + except BaseException as exc: + errors.append(exc) + try: + await client.close() + except BaseException as exc: + errors.append(exc) + server_results = await asyncio.gather( + *(server.close() for server in self._sdk_servers), return_exceptions=True + ) + errors.extend( + result for result in server_results if isinstance(result, BaseException) + ) + self._client = None + self._sdk_servers.clear() + self._active_stream = None + self._state = _State.CLOSED + self._observability.log( + level="error" if errors else "info", + name="droid.sdk.session.close", + message="Droid session closed", + attributes={ + "session_id": session_id, + "status": "error" if errors else "success", + }, + ) + if errors: + raise errors[0] + + def _reset_to_lazy(self) -> None: + self._state = _State.LAZY + self._close_task = None + self._open_task = None + self._open_cleanup_task = None + self._close_requested = False + self._client = None + self._id = None + self._settings = None + self._active_stream = None + self._subscriptions.clear() + self._sdk_servers.clear() + self._cwd = self._requested_cwd + + @overload + def stream( + self, + prompt: str, + *, + images: Sequence[Image] = (), + files: Sequence[Document] = (), + output: None = None, + timeout: float | None = None, + include_partial_messages: Literal[False] = False, + ) -> RunStream[None, StreamMessage[None]]: ... + + @overload + def stream( + self, + prompt: str, + *, + images: Sequence[Image] = (), + files: Sequence[Document] = (), + output: type[ModelT], + timeout: float | None = None, + include_partial_messages: Literal[False] = False, + ) -> RunStream[ModelT, StreamMessage[ModelT]]: ... + + @overload + def stream( + self, + prompt: str, + *, + images: Sequence[Image] = (), + files: Sequence[Document] = (), + output: JsonSchema, + timeout: float | None = None, + include_partial_messages: Literal[False] = False, + ) -> RunStream[JsonObject, StreamMessage[JsonObject]]: ... + + @overload + def stream( + self, + prompt: str, + *, + images: Sequence[Image] = (), + files: Sequence[Document] = (), + output: None = None, + timeout: float | None = None, + include_partial_messages: Literal[True], + ) -> RunStream[None, StreamEvent[None]]: ... + + @overload + def stream( + self, + prompt: str, + *, + images: Sequence[Image] = (), + files: Sequence[Document] = (), + output: type[ModelT], + timeout: float | None = None, + include_partial_messages: Literal[True], + ) -> RunStream[ModelT, StreamEvent[ModelT]]: ... + + @overload + def stream( + self, + prompt: str, + *, + images: Sequence[Image] = (), + files: Sequence[Document] = (), + output: JsonSchema, + timeout: float | None = None, + include_partial_messages: Literal[True], + ) -> RunStream[JsonObject, StreamEvent[JsonObject]]: ... + + def stream( + self, + prompt: str, + *, + images: Sequence[Image] = (), + files: Sequence[Document] = (), + output: type[BaseModel] | JsonSchema | None = None, + timeout: float | None = None, + include_partial_messages: bool = False, + ) -> RunStream[Any, Any]: + self._ensure_active() + if self._active_stream is not None: + raise SessionBusyError(f"Session {self.id} already has an active turn") + adapter = prepare_output_adapter(output) + turn_id = str(uuid.uuid4()) + stream_unsubscribes: tuple[Callable[[], None], ...] = () + + async def start(stream: RunStream[Any, Any]) -> None: + nonlocal stream_unsubscribes + client = self._require_client() + client.set_interaction_handlers( + self._interactions, + error_sink=stream.queue_error_event, + ) + unsubscribe = client.on_notification(stream.feed_notification) + unsubscribe_error = client.on_error(stream.feed_error) + self._subscriptions.update((unsubscribe, unsubscribe_error)) + stream_unsubscribes = ( + unsubscribe, + unsubscribe_error, + ) + message = AddUserMessageRequestParams.model_validate( + { + "text": prompt, + "messageId": turn_id, + "images": [ + { + "type": "base64", + "data": image.source.data, + "mediaType": image.source.media_type, + } + for image in images + ] + or None, + "files": [_document_source(file) for file in files] or None, + "outputFormat": adapter.output_format, + } + ) + await client.add_user_message( + text=message.text, + message_id=message.message_id, + images=cast("Any", message.images), + files=cast("Any", message.files), + output_format=message.output_format, + ) + + async def finish(interrupt: bool) -> None: + client = self._client + for unsubscribe in stream_unsubscribes: + unsubscribe() + self._subscriptions.discard(unsubscribe) + if self._active_stream is stream_value: + self._active_stream = None + if self._state is _State.BUSY: + self._state = _State.OPEN + if client is not None: + client.set_interaction_handlers(self._interactions) + if interrupt and client is not None: + task = asyncio.create_task(client.interrupt_session()) + task.add_done_callback(_consume_task_result) + if interrupt: + status = "interrupted" + elif stream_value.completed: + result = stream_value.result + if result.success: + status = "success" + elif result.interrupted: + status = "interrupted" + else: + status = "error" + else: + status = "error" + self._observability.log( + level="info" if status == "success" else "warn", + name="droid.sdk.run.terminal", + message="Droid run finished", + attributes={ + "session_id": self.id, + "status": status, + }, + ) + self._observability.record_run_terminal(status=status) + + stream_value = RunStream( + expected_turn_id=turn_id, + session_id=self.id, + include_partial_messages=include_partial_messages, + output_adapter=adapter, + start=start, + finish=finish, + timeout=timeout, + ) + self._active_stream = stream_value + self._state = _State.BUSY + return stream_value + + async def interrupt(self) -> None: + self._ensure_active() + await self._require_client().interrupt_session() + + async def update_settings( + self, + *, + model: str | None = None, + reasoning_effort: ReasoningEffort | None = None, + mode: Mode | None = None, + autonomy: Autonomy | None = None, + spec_model: str | None | _Unset = _UNSET, + spec_reasoning_effort: ReasoningEffort | None | _Unset = _UNSET, + tags: Sequence[SessionTag] | None = None, + compaction_token_limit: int | None = None, + compaction_threshold_check_enabled: bool | None = None, + additional_tools: set[str] | frozenset[str] | None = None, + enabled_tools: set[str] | frozenset[str] | None = None, + disabled_tools: set[str] | frozenset[str] | None = None, + restrict_tools: set[str] | frozenset[str] | None = None, + ) -> UpdateSettingsResult: + self._ensure_active() + spec_model_value = None if isinstance(spec_model, _Unset) else spec_model + spec_reasoning_value = ( + None if isinstance(spec_reasoning_effort, _Unset) else spec_reasoning_effort + ) + explicit_null_fields: list[ + Literal["specModeModelId", "specModeReasoningEffort"] + ] = [] + if spec_model is None: + explicit_null_fields.append("specModeModelId") + if spec_reasoning_effort is None: + explicit_null_fields.append("specModeReasoningEffort") + await self._require_client().update_session_settings( + model_id=model, + reasoning_effort=_wire_reasoning(reasoning_effort), + interaction_mode=( + None if mode is None else DroidInteractionMode(mode.value) + ), + autonomy_level=(None if autonomy is None else WireAutonomy(autonomy.value)), + spec_mode_model_id=spec_model_value, + spec_mode_reasoning_effort=_wire_reasoning(spec_reasoning_value), + tags=cast("Any", None if tags is None else _wire_tags(tags)), + compaction_token_limit=compaction_token_limit, + compaction_threshold_check_enabled=(compaction_threshold_check_enabled), + additional_tool_ids=_list_or_none(additional_tools), + enabled_tool_ids=_list_or_none(enabled_tools), + disabled_tool_ids=_list_or_none(disabled_tools), + restrict_tool_ids=_list_or_none(restrict_tools), + explicit_null_fields=explicit_null_fields, + ) + for key, value in ( + ("additional_tools", additional_tools), + ("enabled_tools", enabled_tools), + ("disabled_tools", disabled_tools), + ("restrict_tools", restrict_tools), + ): + if value is not None: + self._load_options[key] = frozenset(value) + current = self.settings + self._settings = SessionSettings( + model=current.model if model is None else model, + reasoning_effort=( + current.reasoning_effort + if reasoning_effort is None + else reasoning_effort + ), + mode=current.mode if mode is None else mode, + autonomy=current.autonomy if autonomy is None else autonomy, + spec_model=( + current.spec_model if isinstance(spec_model, _Unset) else spec_model + ), + spec_reasoning_effort=( + current.spec_reasoning_effort + if isinstance(spec_reasoning_effort, _Unset) + else spec_reasoning_effort + ), + tags=current.tags if tags is None else tags, + sandbox=current.sandbox, + additional_tools=( + current.additional_tools + if additional_tools is None + else additional_tools + ), + enabled_tools=( + current.enabled_tools if enabled_tools is None else enabled_tools + ), + disabled_tools=( + current.disabled_tools if disabled_tools is None else disabled_tools + ), + restrict_tools=( + current.restrict_tools if restrict_tools is None else restrict_tools + ), + ) + return UpdateSettingsResult() + + async def rename(self, title: str) -> None: + self._ensure_active() + await self._require_client().rename_session(title=title) + + def on_notification( + self, + callback: Callable[[Mapping[str, object]], None], + *, + type: str | None = None, + ) -> Callable[[], None]: + self._ensure_active() + + def dispatch(raw: dict[str, Any]) -> None: + inner = _inner_notification(raw) + if inner is None: + return + if type is None or inner.get("type") == type: + callback(cast("Mapping[str, object]", inner)) + + unsubscribe_inner = self._require_client().on_notification(dispatch) + + def unsubscribe() -> None: + unsubscribe_inner() + self._subscriptions.discard(unsubscribe) + + self._subscriptions.add(unsubscribe) + return unsubscribe + + async def list_tools( + self, + *, + model: str | None = None, + mode: Mode | None = None, + autonomy: Autonomy | None = None, + spec_model: str | None = None, + additional_tools: set[str] | frozenset[str] | None = None, + enabled_tools: set[str] | frozenset[str] | None = None, + disabled_tools: set[str] | frozenset[str] | None = None, + restrict_tools: set[str] | frozenset[str] | None = None, + skip_permissions_unsafe: bool | None = None, + ) -> list[ToolInfo]: + self._ensure_active() + result = await self._require_client().list_tools( + model_id=model, + interaction_mode=( + None if mode is None else DroidInteractionMode(mode.value) + ), + autonomy_level=(None if autonomy is None else WireAutonomy(autonomy.value)), + spec_mode_model_id=spec_model, + additional_tool_ids=_list_or_none(additional_tools), + enabled_tool_ids=_list_or_none(enabled_tools), + disabled_tool_ids=_list_or_none(disabled_tools), + restrict_tool_ids=_list_or_none(restrict_tools), + skip_permissions_unsafe=skip_permissions_unsafe, + ) + return [ + ToolInfo( + id=item.llm_id or item.id, + display_name=item.display_name or item.llm_id or item.id, + description=item.description or "", + category=_tool_category(item.category), + default_allowed=item.default_allowed, + allowed=item.currently_allowed, + ) + for item in result.tools + ] + + async def list_skills(self) -> SkillsResult: + self._ensure_active() + result = await self._require_client().list_skills() + return SkillsResult( + skills=[ + SkillInfo( + name=item.name, + description=item.description, + location=cast("Any", item.location.value), + file_path=item.file_path, + enabled=item.enabled, + user_invocable=item.user_invocable, + version=item.version, + content=item.content, + resources=tuple( + SkillResource( + name=resource.name, + path=resource.path, + type=resource.type, + ) + for resource in (item.resources or ()) + ), + disabled_by=item.disabled_by, + ) + for item in result.skills + ], + project_available=result.project_available, + ) + + async def enable_skill( + self, + name: str, + *, + scope: Literal["user", "project"] = "user", + ) -> SkillMutationResult: + return await self._set_skill(name, False, scope) + + async def disable_skill( + self, + name: str, + *, + scope: Literal["user", "project"] = "user", + ) -> SkillMutationResult: + return await self._set_skill(name, True, scope) + + async def _set_skill( + self, + name: str, + disabled: bool, + scope: Literal["user", "project"], + ) -> SkillMutationResult: + self._ensure_active() + result = await self._require_client().set_skill_disabled( + skill_name=name, + disabled=disabled, + settings_level=SettingsLevel(scope), + ) + return SkillMutationResult(result.success) + + async def list_mcp_servers(self) -> McpServersResult: + self._ensure_active() + result = await self._require_client().list_mcp_servers() + return McpServersResult( + servers=tuple(_mcp_server(item) for item in result.servers), + summary=_mcp_summary(result.summary), + ) + + async def list_mcp_tools(self) -> list[McpToolInfo]: + self._ensure_active() + result = await self._require_client().list_mcp_tools() + return [ + McpToolInfo( + server_name=item.server_name, + name=item.name, + description=item.description, + is_enabled=item.is_enabled, + is_read_only=item.is_read_only, + input_schema=( + None + if item.input_schema is None + else McpToolInputSchema( + type=item.input_schema.type, + properties=item.input_schema.properties, + required=item.input_schema.required, + ) + ), + ) + for item in result.tools + ] + + async def add_mcp_server( + self, + config: StdioMcpServerConfig | HttpMcpServerConfig | SseMcpServerConfig, + ) -> McpMutationResult: + self._ensure_active() + raw = _mcp_config(config) + headers = cast("object", raw.get("headers")) + result = await self._require_client().add_mcp_server( + name=config.name, + type=WireMcpServerType(raw.get("type", "stdio")), + url=cast("str | None", raw.get("url")), + headers=( + None + if not isinstance(headers, list) + else _header_mapping(cast("list[object]", headers)) + ), + command=cast("str | None", raw.get("command")), + args=cast("list[str] | None", raw.get("args")), + env=cast("dict[str, str] | None", raw.get("env")), + oauth=cast("Any", raw.get("oauth")), + ) + return McpMutationResult(result.success) + + async def remove_mcp_server( + self, + name: str, + ) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().remove_mcp_server( + server_name=name, + settings_level=SettingsLevel.User, + ) + return McpMutationResult(result.success) + + async def enable_mcp_server( + self, + name: str, + ) -> McpMutationResult: + return await self._toggle_mcp_server(name, True) + + async def disable_mcp_server( + self, + name: str, + ) -> McpMutationResult: + return await self._toggle_mcp_server(name, False) + + async def _toggle_mcp_server( + self, + name: str, + enabled: bool, + ) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().toggle_mcp_server( + server_name=name, + enabled=enabled, + settings_level=SettingsLevel.User, + ) + return McpMutationResult(result.success) + + async def enable_mcp_tool( + self, server_name: str, tool_name: str + ) -> McpMutationResult: + return await self._toggle_mcp_tool(server_name, tool_name, True) + + async def disable_mcp_tool( + self, server_name: str, tool_name: str + ) -> McpMutationResult: + return await self._toggle_mcp_tool(server_name, tool_name, False) + + async def _toggle_mcp_tool( + self, + server_name: str, + tool_name: str, + enabled: bool, + ) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().toggle_mcp_tool( + server_name=server_name, + tool_name=tool_name, + enabled=enabled, + ) + return McpMutationResult(result.success) + + async def authenticate_mcp_server(self, name: str) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().authenticate_mcp_server(server_name=name) + return McpMutationResult(result.success) + + async def cancel_mcp_auth(self, name: str) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().cancel_mcp_auth(server_name=name) + return McpMutationResult(result.success) + + async def clear_mcp_auth(self, name: str) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().clear_mcp_auth(server_name=name) + return McpMutationResult(result.success) + + async def submit_mcp_auth_code( + self, name: str, *, code: str, state: str + ) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().submit_mcp_auth_code( + server_name=name, code=code, state=state + ) + return McpMutationResult(result.success) + + async def submit_mcp_auth_error( + self, + name: str, + *, + error: str, + state: str, + error_description: str | None = None, + ) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().submit_mcp_auth_error( + server_name=name, + error=error, + state=state, + error_description=error_description, + ) + return McpMutationResult(result.success) + + async def context(self) -> ContextUsage: + self._ensure_active() + result = await self._require_client().get_context_stats() + timestamp = datetime.fromisoformat(result.updated_at.replace("Z", "+00:00")) + return ContextUsage( + used=result.used, + remaining=result.remaining, + limit=result.limit, + accuracy=ContextAccuracy(result.accuracy.value), + updated_at=timestamp, + ) + + async def enter_spec( + self, + *, + model: str | None = None, + reasoning_effort: ReasoningEffort | None = None, + ) -> UpdateSettingsResult: + if model is None and reasoning_effort is None: + return await self.update_settings(mode=Mode.SPEC) + if model is None: + return await self.update_settings( + mode=Mode.SPEC, + spec_reasoning_effort=reasoning_effort, + ) + if reasoning_effort is None: + return await self.update_settings( + mode=Mode.SPEC, + spec_model=model, + ) + return await self.update_settings( + mode=Mode.SPEC, + spec_model=model, + spec_reasoning_effort=reasoning_effort, + ) + + async def leave_spec(self) -> UpdateSettingsResult: + return await self.update_settings(mode=Mode.AUTO) + + async def fork( + self, + *, + title: str | None = None, + tags: Sequence[SessionTag] | None = None, + ) -> Session: + _, successor = await self._replacement_operation( + lambda: self._require_client().fork_session( + title=title, + tags=cast("Any", None if tags is None else _wire_tags(tags)), + ) + ) + return successor + + async def compact( + self, + *, + instructions: str | None = None, + ) -> CompactOutcome: + result, successor = await self._replacement_operation( + lambda: self._require_client().compact_session( + custom_instructions=instructions + ) + ) + return CompactOutcome(successor, result.removed_count) + + async def rewind_info(self, message_id: str) -> RewindInfo: + self._ensure_active() + result = await self._require_client().get_rewind_info(message_id=message_id) + return RewindInfo( + available_files=tuple( + RewindFileSnapshot(item.file_path, item.content_hash, item.size) + for item in result.available_files + ), + created_files=tuple( + RewindFileCreation(item.file_path) for item in result.created_files + ), + evicted_files=tuple( + RewindEvictedFile(item.file_path, item.reason) + for item in result.evicted_files + ), + ) + + async def rewind( + self, + message_id: str, + *, + restore: Sequence[RewindFileSnapshot] = (), + delete: Sequence[RewindFileCreation] = (), + title: str, + ) -> RewindOutcome: + result, successor = await self._replacement_operation( + lambda: self._require_client().execute_rewind( + message_id=message_id, + files_to_restore=[ + { + "filePath": item.file_path, + "contentHash": item.content_hash, + "size": item.size, + } + for item in restore + ], + files_to_delete=[{"filePath": item.file_path} for item in delete], + fork_title=title, + ) + ) + return RewindOutcome( + successor, + result.restored_count, + result.deleted_count, + result.failed_restore_count, + result.failed_delete_count, + ) + + async def _replacement_operation( + self, + operation: Callable[[], Any], + ) -> tuple[Any, Session]: + async with self._lifecycle_lock: + if self._close_requested: + raise SessionClosedError("The session is closed") + self._ensure_active() + if self._active_stream is not None: + raise SessionBusyError("Cannot replace a session with an active turn") + self._state = _State.REPLACING + self._replacement_successor = None + self._replacement_close_requested = False + task = asyncio.create_task(self._replacement_impl(operation)) + self._replacement_task = task + try: + return await asyncio.shield(task) + except asyncio.CancelledError: + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + if task.done() and not task.cancelled(): + with contextlib.suppress(BaseException): + _, successor = task.result() + await self._restore_after_cancelled_replacement(successor) + raise + + async def _replacement_impl( + self, + operation: Callable[[], Any], + ) -> tuple[Any, Session]: + successor: Session | None = None + try: + result = await operation() + successor = await self._attach_replacement(result.new_session_id) + self._replacement_successor = successor + await _replacement_handoff_checkpoint() + self._retire_after_replacement(successor) + return result, successor + except asyncio.CancelledError: + if successor is not None: + await self._restore_after_cancelled_replacement(successor) + elif self._state is _State.REPLACING: + self._state = _State.OPEN + raise + except BaseException: + if self._state is _State.REPLACING: + self._state = _State.OPEN + raise + + async def _restore_after_cancelled_replacement(self, successor: Session) -> None: + if self._replacement_close_requested: + self._detach_cancelled_successor(successor) + return + client = successor._require_client() + try: + restored = await self._load_with_policies(client, self.id) + self._settings = _settings(restored.settings) + self._cwd = _load_cwd(restored, self._cwd or Path.cwd()) + except BaseException: + self._state = _State.CLOSING + with contextlib.suppress(BaseException): + await self._close_impl() + self._detach_cancelled_successor(successor) + self._replacement_successor = None + return + self._detach_cancelled_successor(successor) + self._replacement_id = None + self._replacement_successor = None + self._replacement_task = None + self._state = _State.OPEN + + def _detach_cancelled_successor(self, successor: Session) -> None: + for unsubscribe in tuple(successor._subscriptions): + with contextlib.suppress(BaseException): + unsubscribe() + successor._subscriptions.clear() + successor._client = None + successor._sdk_servers = [] + successor._state = _State.RETIRED + successor._replacement_id = self.id + + def _retire_after_replacement(self, successor: Session) -> None: + self._replacement_id = successor.id + self._state = _State.RETIRED + for unsubscribe in tuple(self._subscriptions): + unsubscribe() + self._subscriptions.clear() + self._client = None + self._sdk_servers = [] + + async def _attach_replacement(self, replacement_id: str) -> Session: + client = self._require_client() + try: + loaded = await self._load_with_policies(client, replacement_id) + except BaseException as cause: + try: + restored = await self._load_with_policies(client, self.id) + self._settings = _settings(restored.settings) + self._cwd = _load_cwd(restored, self._cwd or Path.cwd()) + except BaseException as rollback: + self._state = _State.CLOSING + with contextlib.suppress(BaseException): + await self._close_impl() + raise SessionReplacementError( + self.id, + replacement_id, + rollback_error=rollback, + ) from cause + raise SessionReplacementError(self.id, replacement_id) from cause + + successor = object.__new__(Session) + successor.__dict__ = self.__dict__.copy() + successor._id = replacement_id + successor._settings = _settings(loaded.settings) + successor._cwd = _load_cwd(loaded, self._cwd or Path.cwd()) + successor._state = _State.OPEN + successor._active_stream = None + successor._subscriptions = set() + successor._replacement_successor = None + successor._lifecycle_lock = asyncio.Lock() + successor._open_task = None + successor._open_cleanup_task = None + successor._open_waiters = 0 + successor._close_task = None + successor._close_requested = False + successor._replacement_task = None + successor._replacement_close_requested = False + successor._bind_metadata() + return successor + + async def _load_with_policies( + self, + client: DroidClient, + session_id: str, + ) -> Any: + loaded = await client.load_session( + session_id=session_id, + mcp_servers=self._load_mcp_configs or None, + additional_tool_ids=_list_or_none(self._load_options["additional_tools"]), + enabled_tool_ids=_list_or_none(self._load_options["enabled_tools"]), + disabled_tool_ids=_list_or_none(self._load_options["disabled_tools"]), + auto_reject_permission_requests=cast( + "bool | None", + self._load_options["auto_reject_permission_requests"], + ), + disable_builtin_skills=cast( + "bool | None", + self._load_options["disable_builtin_skills"], + ), + session_source=_wire_source( + cast("SessionSource | None", self._load_options["session_source"]) + ), + ) + restrict_tools = _list_or_none(self._load_options["restrict_tools"]) + if restrict_tools is not None: + await client.update_session_settings( + restrict_tool_ids=restrict_tools, + ) + return loaded + + def _bind_metadata(self) -> None: + client = self._require_client() + + def update(raw: dict[str, Any]) -> None: + inner = _inner_notification(raw) + if inner is None: + return + if inner.get("type") == "settings_updated": + settings = inner.get("settings") + if isinstance(settings, Mapping) and self._settings is not None: + self._settings = _merge_settings( + self._settings, + cast("Mapping[str, object]", settings), + ) + return + if inner.get("type") == "session_working_directory_changed": + cwd = inner.get("cwd") + if isinstance(cwd, str): + self._cwd = Path(cwd) + + unsubscribe = client.on_notification(update) + self._subscriptions.add(unsubscribe) + + def _ensure_active(self) -> None: + if self._state in {_State.LAZY, _State.OPENING}: + raise SessionNotOpenError("Call open() before using the session") + if self._state in {_State.CLOSING, _State.CLOSED}: + raise SessionClosedError("The session is closed") + if self._state is _State.RETIRED: + self._raise_replaced() + if self._state is _State.REPLACING: + raise SessionBusyError("The session is being replaced") + + def _raise_replaced(self) -> None: + assert self._id is not None and self._replacement_id is not None + raise SessionReplacedError(self._id, self._replacement_id) + + def _require_client(self) -> DroidClient: + if self._client is None: + if self._state is _State.RETIRED: + self._raise_replaced() + raise SessionNotOpenError("The session has not been opened") + return self._client + + +@overload +async def run( + prompt: str, + *, + cwd: str | Path | None = None, + model: str | None = None, + reasoning_effort: ReasoningEffort | None = None, + images: Sequence[Image] = (), + files: Sequence[Document] = (), + output: None = None, + timeout: float | None = None, + config: SessionConfig | None = None, + interactions: InteractionHandlers | None = None, + runtime: Runtime | None = None, + api_key: str | None = None, +) -> RunResult[None]: ... + + +@overload +async def run( + prompt: str, + *, + cwd: str | Path | None = None, + model: str | None = None, + reasoning_effort: ReasoningEffort | None = None, + images: Sequence[Image] = (), + files: Sequence[Document] = (), + output: type[ModelT], + timeout: float | None = None, + config: SessionConfig | None = None, + interactions: InteractionHandlers | None = None, + runtime: Runtime | None = None, + api_key: str | None = None, +) -> RunResult[ModelT]: ... + + +@overload +async def run( + prompt: str, + *, + cwd: str | Path | None = None, + model: str | None = None, + reasoning_effort: ReasoningEffort | None = None, + images: Sequence[Image] = (), + files: Sequence[Document] = (), + output: JsonSchema, + timeout: float | None = None, + config: SessionConfig | None = None, + interactions: InteractionHandlers | None = None, + runtime: Runtime | None = None, + api_key: str | None = None, +) -> RunResult[JsonObject]: ... + + +async def run( + prompt: str, + *, + cwd: str | Path | None = None, + model: str | None = None, + reasoning_effort: ReasoningEffort | None = None, + images: Sequence[Image] = (), + files: Sequence[Document] = (), + output: type[BaseModel] | JsonSchema | None = None, + timeout: float | None = None, + config: SessionConfig | None = None, + interactions: InteractionHandlers | None = None, + runtime: Runtime | None = None, + api_key: str | None = None, +) -> RunResult[Any]: + session = Session( + cwd=cwd, + model=model, + reasoning_effort=reasoning_effort, + config=config, + interactions=interactions, + runtime=runtime, + api_key=api_key, + ) + try: + await session.open() + stream = session.stream( + prompt, + images=images, + files=files, + output=output, + timeout=timeout, + ) + async with stream: + async for _ in stream: + pass + return stream.result + finally: + close_task = asyncio.create_task(session.close()) + try: + await asyncio.shield(close_task) + except asyncio.CancelledError: + await close_task + raise + + +def _list_or_none(value: object) -> list[str] | None: + if value is None: + return None + return sorted(cast("Sequence[str]", value)) + + +async def _replacement_handoff_checkpoint() -> None: + """Give cancellation a deterministic handoff point after replacement.""" + await asyncio.sleep(0) + + +def _consume_task_result(task: asyncio.Future[Any]) -> None: + with contextlib.suppress(BaseException): + task.result() + + +def _load_cwd(result: Any, fallback: Path) -> Path: + extra = cast("dict[str, object]", result.model_extra or {}) + cwd = extra.get("cwd") + if isinstance(cwd, str): + return Path(cwd) + worktree = extra.get("worktree") + if isinstance(worktree, Mapping): + typed_worktree = cast("Mapping[str, object]", worktree) + path = typed_worktree.get("path") + if isinstance(path, str): + return Path(path) + return fallback + + +def _document_source(document: Document) -> dict[str, Any]: + source = document.source + if isinstance(source, TextDocumentSource): + return { + "type": "text", + "mediaType": "text/plain", + "data": source.data, + "name": source.name, + } + assert isinstance(source, PdfDocumentSource) + return { + "type": "base64", + "mediaType": "application/pdf", + "data": source.data, + "parsedData": source.parsed_data, + "name": source.name, + "path": source.path, + } + + +def _inner_notification(raw: Mapping[str, Any]) -> dict[str, Any] | None: + params = cast("object", raw.get("params")) + if not isinstance(params, Mapping): + return None + inner = cast("Mapping[str, object]", params).get("notification") + return cast("dict[str, Any]", inner) if isinstance(inner, dict) else None + + +def _header_mapping(values: list[object]) -> dict[str, str]: + result: dict[str, str] = {} + for value in values: + if not isinstance(value, Mapping): + continue + header = cast("Mapping[str, object]", value) + name = header.get("name") + content = header.get("value") + if isinstance(name, str) and isinstance(content, str): + result[name] = content + return result + + +def _tool_category(value: str | None) -> ToolCategory: + try: + return ToolCategory(value) + except ValueError: + return ToolCategory.OTHER + + +def _merge_settings( + current: SessionSettings, + update: Mapping[str, object], +) -> SessionSettings: + def enum_value( + key: str, + enum: type[Enum], + fallback: object, + *, + allow_none: bool = False, + ) -> object: + value = update.get(key, fallback) + if value is fallback: + return fallback + if value is None and allow_none: + return None + try: + return enum(value) + except (TypeError, ValueError): + return fallback + + tags: Sequence[SessionTag] = current.tags + raw_tags = update.get("tags") + if isinstance(raw_tags, list): + parsed_tags: list[SessionTag] = [] + for raw_tag in cast("list[object]", raw_tags): + if not isinstance(raw_tag, Mapping): + continue + tag = cast("Mapping[str, object]", raw_tag) + name = tag.get("name") + metadata = tag.get("metadata") + if isinstance(name, str): + parsed_tags.append( + SessionTag( + name=name, + metadata=( + cast("Mapping[str, str]", metadata) + if isinstance(metadata, Mapping) + else None + ), + ) + ) + tags = parsed_tags + + def tool_set(key: str, fallback: object) -> object: + value = update.get(key, fallback) + if isinstance(value, list) and all( + isinstance(item, str) for item in cast("list[object]", value) + ): + return frozenset(cast("list[str]", value)) + return fallback + + model = update.get("modelId", current.model) + spec_model = update.get("specModeModelId", current.spec_model) + return SessionSettings( + model=model if isinstance(model, str) else current.model, + reasoning_effort=cast( + "ReasoningEffort", + enum_value( + "reasoningEffort", + ReasoningEffort, + current.reasoning_effort, + ), + ), + mode=cast( + "Mode | None", + enum_value( + "interactionMode", + Mode, + current.mode, + allow_none=True, + ), + ), + autonomy=cast( + "Autonomy | None", + enum_value( + "autonomyLevel", + Autonomy, + current.autonomy, + allow_none=True, + ), + ), + spec_model=( + spec_model + if isinstance(spec_model, str) or spec_model is None + else current.spec_model + ), + spec_reasoning_effort=cast( + "ReasoningEffort | None", + enum_value( + "specModeReasoningEffort", + ReasoningEffort, + current.spec_reasoning_effort, + allow_none=True, + ), + ), + tags=tags, + sandbox=current.sandbox, + additional_tools=cast( + "set[str] | frozenset[str] | None", + tool_set("additionalToolIds", current.additional_tools), + ), + enabled_tools=cast( + "set[str] | frozenset[str] | None", + tool_set("enabledToolIds", current.enabled_tools), + ), + disabled_tools=cast( + "set[str] | frozenset[str] | None", + tool_set("disabledToolIds", current.disabled_tools), + ), + restrict_tools=cast( + "set[str] | frozenset[str] | None", + tool_set("restrictToolIds", current.restrict_tools), + ), + ) + + +def _mcp_summary(value: Any) -> McpStatusSummary: + return McpStatusSummary( + total=value.total, + connected=value.connected, + connecting=value.connecting, + failed=value.failed, + disabled=value.disabled, + config_error=( + None + if value.config_error is None + else McpConfigError(value.config_error.path, value.config_error.message) + ), + ) + + +def _mcp_server(value: Any) -> McpServerStatusInfo: + return McpServerStatusInfo( + name=value.name, + status=McpServerStatus(value.status.value), + source=value.source.value, + is_managed=value.is_managed, + server_type=McpServerType(value.server_type.value), + error=value.error, + tool_count=value.tool_count, + has_auth_tokens=value.has_auth_tokens, + requires_auth=value.requires_auth, + pending_auth_url=value.pending_auth_url, + pending_auth_message=value.pending_auth_message, + pending_auth_state=value.pending_auth_state, + ) + + +__all__ = ["Session", "run"] diff --git a/src/droid_sdk/_high_level/streaming.py b/src/droid_sdk/_high_level/streaming.py new file mode 100644 index 0000000..0b6fbc4 --- /dev/null +++ b/src/droid_sdk/_high_level/streaming.py @@ -0,0 +1,1130 @@ +"""High-level notification conversion and single-consumer stream primitives.""" + +from __future__ import annotations + +import asyncio +import contextlib +import inspect +import json +import math +import time +from collections import deque +from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence +from datetime import datetime, timedelta, timezone +from decimal import Decimal +from typing import TYPE_CHECKING, Any, Generic, NoReturn, cast + +from pydantic import BaseModel, TypeAdapter, ValidationError +from typing_extensions import TypeVar + +from droid_sdk._high_level._immutable import FrozenJsonObject, freeze_json_object +from droid_sdk._high_level.attachments import ( + Base64ImageSource, + PdfDocumentSource, + TextDocumentSource, +) +from droid_sdk._high_level.config import ( + SessionSettingsUpdate, + SessionTag, +) +from droid_sdk._high_level.enums import ( + Autonomy, + ErrorType, + McpAuthOutcome, + McpServerStatus, + McpServerType, + Mode, + ReasoningEffort, + ToolConfirmationOutcome, + WorkingState, +) +from droid_sdk._high_level.extensions import ( + McpConfigError, + McpServerStatusInfo, + McpStatusSummary, +) +from droid_sdk._high_level.messages import ( + AssistantMessage, + ContentBlock, + DocumentBlock, + ErrorEvent, + HookExecution, + ImageBlock, + McpAuthCompleted, + McpAuthRequired, + McpStatusChanged, + Message, + PermissionResolved, + RedactedThinkingBlock, + RunFailure, + RunInterrupted, + RunResult, + RunSuccess, + SessionTitleUpdated, + SessionWorkingDirectoryChanged, + SettingsUpdated, + StreamEvent, + StructuredOutputError, + TextBlock, + TextComplete, + TextDelta, + ThinkingBlock, + ThinkingComplete, + ThinkingDelta, + TokenUsageUpdate, + ToolCall, + ToolCallDelta, + ToolProgress, + ToolProgressUpdate, + ToolResult, + ToolResultBlock, + ToolUseBlock, + Usage, + UserMessage, + WorkingStateChanged, +) +from droid_sdk.errors import DroidProtocolError, StreamIncompleteError +from droid_sdk.schemas import messages as wire_messages +from droid_sdk.schemas.cli import ( + AgentTurnCompletedNotification, + AssistantTextCompleteNotification, + AssistantTextDeltaNotification, + CreateMessageNotification, + DroidWorkingStateChangedNotification, + ErrorNotification, + HookExecutionCompletedNotification, + HookExecutionStartedNotification, + McpAuthCompletedNotification, + McpAuthRequiredNotification, + McpStatusChangedNotification, + PermissionResolvedNotification, + SessionNotification, + SessionNotificationUnion, + SessionTitleUpdatedNotification, + SessionTokenUsageChangedNotification, + SessionWorkingDirectoryChangedNotification, + SettingsUpdatedNotification, + StructuredOutputNotification, + ThinkingTextCompleteNotification, + ThinkingTextDeltaNotification, + ToolCallNotification, + ToolProgressUpdateNotification, + ToolResultNotification, +) +from droid_sdk.schemas.enums import AgentTurnCompletionReason, SessionNotificationType + +if TYPE_CHECKING: + from droid_sdk._high_level.output import OutputAdapter + +T = TypeVar("T") +E = TypeVar("E", bound=object, default=object) +_NOTIFICATION_ADAPTER: TypeAdapter[SessionNotificationUnion] = TypeAdapter( + SessionNotificationUnion +) +_RESULT_TYPES = (RunSuccess, RunInterrupted, RunFailure) +_KNOWN_NOTIFICATION_TYPES = frozenset(item.value for item in SessionNotificationType) + + +def _utc_from_timestamp(value: float) -> datetime: + """Convert the protocol's epoch-millisecond timestamps to aware UTC.""" + return datetime.fromtimestamp(value / 1000, tz=timezone.utc) + + +def _parse_timestamp(value: str) -> datetime: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + if parsed.tzinfo is None or parsed.utcoffset() is None: + raise ValueError("protocol timestamp must be timezone-aware") + return parsed + + +def _duration(milliseconds: float | None) -> timedelta | None: + return None if milliseconds is None else timedelta(milliseconds=milliseconds) + + +def _image_source(source: wire_messages.Base64ImageSource) -> Base64ImageSource: + return Base64ImageSource(data=source.data, media_type=source.media_type) + + +def _document_source( + source: wire_messages.DocumentSource, +) -> TextDocumentSource | PdfDocumentSource: + if isinstance(source, wire_messages.PlainTextSource): + return TextDocumentSource( + data=source.data, + name=source.name, + mime=source.mime, + ) + return PdfDocumentSource( + data=source.data, + parsed_data=source.parsed_data, + name=source.name, + path=source.path, + ) + + +def _content_block(block: wire_messages.ContentBlock) -> ContentBlock: + if isinstance(block, wire_messages.TextBlock): + return TextBlock(id=block.id, text=block.text) + if isinstance(block, wire_messages.ThinkingBlock): + return ThinkingBlock( + id=block.id, + thinking=block.thinking, + signature=block.signature, + signature_provider=block.signature_provider, + duration=_duration(block.duration_ms), + ) + if isinstance(block, wire_messages.RedactedThinkingBlock): + return RedactedThinkingBlock(id=block.id, data=block.data) + if isinstance(block, wire_messages.ToolUseBlock): + return ToolUseBlock( + id=block.id, + name=block.name, + input=block.input, + thought_signature=block.thought_signature, + ) + if isinstance(block, wire_messages.ToolResultBlock): + content: str | Sequence[object] | None + if isinstance(block.content, list): + content = [_content_block(item) for item in block.content] + else: + content = block.content + return ToolResultBlock( + id=block.id, + tool_use_id=block.tool_use_id, + content=cast("Any", content), + is_error=block.is_error, + ) + if isinstance(block, wire_messages.ImageBlock): + return ImageBlock( + id=block.id, + source=_image_source(block.source), + generated=block.generated, + ) + return DocumentBlock(id=block.id, source=_document_source(block.source)) + + +def _conversation_message( + message: wire_messages.FactoryDroidMessage, +) -> UserMessage | AssistantMessage | None: + content = tuple(_content_block(block) for block in message.content) + text = "".join(block.text for block in content if isinstance(block, TextBlock)) + created_at = _utc_from_timestamp(message.created_at) + updated_at = _utc_from_timestamp(message.updated_at) + if message.role is wire_messages.MessageRole.User: + return UserMessage( + id=message.id, + content=content, + text=text, + parent_id=message.parent_id, + created_at=created_at, + updated_at=updated_at, + ) + if message.role is wire_messages.MessageRole.Assistant: + return AssistantMessage( + id=message.id, + content=content, + text=text, + parent_id=message.parent_id, + created_at=created_at, + updated_at=updated_at, + ) + return None + + +def _usage(value: Any) -> Usage: + return Usage( + input_tokens=value.input_tokens, + output_tokens=value.output_tokens, + cache_creation_tokens=value.cache_creation_tokens, + cache_read_tokens=value.cache_read_tokens, + thinking_tokens=value.thinking_tokens, + factory_credits=value.factory_credits, + ) + + +def _tool_progress_update(value: Any) -> ToolProgressUpdate: + timestamp = ( + None if value.timestamp is None else _utc_from_timestamp(value.timestamp) + ) + return ToolProgressUpdate( + type=value.type, + tool_name=value.tool_name, + status=value.status, + details=value.details, + text=value.text, + error=value.error, + timestamp=timestamp, + parameters=value.parameters, + value_snippet=value.value_snippet, + terminal_id=value.terminal_id, + full_output=value.full_output, + subagent_session_id=value.subagent_session_id, + ) + + +def _tool_progress_content(update: ToolProgressUpdate) -> str: + if update.text is not None: + return update.text + if update.status is not None: + return update.status + return update.details or "" + + +def _settings(value: Any) -> SessionSettingsUpdate: + mode = None + if value.interaction_mode is not None and value.interaction_mode.value in { + "auto", + "spec", + }: + mode = Mode(value.interaction_mode.value) + elif value.autonomy_mode is not None: + mode = Mode.SPEC if value.autonomy_mode.value == "spec" else Mode.AUTO + autonomy = ( + None if value.autonomy_level is None else Autonomy(value.autonomy_level.value) + ) + if autonomy is None and value.autonomy_mode is not None: + autonomy = { + "normal": Autonomy.OFF, + "auto-low": Autonomy.LOW, + "auto-medium": Autonomy.MEDIUM, + "auto-high": Autonomy.HIGH, + }.get(value.autonomy_mode.value) + return SessionSettingsUpdate( + model=value.model_id, + reasoning_effort=( + None + if value.reasoning_effort is None + else ReasoningEffort(value.reasoning_effort.value) + ), + mode=mode, + autonomy=autonomy, + spec_model=value.spec_mode_model_id, + spec_reasoning_effort=( + None + if value.spec_mode_reasoning_effort is None + else ReasoningEffort(value.spec_mode_reasoning_effort.value) + ), + tags=( + None + if value.tags is None + else tuple( + SessionTag(name=tag.name, metadata=tag.metadata) for tag in value.tags + ) + ), + additional_tools=( + None + if value.additional_tool_ids is None + else set(value.additional_tool_ids) + ), + enabled_tools=( + None if value.enabled_tool_ids is None else set(value.enabled_tool_ids) + ), + disabled_tools=( + None if value.disabled_tool_ids is None else set(value.disabled_tool_ids) + ), + restrict_tools=( + None if value.restrict_tool_ids is None else set(value.restrict_tool_ids) + ), + compaction_threshold_check_enabled=value.compaction_threshold_check_enabled, + ) + + +def _mcp_status(notification: McpStatusChangedNotification) -> McpStatusChanged: + servers = tuple( + McpServerStatusInfo( + name=server.name, + status=McpServerStatus(server.status.value), + source=server.source.value, + is_managed=server.is_managed, + server_type=McpServerType(server.server_type.value), + error=server.error, + tool_count=server.tool_count, + has_auth_tokens=server.has_auth_tokens, + requires_auth=server.requires_auth, + pending_auth_url=server.pending_auth_url, + pending_auth_message=server.pending_auth_message, + pending_auth_state=server.pending_auth_state, + ) + for server in notification.servers + ) + summary = notification.summary + return McpStatusChanged( + servers=servers, + summary=McpStatusSummary( + total=summary.total, + connected=summary.connected, + connecting=summary.connecting, + failed=summary.failed, + disabled=summary.disabled, + config_error=( + None + if summary.config_error is None + else McpConfigError( + path=summary.config_error.path, + message=summary.config_error.message, + ) + ), + ), + ) + + +def _json_value(value: object) -> object: + if isinstance(value, BaseModel): + return value.model_dump(mode="json", by_alias=True, exclude_none=True) + return value + + +def _json_values(values: list[Any]) -> list[object]: + return [_json_value(value) for value in values] + + +def _javascript_number_string(value: int | float) -> str: + """Return the ECMAScript ``Number::toString`` spelling for finite JSON numbers.""" + number = float(value) + if not math.isfinite(number): + raise ValueError("tool result number must be finite") + if number == 0: + return "0" + + magnitude = abs(number) + text = repr(number).lower() + if "e" in text: + coefficient, exponent_text = text.split("e", 1) + exponent = int(exponent_text) + coefficient = coefficient.rstrip("0").rstrip(".") + if 1e-6 <= magnitude < 1e21: + return format(Decimal(text), "f") + sign = "+" if exponent >= 0 else "" + return f"{coefficient}e{sign}{exponent}" + if text.endswith(".0"): + return text[:-2] + return text + + +def _javascript_string(value: object) -> str: + """Match JavaScript ``String(value)`` for non-array JSON tool results.""" + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, (int, float)): + return _javascript_number_string(value) + if isinstance(value, Mapping): + return "[object Object]" + return str(value) + + +def _notification_type(raw: object) -> str | None: + if not isinstance(raw, Mapping): + return None + payload = cast("Mapping[str, object]", raw) + params = payload.get("params") + if isinstance(params, Mapping): + params_mapping = cast("Mapping[str, object]", params) + notification = params_mapping.get("notification") + if isinstance(notification, Mapping): + payload = cast("Mapping[str, object]", notification) + value = payload.get("type") + return value if isinstance(value, str) else None + + +def _raise_for_invalid_known_notification(raw: object) -> None: + notification_type = _notification_type(raw) + if notification_type in _KNOWN_NOTIFICATION_TYPES: + raise DroidProtocolError( + f"Invalid {notification_type} notification payload" + ) from None + + +def _inner_notification(raw: object) -> SessionNotificationUnion | None: + raw_object: object = raw + if isinstance(raw, SessionNotification): + return raw.params.notification + if isinstance(raw, Mapping): + mapping = cast("Mapping[str, object]", raw) + params = mapping.get("params") + if isinstance(params, Mapping) and "notification" in params: + try: + return SessionNotification.model_validate( + raw_object + ).params.notification + except ValidationError: + _raise_for_invalid_known_notification(raw_object) + return None + try: + return _NOTIFICATION_ADAPTER.validate_python(raw_object) + except ValidationError: + _raise_for_invalid_known_notification(raw_object) + return None + + +def _reject_json_constant(value: str) -> NoReturn: + raise ValueError(f"invalid JSON constant: {value}") + + +def _parse_structured_output(text: str) -> FrozenJsonObject | None: + try: + parsed = cast( + "object", + json.loads(text, parse_constant=_reject_json_constant), + ) + if not isinstance(parsed, Mapping): + return None + return freeze_json_object( + cast("Mapping[str, object]", parsed), + where="structured output", + ) + except (json.JSONDecodeError, TypeError, ValueError): + return None + + +class StreamStateTracker(Generic[T]): + """Convert canonical notifications and retain one turn's result state.""" + + def __init__( + self, + *, + expected_turn_id: str, + session_id: str, + output_adapter: OutputAdapter[T] | None = None, + started_at: float | None = None, + monotonic: Callable[[], float] = time.monotonic, + now: Callable[[], datetime] = lambda: datetime.now(timezone.utc), + ) -> None: + self.expected_turn_id = expected_turn_id + self.session_id = session_id + self.output_adapter = output_adapter + self._monotonic = monotonic + self._started_at = monotonic() if started_at is None else started_at + self._now = now + self._messages: list[Message] = [] + self._errors: list[ErrorEvent] = [] + self._tool_names: dict[str, str] = {} + self._delta_text: list[str] = [] + self._final_assistant_text = "" + self._structured_output: FrozenJsonObject | None = None + self._last_usage: Usage | None = None + self._completed = False + + @property + def completed(self) -> bool: + return self._completed + + @property + def messages(self) -> tuple[Message, ...]: + return tuple(self._messages) + + def queue_error_event(self, event: ErrorEvent) -> ErrorEvent: + self._errors.append(event) + self._messages.append(event) + return event + + def process(self, raw: object) -> tuple[StreamEvent[T], ...]: + if self._completed: + return () + notification = _inner_notification(raw) + if notification is None: + return () + + if isinstance(notification, AgentTurnCompletedNotification): + if notification.turn_id is None: + raise DroidProtocolError( + "Agent turn completion did not include the expected turn ID" + ) + if notification.turn_id != self.expected_turn_id: + return () + result = self._complete(notification) + self._completed = True + return cast("tuple[StreamEvent[T], ...]", (result,)) + + converted = self._convert(notification) + for event in converted: + self._track(event) + return tuple(converted) + + def _track(self, event: StreamEvent[T]) -> None: + if isinstance(event, ToolCall): + self._tool_names[event.tool_use_id] = event.name + elif isinstance(event, ToolCallDelta): + self._tool_names[event.tool_use.id] = event.tool_use.name + elif isinstance(event, TextDelta): + self._delta_text.append(event.text) + elif isinstance(event, AssistantMessage): + self._final_assistant_text = event.text + elif isinstance(event, TokenUsageUpdate): + self._last_usage = Usage( + input_tokens=event.input_tokens, + output_tokens=event.output_tokens, + cache_creation_tokens=event.cache_creation_tokens, + cache_read_tokens=event.cache_read_tokens, + thinking_tokens=event.thinking_tokens, + factory_credits=event.factory_credits, + ) + if isinstance(event, ErrorEvent): + self._errors.append(event) + if isinstance( + event, + ( + UserMessage, + AssistantMessage, + ToolCall, + ToolResult, + HookExecution, + ErrorEvent, + ), + ): + self._messages.append(event) + + def _convert( + self, + notification: SessionNotificationUnion, + ) -> list[StreamEvent[T]]: + if isinstance(notification, AssistantTextDeltaNotification): + return [ + TextDelta( + message_id=notification.message_id, + block_index=notification.block_index, + text=notification.text_delta, + ) + ] + if isinstance(notification, AssistantTextCompleteNotification): + return [ + TextComplete( + message_id=notification.message_id, + block_index=notification.block_index, + ) + ] + if isinstance(notification, ThinkingTextDeltaNotification): + return [ + ThinkingDelta( + message_id=notification.message_id, + block_index=notification.block_index, + text=notification.text_delta, + ) + ] + if isinstance(notification, ThinkingTextCompleteNotification): + return [ + ThinkingComplete( + message_id=notification.message_id, + block_index=notification.block_index, + duration=_duration(notification.duration_ms), + ) + ] + if isinstance(notification, ToolCallNotification): + tool_use = notification.tool_use + return [ + ToolCallDelta( + tool_use=ToolUseBlock( + id=tool_use.id, + name=tool_use.name, + input=tool_use.input, + thought_signature=tool_use.thought_signature, + ) + ) + ] + if isinstance(notification, ToolResultNotification): + raw_content = notification.content + if raw_content is None: + content: str | Sequence[Any] = "" + elif isinstance(raw_content, str): + content = raw_content + elif isinstance(raw_content, list): + items = cast("list[Any]", raw_content) # type: ignore[redundant-cast] + content = _json_values(items) + else: + content = _javascript_string(raw_content) + return [ + ToolResult( + tool_use_id=notification.tool_use_id, + tool_name=self._tool_names.get(notification.tool_use_id, ""), + content=cast("Any", content), + is_error=bool(notification.is_error), + ) + ] + if isinstance(notification, ToolProgressUpdateNotification): + update = _tool_progress_update(notification.update) + return [ + ToolProgress( + tool_use_id=notification.tool_use_id, + tool_name=notification.tool_name, + content=_tool_progress_content(update), + update=update, + ) + ] + if isinstance(notification, DroidWorkingStateChangedNotification): + return [ + WorkingStateChanged(state=WorkingState(notification.new_state.value)) + ] + if isinstance(notification, SessionTokenUsageChangedNotification): + usage = _usage(notification.token_usage) + return [ + TokenUsageUpdate( + input_tokens=usage.input_tokens, + output_tokens=usage.output_tokens, + cache_creation_tokens=usage.cache_creation_tokens, + cache_read_tokens=usage.cache_read_tokens, + thinking_tokens=usage.thinking_tokens, + factory_credits=usage.factory_credits, + ) + ] + if isinstance(notification, CreateMessageNotification): + result: list[StreamEvent[T]] = [] + for block in notification.message.content: + if isinstance(block, wire_messages.ToolUseBlock): + result.append( + ToolCall( + name=block.name, + tool_use_id=block.id, + input=block.input, + ) + ) + message = _conversation_message(notification.message) + if message is not None: + result.append(message) + return result + if isinstance(notification, ErrorNotification): + return [ + ErrorEvent( + message=notification.message, + error_type=ErrorType(notification.error_type.value), + timestamp=_parse_timestamp(notification.timestamp), + ) + ] + if isinstance(notification, PermissionResolvedNotification): + return [ + PermissionResolved( + request_id=notification.request_id, + tool_use_ids=notification.tool_use_ids, + selected_option=ToolConfirmationOutcome( + notification.selected_option.value + ), + ) + ] + if isinstance(notification, SettingsUpdatedNotification): + return [SettingsUpdated(settings=_settings(notification.settings))] + if isinstance(notification, SessionTitleUpdatedNotification): + return [SessionTitleUpdated(title=notification.title)] + if isinstance(notification, SessionWorkingDirectoryChangedNotification): + return [SessionWorkingDirectoryChanged(cwd=notification.cwd)] + if isinstance(notification, McpStatusChangedNotification): + return [_mcp_status(notification)] + if isinstance(notification, McpAuthRequiredNotification): + return [ + McpAuthRequired( + server_name=notification.server_name, + auth_url=notification.auth_url, + message=notification.message, + state=notification.state, + ) + ] + if isinstance(notification, McpAuthCompletedNotification): + return [ + McpAuthCompleted( + server_name=notification.server_name, + outcome=McpAuthOutcome(notification.outcome.value), + message=notification.message, + ) + ] + if isinstance(notification, HookExecutionStartedNotification): + return [ + HookExecution( + hook_id=notification.hook_id, + event_name=notification.hook_event_name, + matcher=notification.hook_matcher, + tool_call_id=notification.hook_tool_call_id, + command=command.command, + timeout=( + None + if command.timeout is None + else timedelta(seconds=command.timeout) + ), + status="started", + ) + for command in notification.hook_commands + ] + if isinstance(notification, HookExecutionCompletedNotification): + if not notification.hook_results: + return [] + return [ + HookExecution( + hook_id=notification.hook_id, + event_name=notification.hook_event_name, + matcher=notification.hook_matcher, + tool_call_id=notification.hook_tool_call_id, + command=result.command, + timeout=( + None + if result.timeout is None + else timedelta(seconds=result.timeout) + ), + status=notification.hook_status, + exit_code=result.exit_code, + stdout=result.stdout, + stderr=result.stderr, + suppress_output=result.suppress_output, + ) + for result in (notification.hook_results or ()) + ] + if isinstance(notification, StructuredOutputNotification): + try: + self._structured_output = ( + None + if notification.structured_output is None + else freeze_json_object( + notification.structured_output, + where="structured output", + ) + ) + except (TypeError, ValueError): + self._structured_output = None + return [] + + def _complete( + self, + notification: AgentTurnCompletedNotification, + ) -> RunResult[T]: + text = self._final_assistant_text or "".join(self._delta_text) + raw: FrozenJsonObject | None = self._structured_output + if raw is None and self.output_adapter is not None: + raw = _parse_structured_output(text) + + output: T | None = None + validation_error: ValidationError | None = None + if self.output_adapter is not None: + try: + adapted = self.output_adapter.adapt(raw) + except (TypeError, ValueError): + pass + else: + output = adapted.output + validation_error = adapted.validation_error + if adapted.structured_output is not None: + raw = adapted.structured_output + + usage = _usage(notification.token_usage) if notification.token_usage else None + if usage is None: + usage = self._last_usage + elapsed = max(0.0, self._monotonic() - self._started_at) + duration = ( + timedelta(seconds=elapsed) + if notification.duration_ms is None + else timedelta(milliseconds=notification.duration_ms) + ) + reason = notification.reason + if reason in { + AgentTurnCompletionReason.Completed, + AgentTurnCompletionReason.SpecHandoff, + }: + return RunSuccess( + text=text, + messages=tuple(self._messages), + usage=usage, + duration=duration, + turn_count=1, + session_id=self.session_id, + output=output, + structured_output=raw, + output_validation_error=validation_error, + ) + if reason in { + AgentTurnCompletionReason.Cancelled, + AgentTurnCompletionReason.PermissionRejected, + }: + return RunInterrupted( + text=text, + messages=tuple(self._messages), + usage=usage, + duration=duration, + turn_count=1, + session_id=self.session_id, + output=output, + structured_output=raw, + output_validation_error=validation_error, + ) + + structured = reason in { + AgentTurnCompletionReason.StructuredOutputMissing, + AgentTurnCompletionReason.StructuredOutputInvalid, + AgentTurnCompletionReason.StructuredOutputSchemaInvalid, + } + error = ( + self._errors[0] + if self._errors + else ErrorEvent( + message=f"Agent turn ended: {reason.value}", + error_type=ErrorType.ERROR, + timestamp=self._now(), + ) + ) + return RunFailure( + subtype=( + "error_structured_output" if structured else "error_during_execution" + ), + error=error, + structured_output_error=( + None + if not structured + else StructuredOutputError( + code=reason.value, + message=error.message, + ) + ), + text=text, + messages=tuple(self._messages), + usage=usage, + duration=duration, + turn_count=1, + session_id=self.session_id, + output=output, + structured_output=raw, + output_validation_error=validation_error, + ) + + +class RunStream(Generic[T, E], AsyncIterator[E]): + """A queue-backed, deterministic single-consumer turn stream.""" + + def __init__( + self, + *, + expected_turn_id: str, + session_id: str, + include_partial_messages: bool = False, + output_adapter: OutputAdapter[T] | None = None, + started_at: float | None = None, + monotonic: Callable[[], float] = time.monotonic, + start: Callable[[RunStream[T, E]], object] | None = None, + finish: Callable[[bool], object] | None = None, + timeout: float | None = None, + ) -> None: + self._tracker = StreamStateTracker( + expected_turn_id=expected_turn_id, + session_id=session_id, + output_adapter=output_adapter, + started_at=started_at, + monotonic=monotonic, + ) + self._include_partial = include_partial_messages + self._queue: deque[StreamEvent[T]] = deque() + self._wakeup = asyncio.Event() + self._result: RunResult[T] | None = None + self._error: BaseException | None = None + self._done = False + self._iteration_claimed = False + self._iterating = False + self._start_callback = start + self._finish_callback = finish + self._monotonic = monotonic + self._started = False + self._released = False + self._timeout = timeout + self._deadline: float | None = None + + @property + def result(self) -> RunResult[T]: + if self._result is None: + raise StreamIncompleteError("The stream has not completed") + return self._result + + @property + def completed(self) -> bool: + return self._result is not None + + def feed_notification(self, notification: object) -> None: + if self._done: + return + if self._deadline is not None and self._monotonic() >= self._deadline: + self._wakeup.set() + return + try: + events = self._tracker.process(notification) + except asyncio.CancelledError: + raise + except Exception as exc: + self.feed_error(exc) + return + for event in events: + if isinstance(event, _RESULT_TYPES): + self._result = cast("RunResult[T]", event) + self._queue.append(event) + self._done = True + elif self._include_partial or isinstance( + event, + ( + UserMessage, + AssistantMessage, + ToolCall, + ToolResult, + HookExecution, + ErrorEvent, + ), + ): + self._queue.append(event) + if events: + self._wakeup.set() + + def queue_error_event(self, event: ErrorEvent) -> None: + if self._done: + return + self._tracker.queue_error_event(event) + self._queue.append(event) + self._wakeup.set() + + def feed_error(self, error: BaseException) -> None: + if isinstance(error, asyncio.CancelledError): + raise error + if self._done: + return + self._error = error + self._done = True + self._wakeup.set() + + async def __aenter__(self) -> RunStream[T, E]: + await self._ensure_started() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + traceback: object, + ) -> None: + await self._release(interrupt=not self._done) + + def __aiter__(self) -> RunStream[T, E]: + if self._iteration_claimed: + raise RuntimeError("RunStream supports exactly one consumer") + self._iteration_claimed = True + self._iterating = True + return self + + async def __anext__(self) -> E: + if not self._iterating: + raise RuntimeError("RunStream must be iterated with 'async for'") + try: + await self._ensure_started() + except asyncio.CancelledError: + self._iterating = False + await asyncio.shield(self._release(interrupt=True)) + raise + except BaseException: + self._iterating = False + await self._release(interrupt=False) + raise + while True: + await self._raise_if_timed_out() + if self._queue: + event = self._queue.popleft() + return cast("E", event) + if self._done: + self._iterating = False + await self._release(interrupt=False) + if self._error is not None: + raise self._error + raise StopAsyncIteration + self._wakeup.clear() + if self._queue or self._done: + continue + try: + if self._deadline is None: + await self._wakeup.wait() + else: + remaining = self._deadline - self._monotonic() + if remaining <= 0: + raise asyncio.TimeoutError + await asyncio.wait_for(self._wakeup.wait(), remaining) + except asyncio.TimeoutError: + await self._raise_timeout() + except asyncio.CancelledError: + await asyncio.shield(self._release(interrupt=True)) + self._iterating = False + raise + + async def _ensure_started(self) -> None: + if self._started: + return + self._started = True + if self._timeout is not None: + if self._timeout <= 0: + self._deadline = self._monotonic() + else: + self._deadline = self._monotonic() + self._timeout + if self._start_callback is not None: + result = self._start_callback(self) + if hasattr(result, "__await__"): + try: + await self._await_before_deadline(cast("Any", result)) + except asyncio.TimeoutError: + await self._raise_timeout() + except asyncio.CancelledError: + await self._release(interrupt=True) + raise + except BaseException: + await self._release(interrupt=False) + raise + + async def _await_before_deadline(self, awaitable: Awaitable[object]) -> None: + if self._deadline is None: + await awaitable + return + remaining = self._deadline - self._monotonic() + if remaining <= 0: + if inspect.iscoroutine(awaitable): + awaitable.close() + raise asyncio.TimeoutError + await asyncio.wait_for(awaitable, timeout=remaining) + + async def _raise_if_timed_out(self) -> None: + if self._deadline is not None and self._monotonic() >= self._deadline: + await self._raise_timeout() + + async def _raise_timeout(self) -> None: + from droid_sdk.errors import RunTimeoutError + + self._queue.clear() + self._result = None + self._error = None + self._done = True + self._iterating = False + await self._release(interrupt=True) + raise RunTimeoutError( + "The run exceeded its timeout", + timeout_duration=self._timeout, + ) from None + + async def _release(self, *, interrupt: bool) -> None: + if self._released: + return + self._released = True + if self._finish_callback is not None: + task: asyncio.Future[object] | None = None + try: + result = self._finish_callback(interrupt) + if hasattr(result, "__await__"): + finish_task = asyncio.ensure_future(cast("Any", result)) + task = finish_task + await asyncio.wait_for( + asyncio.shield(finish_task), + timeout=0.1, + ) + except asyncio.TimeoutError: + if task is not None: + task.add_done_callback(_consume_task_result) + except asyncio.CancelledError: + if task is not None: + task.add_done_callback(_consume_task_result) + raise + except Exception: + # Cleanup and best-effort interruption never mask the primary + # stream outcome. + pass + + async def aclose(self) -> None: + """Interrupt and detach this stream if it is unfinished.""" + await self._release(interrupt=not self._done) + + +def _consume_task_result(task: asyncio.Future[object]) -> None: + with contextlib.suppress(BaseException): + task.result() + + +__all__ = ["RunStream", "StreamStateTracker"] diff --git a/src/droid_sdk/client.py b/src/droid_sdk/client.py index 2b95316..818e753 100644 --- a/src/droid_sdk/client.py +++ b/src/droid_sdk/client.py @@ -1,3 +1,5 @@ +# pyright: reportCallIssue=false, reportUnknownMemberType=false, reportUnknownVariableType=false + """DroidClient — high-level async API for the Factory Droid SDK. Provides typed async methods for all ``droid.*`` JSON-RPC methods, @@ -11,10 +13,11 @@ import contextlib import dataclasses import logging -from collections.abc import AsyncIterator, Callable +from collections.abc import AsyncIterator, Callable, Sequence from types import TracebackType # noqa: TC003 from typing import TYPE_CHECKING, Any, Literal +from droid_sdk._high_level.interaction_adapter import InteractionDispatcher from droid_sdk.errors import ( ConnectionError as DroidConnectionError, ) @@ -26,6 +29,8 @@ MCP_AUTH_TIMEOUT, SESSION_INIT_TIMEOUT, ProtocolEngine, + ProtocolTimingCallback, + TraceMetaInjector, ) from droid_sdk.schemas.cli import ( SessionNotification, @@ -50,6 +55,7 @@ GetContextStatsResult, GetRewindInfoRequestParams, GetRewindInfoResult, + HttpMcpConfig, InitializeSessionRequestParams, InitializeSessionResult, ListCommandsResult, @@ -61,6 +67,7 @@ ListToolsResult, LoadSessionRequestParams, LoadSessionResult, + McpOAuthOptions, OutputFormat, RemoveMcpServerResult, RenameSessionRequestParams, @@ -69,8 +76,12 @@ RewindFileSnapshot, SessionSource, SessionTag, + SetSkillDisabledResult, + SseMcpConfig, + StdioMcpConfig, SubmitBugReportResult, SubmitMcpAuthCodeResult, + SubmitMcpAuthErrorResult, ToggleMcpServerResult, ToggleMcpToolResult, UpdateSessionSettingsRequestParams, @@ -101,6 +112,9 @@ if TYPE_CHECKING: from pydantic import BaseModel + from droid_sdk._high_level.interactions import InteractionHandlers + from droid_sdk._high_level.messages import ErrorEvent as HighLevelErrorEvent + logger = logging.getLogger(__name__) # Type alias for notification listener callbacks @@ -150,6 +164,8 @@ def __init__( exec_path: str | None = None, cwd: str | None = None, env: dict[str, str] | None = None, + trace_meta_injector: TraceMetaInjector | None = None, + timing_callback: ProtocolTimingCallback | None = None, ) -> None: if transport is None and exec_path is None: raise ValueError( @@ -163,6 +179,8 @@ def __init__( self._exec_path = exec_path self._cwd = cwd self._env = env + self._trace_meta_injector = trace_meta_injector + self._timing_callback = timing_callback self._protocol: ProtocolEngine | None = None self._session_id: str | None = None @@ -172,10 +190,12 @@ def __init__( self._notification_listeners: list[ tuple[NotificationCallback, SessionNotificationType | None] ] = [] + self._error_listeners: list[Callable[[Exception], None]] = [] # Client-level server→client request handlers self._permission_handler: Callable[..., Any] | None = None self._ask_user_handler: Callable[..., Any] | None = None + self._interaction_dispatcher: InteractionDispatcher | None = None # ---------------------------------------------------------- # Properties @@ -224,12 +244,18 @@ async def connect(self) -> None: ) # Connect the transport (e.g. spawn subprocess) - await self._transport.connect() + if not self._transport.is_connected: + await self._transport.connect() - self._protocol = ProtocolEngine(transport=self._transport) + self._protocol = ProtocolEngine( + transport=self._transport, + trace_meta_injector=self._trace_meta_injector, + timing_callback=self._timing_callback, + ) # Wire up protocol engine's notification dispatch to client listeners self._protocol.on_notification(self._dispatch_notification) + self._protocol.on_error(self._dispatch_error) # Wire up protocol engine's server→client request handlers self._protocol.set_permission_handler(self._dispatch_permission_request) @@ -252,8 +278,10 @@ async def close(self) -> None: # Clear client-level handlers and listeners self._notification_listeners.clear() + self._error_listeners.clear() self._permission_handler = None self._ask_user_handler = None + self._interaction_dispatcher = None if self._protocol is not None: await self._protocol.close() @@ -301,11 +329,16 @@ async def initialize_session( decomp_session_type: DecompSessionType | None = None, decomp_mission_id: str | None = None, skip_permissions_unsafe: bool | None = None, + compaction_threshold_check_enabled: bool | None = None, + additional_tool_ids: list[str] | None = None, enabled_tool_ids: list[str] | None = None, disabled_tool_ids: list[str] | None = None, + restrict_tool_ids: list[str] | None = None, session_location: str | None = None, session_source: SessionSource | dict[str, Any] | None = None, tags: list[SessionTag | dict[str, Any]] | None = None, + auto_reject_permission_requests: bool | None = None, + disable_builtin_skills: bool | None = None, mcp_oauth_callback_uri: str | None = None, ) -> InitializeSessionResult: """Initialize a new session. @@ -330,13 +363,20 @@ async def initialize_session( decomp_session_type: Session type for mission decomposition. decomp_mission_id: Mission ID for worker sessions. skip_permissions_unsafe: Skip permission checks. + compaction_threshold_check_enabled: Whether to check the context + compaction threshold. + additional_tool_ids: Tool IDs to add to the available catalog. enabled_tool_ids: Additional tool IDs to enable beyond defaults. disabled_tool_ids: Tool IDs to disable (subtractive). Combine with ``enabled_tool_ids=[]`` and an explicit disable list to lock the tool set down. + restrict_tool_ids: Restrict available tools to these IDs. session_location: Session metadata location. session_source: Session source information. tags: Optional session tags. + auto_reject_permission_requests: Whether to reject permission + requests instead of forwarding them. + disable_builtin_skills: Whether builtin skills are unavailable. mcp_oauth_callback_uri: OAuth callback URI for MCP. Returns: @@ -366,6 +406,7 @@ async def initialize_session( cwd=cwd, session_id=session_id, workspace_id=workspace_id, + mcp_servers=_validate_mcp_servers(mcp_servers), autonomy_mode=autonomy_mode, interaction_mode=interaction_mode, autonomy_level=autonomy_level, @@ -376,18 +417,19 @@ async def initialize_session( decomp_session_type=decomp_session_type, decomp_mission_id=decomp_mission_id, skip_permissions_unsafe=skip_permissions_unsafe, + compaction_threshold_check_enabled=compaction_threshold_check_enabled, + additional_tool_ids=additional_tool_ids, enabled_tool_ids=enabled_tool_ids, disabled_tool_ids=disabled_tool_ids, + restrict_tool_ids=restrict_tool_ids, session_location=session_location, session_source=validated_session_source, tags=validated_tags, + auto_reject_permission_requests=auto_reject_permission_requests, + disable_builtin_skills=disable_builtin_skills, mcp_oauth_callback_uri=mcp_oauth_callback_uri, ) ) - # Preserve compatibility with legacy unvalidated MCP dictionaries. - if mcp_servers is not None: - params["mcpServers"] = mcp_servers - response = await protocol.send_request( method=DroidServerMethod.INITIALIZE_SESSION.value, params=params, @@ -404,6 +446,13 @@ async def load_session( session_id: str, mcp_servers: list[dict[str, Any]] | None = None, mcp_oauth_callback_uri: str | None = None, + additional_tool_ids: list[str] | None = None, + enabled_tool_ids: list[str] | None = None, + disabled_tool_ids: list[str] | None = None, + auto_reject_permission_requests: bool | None = None, + disable_builtin_skills: bool | None = None, + session_location: str | None = None, + session_source: SessionSource | dict[str, Any] | None = None, ) -> LoadSessionResult: """Load an existing session. @@ -415,6 +464,14 @@ async def load_session( session_id: Session ID to load. mcp_servers: Optional MCP server configurations. mcp_oauth_callback_uri: OAuth callback URI for MCP. + additional_tool_ids: Tool IDs to add to the available catalog. + enabled_tool_ids: Additional tool IDs to enable beyond defaults. + disabled_tool_ids: Tool IDs to disable (subtractive). + auto_reject_permission_requests: Whether to reject permission + requests instead of forwarding them. + disable_builtin_skills: Whether builtin skills are unavailable. + session_location: Optional session origin/location metadata. + session_source: Optional structured session source metadata. Returns: Typed ``LoadSessionResult`` with session and settings. @@ -427,16 +484,25 @@ async def load_session( self._ensure_not_closed() protocol = self._ensure_protocol() + validated_session_source = ( + SessionSource.model_validate(session_source) + if session_source is not None + else None + ) params = _serialize_params( LoadSessionRequestParams( session_id=session_id, + mcp_servers=_validate_mcp_servers(mcp_servers), mcp_oauth_callback_uri=mcp_oauth_callback_uri, + additional_tool_ids=additional_tool_ids, + enabled_tool_ids=enabled_tool_ids, + disabled_tool_ids=disabled_tool_ids, + auto_reject_permission_requests=auto_reject_permission_requests, + disable_builtin_skills=disable_builtin_skills, + session_location=session_location, + session_source=validated_session_source, ) ) - # Preserve compatibility with legacy unvalidated MCP dictionaries. - if mcp_servers is not None: - params["mcpServers"] = mcp_servers - response = await protocol.send_request( method=DroidServerMethod.LOAD_SESSION.value, params=params, @@ -451,6 +517,7 @@ async def add_user_message( self, *, text: str, + message_id: str | None = None, images: list[Base64ImageSource | dict[str, Any]] | None = None, files: list[DocumentSource | dict[str, Any]] | None = None, output_format: OutputFormat | dict[str, Any] | None = None, @@ -462,6 +529,7 @@ async def add_user_message( Args: text: Message text content. + message_id: Optional stable identifier for the user message. images: Optional attached images. files: Optional attached documents. output_format: Optional structured-output contract. Either an @@ -479,37 +547,23 @@ async def add_user_message( self._ensure_session() protocol = self._ensure_protocol() - validated_output_format = ( - OutputFormat.model_validate(output_format) - if output_format is not None - else None - ) params = _serialize_params( - AddUserMessageRequestParams( - text=text, - output_format=validated_output_format, + AddUserMessageRequestParams.model_validate( + { + "messageId": message_id, + "text": text, + "images": images, + "files": files, + "outputFormat": output_format, + } ) ) - if images is not None: - params["images"] = images - if files is not None: - params["files"] = files - - # Use custom request_id by monkey-patching the protocol temporarily, - # or pass via overridden send_request. The protocol engine generates - # its own IDs. For custom request_id support, we'll use the protocol's - # send_request with a specially constructed envelope. - if request_id is not None: - await protocol.send_request( - method=DroidServerMethod.ADD_USER_MESSAGE.value, - params=params, - request_id=request_id, - ) - else: - await protocol.send_request( - method=DroidServerMethod.ADD_USER_MESSAGE.value, - params=params, - ) + + await protocol.send_request( + method=DroidServerMethod.ADD_USER_MESSAGE.value, + params=params, + request_id=request_id, + ) async def interrupt_session(self) -> None: """Interrupt the current session. @@ -564,8 +618,16 @@ async def update_session_settings( autonomy_level: AutonomyLevel | None = None, spec_mode_model_id: str | None = None, spec_mode_reasoning_effort: ReasoningEffort | None = None, + additional_tool_ids: list[str] | None = None, enabled_tool_ids: list[str] | None = None, disabled_tool_ids: list[str] | None = None, + restrict_tool_ids: list[str] | None = None, + tags: list[SessionTag | dict[str, Any]] | None = None, + compaction_token_limit: int | None = None, + compaction_threshold_check_enabled: bool | None = None, + explicit_null_fields: Sequence[ + Literal["specModeModelId", "specModeReasoningEffort"] + ] = (), ) -> None: """Update session settings. @@ -580,8 +642,14 @@ async def update_session_settings( autonomy_level: Optional autonomy level. spec_mode_model_id: Optional spec mode model ID. spec_mode_reasoning_effort: Optional spec mode reasoning effort. + additional_tool_ids: Tool IDs to add to the available catalog. enabled_tool_ids: Additional tool IDs to enable beyond defaults. disabled_tool_ids: Tool IDs to disable (subtractive). + restrict_tool_ids: Restrict available tools to these IDs. + tags: Optional replacement session tags. + compaction_token_limit: Optional context compaction token limit. + compaction_threshold_check_enabled: Whether to check the context + compaction threshold. Raises: SessionError: If no active session. @@ -592,6 +660,11 @@ async def update_session_settings( self._ensure_session() protocol = self._ensure_protocol() + validated_tags = ( + [SessionTag.model_validate(tag) for tag in tags] + if tags is not None + else None + ) params = _serialize_params( UpdateSessionSettingsRequestParams( model_id=model_id, @@ -601,10 +674,17 @@ async def update_session_settings( autonomy_level=autonomy_level, spec_mode_model_id=spec_mode_model_id, spec_mode_reasoning_effort=spec_mode_reasoning_effort, + additional_tool_ids=additional_tool_ids, enabled_tool_ids=enabled_tool_ids, disabled_tool_ids=disabled_tool_ids, + restrict_tool_ids=restrict_tool_ids, + tags=validated_tags, + compaction_token_limit=compaction_token_limit, + compaction_threshold_check_enabled=compaction_threshold_check_enabled, ) ) + for field in explicit_null_fields: + params[field] = None await protocol.send_request( method=DroidServerMethod.UPDATE_SESSION_SETTINGS.value, @@ -806,6 +886,31 @@ async def submit_mcp_auth_code( return SubmitMcpAuthCodeResult.model_validate(response.get("result", {})) + async def submit_mcp_auth_error( + self, + *, + server_name: str, + error: str, + state: str, + error_description: str | None = None, + ) -> SubmitMcpAuthErrorResult: + """Report an MCP OAuth callback error.""" + self._ensure_not_closed() + self._ensure_session() + protocol = self._ensure_protocol() + + params: dict[str, Any] = { + "serverName": server_name, + "error": error, + "state": state, + } + _set_if_not_none(params, "errorDescription", error_description) + response = await protocol.send_request( + method=DroidServerMethod.SUBMIT_MCP_AUTH_ERROR.value, + params=params, + ) + return SubmitMcpAuthErrorResult.model_validate(response.get("result", {})) + async def add_mcp_server( self, *, @@ -816,6 +921,7 @@ async def add_mcp_server( command: str | None = None, args: list[str] | None = None, env: dict[str, str] | None = None, + oauth: McpOAuthOptions | dict[str, Any] | Literal[False] | None = None, ) -> AddMcpServerResult: """Add an MCP server. @@ -830,6 +936,8 @@ async def add_mcp_server( command: Command to spawn (for stdio servers). args: Command arguments (for stdio servers). env: Environment variables (for stdio servers). + oauth: OAuth options for HTTP/SSE servers, or ``False`` to + explicitly disable OAuth. Returns: Typed ``AddMcpServerResult`` with ``success`` flag. @@ -852,6 +960,13 @@ async def add_mcp_server( _set_if_not_none(params, "command", command) _set_if_not_none(params, "args", args) _set_if_not_none(params, "env", env) + if oauth is not None: + if oauth is False: + params["oauth"] = False + else: + params["oauth"] = _serialize_params( + McpOAuthOptions.model_validate(oauth) + ) response = await protocol.send_request( method=DroidServerMethod.ADD_MCP_SERVER.value, @@ -1039,6 +1154,35 @@ async def list_skills(self) -> ListSkillsResult: return ListSkillsResult.model_validate(response.get("result", {})) + async def set_skill_disabled( + self, + *, + skill_name: str, + disabled: bool, + settings_level: SettingsLevel | None = None, + ) -> SetSkillDisabledResult: + """Enable or disable a skill in user or project settings.""" + self._ensure_not_closed() + self._ensure_session() + protocol = self._ensure_protocol() + + params: dict[str, Any] = { + "skillName": skill_name, + "disabled": disabled, + } + if settings_level not in { + None, + SettingsLevel.User, + SettingsLevel.Project, + }: + raise ValueError("settings_level must be user or project") + _set_if_not_none(params, "settingsLevel", _enum_value(settings_level)) + response = await protocol.send_request( + method=DroidServerMethod.SET_SKILL_DISABLED.value, + params=params, + ) + return SetSkillDisabledResult.model_validate(response.get("result", {})) + async def submit_bug_report( self, *, @@ -1084,8 +1228,16 @@ async def submit_bug_report( async def list_tools( self, *, + model_id: str | None = None, + autonomy_mode: AutonomyMode | None = None, + interaction_mode: DroidInteractionMode | None = None, + autonomy_level: AutonomyLevel | None = None, + spec_mode_model_id: str | None = None, + additional_tool_ids: list[str] | None = None, enabled_tool_ids: list[str] | None = None, disabled_tool_ids: list[str] | None = None, + restrict_tool_ids: list[str] | None = None, + skip_permissions_unsafe: bool | None = None, ) -> ListToolsResult: """List native CLI tools with their allow-state. @@ -1095,9 +1247,18 @@ async def list_tools( ``default_allowed`` and ``currently_allowed``. Args: + model_id: Optional hypothetical model ID. + autonomy_mode: Optional hypothetical deprecated autonomy mode. + interaction_mode: Optional hypothetical interaction mode. + autonomy_level: Optional hypothetical autonomy level. + spec_mode_model_id: Optional hypothetical spec-mode model ID. + additional_tool_ids: Tool IDs to add to the hypothetical catalog. enabled_tool_ids: Optional hypothetical enable list to evaluate ``currently_allowed`` against (does not mutate the session). disabled_tool_ids: Optional hypothetical disable list. + restrict_tool_ids: Restrict the hypothetical catalog to these IDs. + skip_permissions_unsafe: Whether to hypothetically skip permission + checks. Returns: Typed ``ListToolsResult`` with a ``tools`` list. @@ -1111,8 +1272,16 @@ async def list_tools( params = _serialize_params( ListToolsRequestParams( + model_id=model_id, + autonomy_mode=autonomy_mode, + interaction_mode=interaction_mode, + autonomy_level=autonomy_level, + spec_mode_model_id=spec_mode_model_id, + additional_tool_ids=additional_tool_ids, enabled_tool_ids=enabled_tool_ids, disabled_tool_ids=disabled_tool_ids, + restrict_tool_ids=restrict_tool_ids, + skip_permissions_unsafe=skip_permissions_unsafe, ) ) @@ -1592,10 +1761,54 @@ def unsubscribe() -> None: return unsubscribe + def on_error( + self, + callback: Callable[[Exception], None], + ) -> Callable[[], None]: + """Register a listener for terminal transport errors.""" + self._error_listeners.append(callback) + + def unsubscribe() -> None: + with contextlib.suppress(ValueError): + self._error_listeners.remove(callback) + + return unsubscribe + # ---------------------------------------------------------- # Server→client request handlers # ---------------------------------------------------------- + def set_interaction_handlers( + self, + handlers: InteractionHandlers, + *, + error_sink: Callable[[HighLevelErrorEvent], None] | None = None, + ) -> None: + """Register immutable high-level interaction handlers. + + Handler failures return the protocol cancellation response and are + reported to ``error_sink`` as content-free :class:`ErrorEvent` values. + """ + dispatcher = InteractionDispatcher( + handlers, + error_sink=error_sink, + ) + self._permission_handler = None + self._ask_user_handler = None + self._interaction_dispatcher = dispatcher + if self._protocol is not None: + self._protocol.set_permission_handler(self._dispatch_permission_request) + self._protocol.set_ask_user_handler(self._dispatch_ask_user_request) + + def clear_interaction_handlers(self) -> None: + """Clear high-level handlers and restore protocol cancellation defaults.""" + self._permission_handler = None + self._ask_user_handler = None + self._interaction_dispatcher = None + if self._protocol is not None: + self._protocol.set_permission_handler(self._dispatch_permission_request) + self._protocol.set_ask_user_handler(self._dispatch_ask_user_request) + def set_permission_handler(self, handler: Callable[..., Any]) -> None: """Register a handler for server→client permission requests. @@ -1607,6 +1820,7 @@ def set_permission_handler(self, handler: Callable[..., Any]) -> None: Args: handler: Sync or async callable ``(params) -> str``. """ + self._interaction_dispatcher = None self._permission_handler = handler # Update protocol engine if already connected if self._protocol is not None: @@ -1632,6 +1846,7 @@ def set_ask_user_handler(self, handler: Callable[..., Any]) -> None: Args: handler: Sync or async callable ``(params) -> dict``. """ + self._interaction_dispatcher = None self._ask_user_handler = handler if self._protocol is not None: self._protocol.set_ask_user_handler(self._dispatch_ask_user_request) @@ -1674,11 +1889,20 @@ def _dispatch_notification(self, notification: dict[str, Any]) -> None: exc_info=True, ) + def _dispatch_error(self, error: Exception) -> None: + for callback in list(self._error_listeners): + try: + callback(error) + except Exception: + logger.warning("Client error listener raised", exc_info=True) + def _dispatch_permission_request(self, params: dict[str, Any]) -> Any: """Dispatch to the client-level permission handler. If no handler is set, returns the default Cancel outcome. """ + if self._interaction_dispatcher is not None: + return self._interaction_dispatcher.handle_permission(params) handler = self._permission_handler if handler is None: return "cancel" @@ -1689,6 +1913,8 @@ def _dispatch_ask_user_request(self, params: dict[str, Any]) -> Any: If no handler is set, returns the default cancelled response. """ + if self._interaction_dispatcher is not None: + return self._interaction_dispatcher.handle_question(params) handler = self._ask_user_handler if handler is None: return {"cancelled": True, "answers": []} @@ -1736,6 +1962,23 @@ def _serialize_params(model: BaseModel) -> dict[str, Any]: ) +def _validate_mcp_servers( + values: list[dict[str, Any]] | None, +) -> list[StdioMcpConfig | HttpMcpConfig | SseMcpConfig] | None: + if values is None: + return None + result: list[StdioMcpConfig | HttpMcpConfig | SseMcpConfig] = [] + for value in values: + server_type = value.get("type") + if server_type == "http": + result.append(HttpMcpConfig.model_validate(value)) + elif server_type == "sse": + result.append(SseMcpConfig.model_validate(value)) + else: + result.append(StdioMcpConfig.model_validate(value)) + return result + + def _enum_value(val: Any) -> Any: """Extract .value from an enum, or return None.""" if val is None: diff --git a/src/droid_sdk/errors.py b/src/droid_sdk/errors.py index fd862d3..b477843 100644 --- a/src/droid_sdk/errors.py +++ b/src/droid_sdk/errors.py @@ -1,8 +1,7 @@ -"""Error class hierarchy for the Factory Droid SDK. +"""Exception hierarchy for the Factory Droid SDK. -All SDK errors inherit from DroidClientError, which inherits from Exception. -Error classes are namespaced under droid_sdk.errors and do NOT shadow -Python builtins. +The v5 public exceptions all derive from :class:`DroidError`. Legacy names +remain as aliases while the low-level client transitions to the v5 surface. """ from __future__ import annotations @@ -10,8 +9,8 @@ from typing import Any -class DroidClientError(Exception): - """Base exception for all Factory Droid SDK errors.""" +class DroidError(Exception): + """Base class for every SDK-defined exception.""" def __init__(self, message: str) -> None: self.message = message @@ -21,42 +20,8 @@ def __str__(self) -> str: return self.message -class ConnectionError(DroidClientError): - """Raised when a connection to the droid process fails. - - Attributes: - cwd: The working directory used when spawning the process, if available. - exec_path: The executable path used when spawning the process, if available. - """ - - def __init__( - self, - message: str, - *, - cwd: str | None = None, - exec_path: str | None = None, - ) -> None: - self.cwd = cwd - self.exec_path = exec_path - super().__init__(message) - - def __str__(self) -> str: - parts = [self.message] - if self.cwd is not None: - parts.append(f"cwd={self.cwd!r}") - if self.exec_path is not None: - parts.append(f"exec_path={self.exec_path!r}") - return ", ".join(parts) if len(parts) > 1 else parts[0] - - -class TimeoutError(DroidClientError): - """Raised when a request to the droid process times out. - - Attributes: - request_id: The ID of the timed-out request, if available. - method: The RPC method that timed out, if available. - timeout_duration: The timeout duration in seconds, if available. - """ +class RunTimeoutError(DroidError): + """Raised when an operation exceeds its deadline.""" def __init__( self, @@ -79,60 +44,111 @@ def __str__(self) -> str: parts.append(f"method={self.method!r}") if self.timeout_duration is not None: parts.append(f"timeout_duration={self.timeout_duration}") - return ", ".join(parts) if len(parts) > 1 else parts[0] + return ", ".join(parts) + + +class StreamIncompleteError(DroidError): + """Raised when a stream result is read before the stream completes.""" + +class InvalidAttachmentError(DroidError): + """Raised when a local image or document attachment is invalid.""" -class ProtocolError(DroidClientError): - """Raised when a JSON-RPC protocol error occurs. - Attributes: - code: The JSON-RPC error code, if available. - data: Additional error data from the JSON-RPC response, if available. - """ +class SessionError(DroidError): + """Compatibility base for session-specific failures.""" + + +class SessionNotOpenError(SessionError): + """Raised when an operation requires an opened session.""" + + +class SessionBusyError(SessionError): + """Raised when a session already has an active turn.""" + + +class SessionClosedError(SessionError): + """Raised when an operation is attempted on a closed session.""" + + +class SessionReplacedError(SessionError): + """Raised when a successor session has retired this session handle.""" + + def __init__(self, session_id: str, replacement_session_id: str) -> None: + self.session_id = session_id + self.replacement_session_id = replacement_session_id + super().__init__( + f"Session handle {session_id} was replaced by {replacement_session_id}. " + "Use the returned session handle, or resume the original session " + "explicitly." + ) + + +class SessionReplacementError(SessionError): + """Raised when attaching a replacement session or restoring its source fails.""" def __init__( self, - message: str, + session_id: str, + replacement_session_id: str, *, - code: int | None = None, - data: Any | None = None, + rollback_error: BaseException | None = None, ) -> None: - self.code = code - self.data = data + self.session_id = session_id + self.replacement_session_id = replacement_session_id + self.rollback_error = rollback_error + self.rollback_failed = rollback_error is not None + message = ( + f"Created replacement session {replacement_session_id}, but could not " + f"attach it or restore session {session_id}." + if self.rollback_failed + else f"Created replacement session {replacement_session_id}, but could " + "not attach it. The original session handle is still usable." + ) super().__init__(message) - def __str__(self) -> str: - parts = [self.message] - if self.code is not None: - parts.append(f"code={self.code}") - if self.data is not None: - parts.append(f"data={self.data!r}") - return ", ".join(parts) if len(parts) > 1 else parts[0] - - -class SessionError(DroidClientError): - """Raised for session-related errors.""" - class SessionNotFoundError(SessionError): - """Raised when a session cannot be found. - - Constructs a default message of 'Session not found: {session_id}' - when given a session_id. - """ + """Raised when a saved session cannot be found.""" def __init__(self, session_id: str) -> None: self.session_id = session_id super().__init__(f"Session not found: {session_id}") -class ProcessExitError(DroidClientError): - """Raised when the droid subprocess exits unexpectedly. +class InvalidWorkingDirectoryError(SessionError): + """Raised when a requested working directory is unavailable.""" + + def __init__(self, cwd: str, message: str | None = None) -> None: + self.cwd = cwd + super().__init__(message or f"Invalid working directory: {cwd}") + - Attributes: - exit_code: The exit code of the process, if it exited normally. - signal: The signal number that terminated the process, if it was killed. - """ +class DroidConnectionError(DroidError): + """Raised when connecting to or writing to Droid fails.""" + + def __init__( + self, + message: str, + *, + cwd: str | None = None, + exec_path: str | None = None, + ) -> None: + self.cwd = cwd + self.exec_path = exec_path + super().__init__(message) + + def __str__(self) -> str: + parts = [self.message] + if self.cwd is not None: + parts.append(f"cwd={self.cwd!r}") + if self.exec_path is not None: + parts.append(f"exec_path={self.exec_path!r}") + return ", ".join(parts) + + +class DroidProcessError(DroidError): + """Raised when the Droid process exits unexpectedly.""" def __init__( self, @@ -151,15 +167,55 @@ def __str__(self) -> str: parts.append(f"exit_code={self.exit_code}") if self.signal is not None: parts.append(f"signal={self.signal}") - return ", ".join(parts) if len(parts) > 1 else parts[0] + return ", ".join(parts) + + +class DroidProtocolError(DroidError): + """Raised for JSON-RPC negotiation, validation, or server errors.""" + + def __init__( + self, + message: str, + *, + code: int | None = None, + data: Any | None = None, + ) -> None: + self.code = code + self.data = data + super().__init__(message) + + def __str__(self) -> str: + parts = [self.message] + if self.code is not None: + parts.append(f"code={self.code}") + if self.data is not None: + parts.append(f"data={self.data!r}") + return ", ".join(parts) + + +# Temporary low-level compatibility aliases. They intentionally point at the +# v5 classes so catch behavior is identical under old and new imports. +DroidClientError = DroidError +ConnectionError = DroidConnectionError +TimeoutError = RunTimeoutError +ProcessExitError = DroidProcessError +ProtocolError = DroidProtocolError __all__ = [ - "ConnectionError", - "DroidClientError", - "ProcessExitError", - "ProtocolError", + "DroidConnectionError", + "DroidError", + "DroidProcessError", + "DroidProtocolError", + "InvalidAttachmentError", + "InvalidWorkingDirectoryError", + "RunTimeoutError", + "SessionBusyError", + "SessionClosedError", "SessionError", "SessionNotFoundError", - "TimeoutError", + "SessionNotOpenError", + "SessionReplacedError", + "SessionReplacementError", + "StreamIncompleteError", ] diff --git a/src/droid_sdk/low_level/__init__.py b/src/droid_sdk/low_level/__init__.py new file mode 100644 index 0000000..403767e --- /dev/null +++ b/src/droid_sdk/low_level/__init__.py @@ -0,0 +1,43 @@ +# pyright: reportUnsupportedDunderAll=false + +"""Low-level JSON-RPC and transport API. + +This namespace exposes protocol building blocks without adding high-level +session ordering, ownership, or cleanup guarantees. +""" + +from __future__ import annotations + +from droid_sdk.client import DroidClient +from droid_sdk.protocol import ( + COMPACTION_TIMEOUT, + DEFAULT_REQUEST_TIMEOUT, + MCP_AUTH_TIMEOUT, + SESSION_INIT_TIMEOUT, + ProtocolEngine, + ProtocolTiming, + ProtocolTimingCallback, + TraceMetaInjector, +) +from droid_sdk.schemas import * # noqa: F403 +from droid_sdk.schemas import __all__ as _schema_exports +from droid_sdk.transport import ProcessTransport +from droid_sdk.types import DroidClientTransport + +Transport = DroidClientTransport + +__all__ = [ + "COMPACTION_TIMEOUT", + "DEFAULT_REQUEST_TIMEOUT", + "DroidClient", + "DroidClientTransport", + "MCP_AUTH_TIMEOUT", + "ProcessTransport", + "ProtocolEngine", + "ProtocolTiming", + "ProtocolTimingCallback", + "SESSION_INIT_TIMEOUT", + "TraceMetaInjector", + "Transport", + *_schema_exports, +] diff --git a/src/droid_sdk/mcp.py b/src/droid_sdk/mcp.py new file mode 100644 index 0000000..422b1d7 --- /dev/null +++ b/src/droid_sdk/mcp.py @@ -0,0 +1,487 @@ +"""Public MCP configuration and authenticated in-process MCP tools.""" + +# ruff: noqa: TC002 + +from __future__ import annotations + +import asyncio +import inspect +import json +import secrets +import socket +from collections.abc import AsyncGenerator, Awaitable, Callable, Mapping, Sequence +from contextlib import asynccontextmanager, suppress +from dataclasses import dataclass, field +from typing import Any, ParamSpec, cast, get_type_hints, overload + +import uvicorn +from mcp import types as mcp_types +from mcp.server.lowlevel import Server as McpServer +from mcp.server.streamable_http_manager import StreamableHTTPSessionManager +from pydantic import ConfigDict, TypeAdapter, create_model +from starlette.applications import Starlette +from starlette.responses import JSONResponse, Response +from starlette.routing import Route +from starlette.types import Receive, Scope, Send + +from droid_sdk._high_level._immutable import FrozenJsonValue, thaw_json +from droid_sdk._high_level.extensions import ( + DroidTool, + HttpHeader, + HttpMcpServerConfig, + McpOAuthOptions, + McpServerConfig, + SdkMcpServer, + SseMcpServerConfig, + StdioMcpServerConfig, + ToolResponse, +) + +P = ParamSpec("P") + + +def _serialize_structured_content( + adapter: TypeAdapter[Any], + value: object, +) -> dict[str, object]: + validated = adapter.validate_python(value) + dumped = adapter.dump_python( + validated, + mode="json", + by_alias=True, + ) + if not isinstance(dumped, Mapping): + raise TypeError("Structured MCP tools must return an object") + return dict(cast("Mapping[str, object]", dumped)) + + +@overload +def tool( + name: str, + description: str, +) -> Callable[[Callable[P, object]], DroidTool]: ... + + +@overload +def tool( + name: str, + description: str, + function: Callable[P, object], +) -> DroidTool: ... + + +def tool( + name: str, + description: str, + function: Callable[P, object] | None = None, +) -> DroidTool | Callable[[Callable[P, object]], DroidTool]: + """Create a validated MCP tool from an annotated Python callable.""" + + def decorate(handler: Callable[P, object]) -> DroidTool: + signature = inspect.signature(handler) + hints = get_type_hints(handler) + fields: dict[str, Any] = {} + for parameter_name, parameter in signature.parameters.items(): + if parameter.kind in { + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.VAR_POSITIONAL, + inspect.Parameter.VAR_KEYWORD, + }: + raise TypeError("MCP tool parameters must be named parameters") + annotation = hints.get(parameter_name) + if annotation is None: + raise TypeError( + f'MCP tool parameter "{parameter_name}" requires an annotation' + ) + default = ( + ... + if parameter.default is inspect.Parameter.empty + else parameter.default + ) + fields[parameter_name] = (annotation, default) + + arguments_model = create_model( + f"{handler.__name__.title()}Arguments", + __config__=ConfigDict(extra="forbid"), + **fields, + ) + adapter = TypeAdapter(arguments_model) + return_annotation = hints.get("return") + if return_annotation is None: + raise TypeError("MCP tool handlers require a return annotation") + output_adapter: TypeAdapter[Any] | None = None + output_schema: dict[str, Any] | None = None + if return_annotation not in {str, ToolResponse}: + output_adapter = TypeAdapter(return_annotation) + output_schema = output_adapter.json_schema(mode="serialization") + if output_schema.get("type") != "object": + raise TypeError( + "MCP structured tool return annotations must describe an object" + ) + + async def invoke(arguments: Mapping[str, object]) -> str | ToolResponse: + parsed = adapter.validate_python(arguments) + callable_handler = cast("Callable[..., object]", handler) + value: object = callable_handler(**parsed.model_dump()) + if inspect.isawaitable(value): + value = await cast("Awaitable[object]", value) + if isinstance(value, (str, ToolResponse)): + if output_adapter is not None: + if not isinstance(value, ToolResponse): + raise TypeError("Structured MCP tools must return an object") + if value.structured_content is None: + raise TypeError( + "Structured MCP ToolResponse requires structured_content" + ) + structured = _serialize_structured_content( + output_adapter, value.structured_content + ) + return ToolResponse( + content=value.content, + is_error=value.is_error, + structured_content=structured, + ) + return value + if output_adapter is not None: + structured = _serialize_structured_content(output_adapter, value) + return ToolResponse( + content=json.dumps(structured, separators=(",", ":")), + structured_content=structured, + ) + raise TypeError("MCP tool handlers must return str or ToolResponse") + + return DroidTool( + name=name, + description=description, + input_schema=arguments_model.model_json_schema(mode="validation"), + output_schema=output_schema, + handler=invoke, + ) + + return decorate if function is None else decorate(function) + + +def create_sdk_mcp_server( + name: str, + tools: Sequence[DroidTool], + version: str = "1.0.0", +) -> SdkMcpServer: + """Create a restartable loopback-only Streamable HTTP MCP server.""" + return SdkMcpServer(name=name, version=version, tools=tools) + + +@dataclass(slots=True) +class _ServerRuntime: + config: HttpMcpServerConfig + token: str + server: uvicorn.Server + task: asyncio.Task[None] + listener: socket.socket + + +@dataclass(slots=True) +class _ServerLifecycle: + lock: asyncio.Lock = field(default_factory=asyncio.Lock) + start_task: asyncio.Task[HttpMcpServerConfig] | None = None + close_task: asyncio.Task[None] | None = None + start_waiters: int = 0 + + +def _server_lifecycle(server: SdkMcpServer) -> _ServerLifecycle: + lifecycle = cast( + "_ServerLifecycle | None", + object.__getattribute__(server, "_lifecycle"), + ) + if lifecycle is None: + lifecycle = _ServerLifecycle() + object.__setattr__(server, "_lifecycle", lifecycle) + return lifecycle + + +class _BearerEndpoint: + def __init__( + self, + manager: StreamableHTTPSessionManager, + token: str, + ) -> None: + self._manager = manager + self._token = token + + async def __call__( + self, + scope: Scope, + receive: Receive, + send: Send, + ) -> None: + if scope["type"] != "http": + await Response(status_code=404)(scope, receive, send) + return + raw_headers = cast( + "Sequence[tuple[bytes, bytes]]", + scope.get("headers", ()), + ) + authorization: bytes = dict(raw_headers).get(b"authorization", b"") + try: + scheme, supplied = authorization.decode("ascii").split(" ", 1) + except (UnicodeDecodeError, ValueError): + scheme, supplied = "", "" + if scheme.lower() != "bearer" or not secrets.compare_digest( + supplied, + self._token, + ): + await JSONResponse( + { + "jsonrpc": "2.0", + "error": {"code": -32603, "message": "Unauthorized"}, + "id": None, + }, + status_code=401, + headers={"WWW-Authenticate": "Bearer"}, + )(scope, receive, send) + return + await self._manager.handle_request(scope, receive, send) + + +def _create_mcp_application(server: SdkMcpServer, token: str) -> Starlette: + low_level = McpServer(server.name, version=server.version) + tools_by_name = {item.name: item for item in server.tools} + + @low_level.list_tools() # type: ignore[untyped-decorator,no-untyped-call] + async def _list_tools() -> list[mcp_types.Tool]: + return [ + mcp_types.Tool( + name=item.name, + description=item.description, + inputSchema=cast( + "dict[str, Any]", + thaw_json(cast("FrozenJsonValue", item.input_schema)), + ), + outputSchema=( + None + if item.output_schema is None + else cast( + "dict[str, Any]", + thaw_json(cast("FrozenJsonValue", item.output_schema)), + ) + ), + ) + for item in server.tools + ] + + @low_level.call_tool(validate_input=True) # type: ignore[untyped-decorator] + async def _call_tool( + name: str, + arguments: dict[str, Any], + ) -> mcp_types.CallToolResult: + selected = tools_by_name.get(name) + if selected is None: + raise ValueError(f"Unknown tool: {name}") + value = selected.handler(arguments) + if inspect.isawaitable(value): + value = await cast("Awaitable[object]", value) + if isinstance(value, str): + return mcp_types.CallToolResult( + content=[mcp_types.TextContent(type="text", text=value)] + ) + if not isinstance(value, ToolResponse): + raise TypeError("MCP tool handlers must return str or ToolResponse") + return mcp_types.CallToolResult( + content=[mcp_types.TextContent(type="text", text=value.content)], + isError=value.is_error, + structuredContent=( + None + if value.structured_content is None + else cast( + "dict[str, Any]", + thaw_json(cast("FrozenJsonValue", value.structured_content)), + ) + ), + ) + + _registered_handlers = (_list_tools, _call_tool) + + manager = StreamableHTTPSessionManager( + app=low_level, + stateless=True, + json_response=True, + ) + + @asynccontextmanager + async def lifespan(_app: Starlette) -> AsyncGenerator[None, None]: + async with manager.run(): + yield + + return Starlette( + routes=[Route("/mcp", endpoint=_BearerEndpoint(manager, token))], + lifespan=lifespan, + ) + + +def sdk_server_config(server: SdkMcpServer) -> HttpMcpServerConfig | None: + runtime = cast( + "_ServerRuntime | None", + object.__getattribute__(server, "_runtime"), + ) + return None if runtime is None else runtime.config + + +async def start_sdk_server(server: SdkMcpServer) -> HttpMcpServerConfig: + lifecycle = _server_lifecycle(server) + async with lifecycle.lock: + current = cast( + "_ServerRuntime | None", + object.__getattribute__(server, "_runtime"), + ) + if current is not None and ( + lifecycle.close_task is None or lifecycle.close_task.done() + ): + return current.config + if lifecycle.start_task is not None and not lifecycle.start_task.done(): + task = lifecycle.start_task + elif lifecycle.close_task is not None and not lifecycle.close_task.done(): + task = asyncio.create_task(_start_after_close(server, lifecycle.close_task)) + lifecycle.start_task = task + else: + task = asyncio.create_task(_start_sdk_server_impl(server)) + lifecycle.start_task = task + lifecycle.start_waiters += 1 + cancelled = False + try: + return await asyncio.shield(task) + except asyncio.CancelledError: + cancelled = True + raise + finally: + lifecycle.start_waiters -= 1 + if cancelled and lifecycle.start_waiters == 0 and lifecycle.start_task is task: + lifecycle.start_task = None + lifecycle.close_task = asyncio.create_task(_close_after_start(server, task)) + + +async def _start_after_close( + server: SdkMcpServer, + close_task: asyncio.Task[None], +) -> HttpMcpServerConfig: + with suppress(BaseException): + await close_task + return await _start_sdk_server_impl(server) + + +async def _start_sdk_server_impl(server: SdkMcpServer) -> HttpMcpServerConfig: + token = secrets.token_urlsafe(32) + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + uvicorn_server: uvicorn.Server | None = None + task: asyncio.Task[None] | None = None + try: + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listener.bind(("127.0.0.1", 0)) + listener.listen() + listener.setblocking(False) + port = cast("tuple[str, int]", listener.getsockname())[1] + app = _create_mcp_application(server, token) + uvicorn_server = uvicorn.Server( + uvicorn.Config( + app, + host="127.0.0.1", + port=port, + log_level="critical", + access_log=False, + lifespan="on", + ) + ) + task = asyncio.create_task(uvicorn_server.serve(sockets=[listener])) + for _ in range(500): + if uvicorn_server.started: + break + if task.done(): + await task + raise RuntimeError("SDK MCP server stopped during startup") + await asyncio.sleep(0.01) + else: + raise RuntimeError("Timed out starting SDK MCP server") + config = HttpMcpServerConfig( + name=server.name, + url=f"http://127.0.0.1:{port}/mcp", + headers=(HttpHeader("Authorization", f"Bearer {token}"),), + oauth=False, + ) + runtime = _ServerRuntime(config, token, uvicorn_server, task, listener) + object.__setattr__(server, "_runtime", runtime) + return config + except BaseException: + if uvicorn_server is not None: + uvicorn_server.should_exit = True + listener.close() + if task is not None: + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + raise + + +async def close_sdk_server(server: SdkMcpServer) -> None: + lifecycle = _server_lifecycle(server) + async with lifecycle.lock: + if lifecycle.start_task is not None and not lifecycle.start_task.done(): + task = asyncio.create_task(_close_after_start(server, lifecycle.start_task)) + lifecycle.start_task = None + lifecycle.close_task = task + elif lifecycle.close_task is not None and not lifecycle.close_task.done(): + task = lifecycle.close_task + else: + runtime = cast( + "_ServerRuntime | None", + object.__getattribute__(server, "_runtime"), + ) + if runtime is None: + return + task = asyncio.create_task(_close_sdk_server_impl(server, runtime)) + lifecycle.close_task = task + await asyncio.shield(task) + + +async def _close_after_start( + server: SdkMcpServer, + start_task: asyncio.Task[HttpMcpServerConfig], +) -> None: + try: + await start_task + except BaseException: + return + runtime = cast( + "_ServerRuntime | None", + object.__getattribute__(server, "_runtime"), + ) + if runtime is not None: + await _close_sdk_server_impl(server, runtime) + + +async def _close_sdk_server_impl( + server: SdkMcpServer, + runtime: _ServerRuntime, +) -> None: + runtime.server.should_exit = True + try: + await asyncio.wait_for(runtime.task, timeout=5) + except asyncio.TimeoutError: + runtime.task.cancel() + await asyncio.gather(runtime.task, return_exceptions=True) + finally: + runtime.listener.close() + if object.__getattribute__(server, "_runtime") is runtime: + object.__setattr__(server, "_runtime", None) + + +__all__ = [ + "DroidTool", + "HttpHeader", + "HttpMcpServerConfig", + "McpOAuthOptions", + "McpServerConfig", + "SdkMcpServer", + "SseMcpServerConfig", + "StdioMcpServerConfig", + "ToolResponse", + "create_sdk_mcp_server", + "tool", +] diff --git a/src/droid_sdk/observability.py b/src/droid_sdk/observability.py new file mode 100644 index 0000000..7fc6275 --- /dev/null +++ b/src/droid_sdk/observability.py @@ -0,0 +1,232 @@ +"""Synchronous, best-effort observability contracts and helpers.""" + +# ruff: noqa: TC001, TC003 + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Literal, Protocol, runtime_checkable + +from droid_sdk._high_level._immutable import Scalar, freeze_scalar_mapping +from droid_sdk.protocol import ProtocolTiming + + +@dataclass(frozen=True, slots=True) +class SerializedError: + message: str + name: str | None = None + code: str | None = None + + +@dataclass(frozen=True, slots=True) +class LogEvent: + level: Literal["debug", "info", "warn", "error"] + name: str + message: str + attributes: Mapping[str, Scalar] | None = None + error: SerializedError | None = None + + def __post_init__(self) -> None: + if self.attributes is not None: + object.__setattr__( + self, "attributes", freeze_scalar_mapping(self.attributes) + ) + + +@runtime_checkable +class Logger(Protocol): + def log(self, event: LogEvent) -> None: ... + + +@dataclass(frozen=True, slots=True) +class MetricEvent: + name: str + kind: Literal["counter", "histogram"] + value: int | float + unit: Literal["1", "ms"] + attributes: Mapping[str, Scalar] | None = None + + def __post_init__(self) -> None: + if self.attributes is not None: + object.__setattr__( + self, "attributes", freeze_scalar_mapping(self.attributes) + ) + + +@runtime_checkable +class MetricSink(Protocol): + def record(self, event: MetricEvent) -> None: ... + + +@dataclass(slots=True) +class TraceContext: + traceparent: str | None = None + tracestate: str | None = None + + +@runtime_checkable +class TraceContextProvider(Protocol): + def inject(self, carrier: TraceContext) -> None: ... + + +@dataclass(frozen=True, slots=True) +class Observability: + logger: Logger | None = None + metrics: MetricSink | None = None + tracing: TraceContextProvider | None = None + + +def serialize_error(error: object) -> SerializedError: + if isinstance(error, BaseException): + code_value = getattr(error, "code", None) + code = code_value if isinstance(code_value, str) else None + return SerializedError( + name=type(error).__name__, + message=str(error), + code=code, + ) + return SerializedError(message=str(error)) + + +def emit_log( + observability: Observability | None, + event: LogEvent, +) -> bool: + sink = observability.logger if observability is not None else None + if sink is None: + return False + try: + sink.log(event) + except Exception: + return False + return True + + +def record_metric( + observability: Observability | None, + event: MetricEvent, +) -> bool: + sink = observability.metrics if observability is not None else None + if sink is None: + return False + try: + sink.record(event) + except Exception: + return False + return True + + +def inject_trace_context( + observability: Observability | None, + carrier: TraceContext, +) -> bool: + sink = observability.tracing if observability is not None else None + if sink is None: + return False + try: + sink.inject(carrier) + except Exception: + # A throwing provider must not leave partial context behind. + carrier.traceparent = None + carrier.tracestate = None + return False + return True + + +class ObservabilityAdapter: + """Content-free callbacks accepted by :class:`ProtocolEngine`.""" + + __slots__ = ("_observability",) + + def __init__(self, observability: Observability | None) -> None: + self._observability = observability + + def trace_meta_injector(self, metadata: dict[str, str]) -> None: + carrier = TraceContext() + if not inject_trace_context(self._observability, carrier): + return + if carrier.traceparent is not None: + metadata["traceparent"] = carrier.traceparent + if carrier.tracestate is not None: + metadata["tracestate"] = carrier.tracestate + + def timing_callback(self, timing: ProtocolTiming) -> None: + self.record_request_timing( + method=timing.method, + duration_seconds=timing.duration_seconds, + outcome=timing.outcome, + ) + self.log( + level="info" if timing.outcome == "success" else "error", + name="droid.sdk.request", + message="Droid request completed", + attributes={ + "method": timing.method, + "status": timing.outcome, + "duration_ms": timing.duration_seconds * 1000, + }, + ) + + def log( + self, + *, + level: Literal["debug", "info", "warn", "error"], + name: str, + message: str, + attributes: Mapping[str, Scalar] | None = None, + error: BaseException | None = None, + ) -> None: + serialized = ( + None + if error is None + else SerializedError( + name=type(error).__name__, + message="Droid SDK operation failed", + ) + ) + emit_log( + self._observability, + LogEvent( + level=level, + name=name, + message=message, + attributes=attributes, + error=serialized, + ), + ) + + def record_request_timing( + self, + *, + method: str, + duration_seconds: float, + outcome: str, + ) -> None: + """Emit one content-free protocol duration through the metric sink.""" + record_metric( + self._observability, + MetricEvent( + name="droid.sdk.request.duration", + kind="histogram", + value=duration_seconds * 1000, + unit="ms", + attributes={ + "method": method, + "outcome": outcome, + }, + ), + ) + + def record_run_terminal(self, *, status: str) -> None: + """Count a content-free high-level run terminal outcome.""" + record_metric( + self._observability, + MetricEvent( + name="droid.sdk.run.terminal", + kind="counter", + value=1, + unit="1", + attributes={"status": status}, + ), + ) diff --git a/src/droid_sdk/permissions.py b/src/droid_sdk/permissions.py new file mode 100644 index 0000000..6f866d4 --- /dev/null +++ b/src/droid_sdk/permissions.py @@ -0,0 +1,31 @@ +"""Permission action models.""" + +from droid_sdk._high_level.interactions import ( + ApplyPatchAction, + ApplyPatchFile, + AskUserAction, + AskUserParseError, + CreateFile, + DroidShieldViolationAction, + EditAction, + ExecuteAction, + ExitSpecModeAction, + McpToolAction, + Plan, + SandboxViolationAction, +) + +__all__ = [ + "ApplyPatchAction", + "ApplyPatchFile", + "AskUserAction", + "AskUserParseError", + "CreateFile", + "DroidShieldViolationAction", + "EditAction", + "ExecuteAction", + "ExitSpecModeAction", + "McpToolAction", + "Plan", + "SandboxViolationAction", +] diff --git a/src/droid_sdk/protocol.py b/src/droid_sdk/protocol.py index a9e87ef..c18728f 100644 --- a/src/droid_sdk/protocol.py +++ b/src/droid_sdk/protocol.py @@ -20,21 +20,22 @@ import contextlib import json import logging +import time import uuid -from collections.abc import Callable # noqa: TC003 -from typing import Any, Final +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, Final, cast + +from pydantic import BaseModel from droid_sdk.errors import ( - ConnectionError as DroidConnectionError, -) -from droid_sdk.errors import ( - DroidClientError, - ProtocolError, + DroidConnectionError, + DroidError, + DroidProtocolError, + InvalidWorkingDirectoryError, + RunTimeoutError, SessionNotFoundError, ) -from droid_sdk.errors import ( - TimeoutError as DroidTimeoutError, -) from droid_sdk.schemas.constants import ( FACTORY_PROTOCOL_VERSION, JSONRPC_VERSION, @@ -45,6 +46,20 @@ logger = logging.getLogger(__name__) +TraceMetaInjector = Callable[[dict[str, str]], None] + + +@dataclass(frozen=True, slots=True) +class ProtocolTiming: + """Content-free completion timing for a JSON-RPC method.""" + + method: str + duration_seconds: float + outcome: str + + +ProtocolTimingCallback = Callable[[ProtocolTiming], None] + # Timeout constants (in seconds, matching TypeScript SDK) DEFAULT_REQUEST_TIMEOUT: Final[float] = 30.0 """Standard timeout for quick request/response operations (30 seconds).""" @@ -94,9 +109,13 @@ def __init__( *, transport: DroidClientTransport, default_timeout: float = DEFAULT_REQUEST_TIMEOUT, + trace_meta_injector: TraceMetaInjector | None = None, + timing_callback: ProtocolTimingCallback | None = None, ) -> None: self._transport = transport self._default_timeout = default_timeout + self._trace_meta_injector = trace_meta_injector + self._timing_callback = timing_callback # Pending requests keyed by UUID string self._pending_requests: dict[str, _PendingRequest] = {} @@ -106,6 +125,7 @@ def __init__( # Notification listeners self._notification_listeners: list[Callable[[dict[str, Any]], None]] = [] + self._error_listeners: list[Callable[[Exception], None]] = [] # Server→client request handlers self._permission_handler: Callable[[dict[str, Any]], Any] | None = None @@ -133,6 +153,16 @@ async def start(self) -> None: """ self._reader_task = asyncio.create_task(self._read_loop()) + def on_error(self, callback: Callable[[Exception], None]) -> Callable[[], None]: + """Subscribe to terminal transport errors.""" + self._error_listeners.append(callback) + + def unsubscribe() -> None: + with contextlib.suppress(ValueError): + self._error_listeners.remove(callback) + + return unsubscribe + async def _read_loop(self) -> None: """Consume messages from the transport iterator.""" try: @@ -176,13 +206,16 @@ async def send_request( DroidConnectionError: If transport is not connected. DroidClientError: If the engine is closed or a sticky error exists. """ + started_at = time.monotonic() # Check closed state if self._closed: - raise DroidClientError("Protocol engine is closed") + self._record_timing(method, started_at, "connection_error") + raise DroidConnectionError("Protocol engine is closed") # Check sticky transport error if self._transport_error is not None: - raise DroidClientError(f"Transport error: {self._transport_error}") + self._record_timing(method, started_at, "connection_error") + raise self._transport_error effective_timeout = timeout if timeout is not None else self._default_timeout @@ -198,6 +231,23 @@ async def send_request( "method": method, "params": params, } + if self._trace_meta_injector is not None: + carrier: dict[str, str] = {} + try: + self._trace_meta_injector(carrier) + except Exception as exc: + logger.debug( + "Trace metadata injector failed: exception_type=%s", + type(exc).__name__, + ) + else: + safe_meta = { + key: value + for key, value in carrier.items() + if key in {"traceparent", "tracestate"} + } + if safe_meta: + envelope["_meta"] = safe_meta # Create future loop = asyncio.get_running_loop() @@ -212,10 +262,15 @@ async def send_request( # Send via transport try: await self._transport.send(json.dumps(envelope)) + except asyncio.CancelledError: + self._pending_requests.pop(request_id, None) + self._record_timing(method, started_at, "cancelled") + raise except Exception as send_exc: # Clean up pending and re-raise self._pending_requests.pop(request_id, None) - if isinstance(send_exc, DroidClientError): + self._record_timing(method, started_at, "connection_error") + if isinstance(send_exc, DroidError): raise raise DroidConnectionError( f"Failed to send request: {send_exc}" @@ -226,12 +281,26 @@ async def send_request( response = await asyncio.wait_for(future, timeout=effective_timeout) except asyncio.TimeoutError: self._pending_requests.pop(request_id, None) - raise DroidTimeoutError( + self._record_timing(method, started_at, "timeout") + raise RunTimeoutError( f"Request {method} timed out after {effective_timeout}s", request_id=request_id, method=method, timeout_duration=effective_timeout, ) from None + except asyncio.CancelledError: + self._pending_requests.pop(request_id, None) + self._record_timing(method, started_at, "cancelled") + raise + except Exception: + self._record_timing(method, started_at, "error") + raise + + self._record_timing( + method, + started_at, + "error" if response.get("error") is not None else "success", + ) # Check for error response and map to exceptions if "error" in response and response["error"] is not None: @@ -240,21 +309,34 @@ async def send_request( # Guard against non-dict error payloads if not isinstance(error_obj, dict): obj_type = type(error_obj).__name__ - raise ProtocolError( + raise DroidProtocolError( f"Malformed error response: expected dict, got {obj_type}", code=JsonRpcErrorCode.PARSE_ERROR.value, ) - code = error_obj.get("code") - message = error_obj.get("message", "Unknown error") - data = error_obj.get("data") + typed_error = cast("dict[str, Any]", error_obj) + raw_code = typed_error.get("code") + code = raw_code if isinstance(raw_code, int) else None + message = str(typed_error.get("message", "Unknown error")) + data: Any = typed_error.get("data") - if code == JsonRpcErrorCode.ENTITY_NOT_FOUND.value: + if ( + code == JsonRpcErrorCode.ENTITY_NOT_FOUND.value + and method == "droid.load_session" + ): # Extract session_id from params if available session_id = params.get("sessionId", request_id) raise SessionNotFoundError(str(session_id)) - raise ProtocolError( + if ( + code == JsonRpcErrorCode.INVALID_PARAMS.value + and method == "droid.initialize_session" + and "cwd" in params + and _looks_like_invalid_cwd(message, data) + ): + raise InvalidWorkingDirectoryError(str(params["cwd"]), message) + + raise DroidProtocolError( message, code=code, data=data, @@ -348,7 +430,9 @@ async def close(self) -> None: self._reader_task = None # Reject all pending - error = DroidClientError("Protocol engine closed: pending requests cancelled") + error = DroidConnectionError( + "Protocol engine closed: pending requests cancelled" + ) self._reject_all_pending(error) # Cancel all in-flight server→client request handler tasks @@ -444,7 +528,7 @@ def _handle_response(self, response: dict[str, Any]) -> None: # Malformed response — reject with ProtocolError if not pending.future.done(): pending.future.set_exception( - ProtocolError( + DroidProtocolError( "Malformed response: missing 'result' and 'error'", code=JsonRpcErrorCode.PARSE_ERROR.value, ) @@ -463,10 +547,10 @@ def _handle_notification(self, notification: dict[str, Any]) -> None: for listener in list(self._notification_listeners): try: listener(notification) - except Exception: + except Exception as exc: logger.warning( - "Notification listener raised an exception", - exc_info=True, + "Notification listener raised: exception_type=%s", + type(exc).__name__, ) async def _handle_server_request(self, request: dict[str, Any]) -> None: @@ -503,21 +587,22 @@ async def _handle_permission_request( try: result = handler(params) - if asyncio.iscoroutine(result) or asyncio.isfuture(result): - selected_option = await result - else: - selected_option = result + permission_result = await _resolve_handler_result(result) await self._send_response( request_id, - result={"selectedOption": selected_option}, + result=_serialize_permission_result(permission_result), ) except Exception as exc: - logger.warning("Permission handler raised: %s", exc, exc_info=True) + diagnostic = _handler_error_diagnostic(exc) + logger.warning( + "Permission handler raised: exception_type=%s", + diagnostic["exceptionType"], + ) await self._send_error_response( request_id, code=JsonRpcErrorCode.INTERNAL_ERROR.value, message="Failed to handle permission request", - data=str(exc), + data=diagnostic, ) async def _handle_ask_user_request( @@ -538,21 +623,22 @@ async def _handle_ask_user_request( try: result = handler(params) - if asyncio.iscoroutine(result) or asyncio.isfuture(result): - ask_result = await result - else: - ask_result = result + ask_result = await _resolve_handler_result(result) await self._send_response( request_id, - result=ask_result, + result=_serialize_question_result(ask_result), ) except Exception as exc: - logger.warning("Ask-user handler raised: %s", exc, exc_info=True) + diagnostic = _handler_error_diagnostic(exc) + logger.warning( + "Ask-user handler raised: exception_type=%s", + diagnostic["exceptionType"], + ) await self._send_error_response( request_id, code=JsonRpcErrorCode.INTERNAL_ERROR.value, message="Failed to handle ask-user request", - data=str(exc), + data=diagnostic, ) # ---------------------------------------------------------- @@ -564,8 +650,40 @@ def _handle_transport_error(self, error: Exception) -> None: Sets the sticky transport error and rejects all pending requests. """ - self._transport_error = error - self._reject_all_pending(DroidClientError(f"Transport error: {error}")) + connection_error = ( + error + if isinstance(error, DroidError) + else DroidConnectionError(f"Transport error: {error}") + ) + self._transport_error = connection_error + self._reject_all_pending(connection_error) + for callback in list(self._error_listeners): + try: + callback(connection_error) + except Exception as exc: + logger.warning( + "Protocol error listener raised: exception_type=%s", + type(exc).__name__, + ) + + def _record_timing(self, method: str, started_at: float, outcome: str) -> None: + """Invoke the content-free timing callback on a best-effort basis.""" + callback = self._timing_callback + if callback is None: + return + try: + callback( + ProtocolTiming( + method=method, + duration_seconds=max(0.0, time.monotonic() - started_at), + outcome=outcome, + ) + ) + except Exception as exc: + logger.debug( + "Protocol timing callback failed: exception_type=%s", + type(exc).__name__, + ) # ---------------------------------------------------------- # Internal: Response helpers @@ -587,11 +705,11 @@ async def _send_response( } try: await self._transport.send(json.dumps(response)) - except Exception: + except Exception as exc: logger.warning( - "Failed to send response for request %s", + "Failed to send response for request %s: exception_type=%s", request_id, - exc_info=True, + type(exc).__name__, ) async def _send_error_response( @@ -616,11 +734,11 @@ async def _send_error_response( } try: await self._transport.send(json.dumps(response)) - except Exception: + except Exception as exc: logger.warning( - "Failed to send error response for request %s", + "Failed to send error response for request %s: exception_type=%s", request_id, - exc_info=True, + type(exc).__name__, ) def _reject_all_pending(self, error: Exception) -> None: @@ -633,10 +751,68 @@ def _reject_all_pending(self, error: Exception) -> None: req.future.set_exception(error) +def _looks_like_invalid_cwd(message: Any, data: Any) -> bool: + """Return whether an INVALID_PARAMS response identifies the cwd.""" + description = f"{message} {data}".lower() + return any( + marker in description + for marker in ("cwd", "working directory", "working_directory") + ) + + +def _handler_error_diagnostic(error: Exception) -> dict[str, str]: + """Return content-free diagnostics safe for logs and JSON-RPC responses.""" + return {"exceptionType": type(error).__name__} + + +def _model_dump(value: Any) -> dict[str, Any] | None: + if not isinstance(value, BaseModel): + return None + return value.model_dump(by_alias=True, exclude_none=True) + + +async def _resolve_handler_result(value: Any) -> Any: + if asyncio.iscoroutine(value) or asyncio.isfuture(value): + return await value + return value + + +def _serialize_permission_result(value: Any) -> dict[str, Any]: + """Serialize legacy outcomes and complete permission response models.""" + model_result = _model_dump(value) + if model_result is not None: + return model_result + if isinstance(value, dict): + result = dict(cast("dict[str, Any]", value)) + aliases = { + "selected_option": "selectedOption", + "edited_spec_content": "editedSpecContent", + } + for python_name, wire_name in aliases.items(): + if python_name in result: + result[wire_name] = result.pop(python_name) + return result + selected_option = getattr(value, "value", value) + return {"selectedOption": selected_option} + + +def _serialize_question_result(value: Any) -> dict[str, Any]: + """Serialize complete ask-user response dictionaries or Pydantic models.""" + model_result = _model_dump(value) + if model_result is not None: + return model_result + if isinstance(value, dict): + return dict(cast("dict[str, Any]", value)) + raise TypeError("Ask-user handler must return a response mapping") + + __all__ = [ "COMPACTION_TIMEOUT", "DEFAULT_REQUEST_TIMEOUT", "MCP_AUTH_TIMEOUT", "SESSION_INIT_TIMEOUT", "ProtocolEngine", + "ProtocolTiming", + "ProtocolTimingCallback", + "TraceMetaInjector", ] diff --git a/src/droid_sdk/schemas/__init__.py b/src/droid_sdk/schemas/__init__.py index 468ead2..c8734a4 100644 --- a/src/droid_sdk/schemas/__init__.py +++ b/src/droid_sdk/schemas/__init__.py @@ -1,3 +1,5 @@ +# pyright: reportUnusedImport=false + """Pydantic schema definitions for the Factory Droid protocol. Re-exports all public schema models, enums, and constants for @@ -7,6 +9,7 @@ from __future__ import annotations from droid_sdk.schemas.cli import ( + AgentTurnCompletedNotification, ApplyPatchToolConfirmationDetails, AskUserCollectedAnswer, AskUserConfirmationDetails, @@ -16,16 +19,25 @@ AskUserRequest, AskUserRequestParams, AskUserResult, + AssistantTextCompleteNotification, AssistantTextDeltaNotification, + ChildSessionAvailableNotification, CliRequestOrNotification, CreateMessageNotification, CreateToolConfirmationDetails, + DroidShieldViolationConfirmationDetails, DroidWorkingStateChangedNotification, EditToolConfirmationDetails, ErrorDetail, ErrorNotification, ExecuteToolConfirmationDetails, ExitSpecModeConfirmationDetails, + HookCommand, + HookExecutionCompletedNotification, + HookExecutionStartedNotification, + HookResult, + LlmRetryNotification, + LoopStateChangedNotification, McpAuthCompletedNotification, McpAuthRequiredNotification, McpStatusChangedNotification, @@ -38,25 +50,35 @@ MissionWorkerStartedNotification, PermissionResolvedNotification, ProposeMissionConfirmationDetails, + QueuedMessagesDiscardedNotification, RequestPermissionRequest, RequestPermissionRequestParams, RequestPermissionResult, + SandboxViolationConfirmationDetails, + SessionCompactedNotification, SessionNotification, SessionNotificationParams, SessionTitleUpdatedNotification, SessionTokenUsageChangedNotification, + SessionWorkingDirectoryChangedNotification, SettingsUpdatedNotification, SettingsUpdatedPayload, StartMissionRunConfirmationDetails, + StructuredOutputNotification, + ThinkingTextCompleteNotification, ThinkingTextDeltaNotification, + ToolCallNotification, ToolConfirmationDetails, ToolConfirmationInfo, + ToolExecutionHeartbeatNotification, + ToolExecutionPhaseChangedNotification, ToolProgressUpdate, ToolProgressUpdateNotification, ToolResultNotification, ToolUse, ) from droid_sdk.schemas.client import ( + AcpSessionSource, AddMcpServerRequest, AddMcpServerRequestParams, AddMcpServerResponse, @@ -65,10 +87,12 @@ AddUserMessageRequestParams, AddUserMessageResponse, AddUserMessageResult, + ApiSessionSource, AuthenticateMcpServerRequest, AuthenticateMcpServerRequestParams, AuthenticateMcpServerResponse, AuthenticateMcpServerResult, + AutomationSessionSource, AvailableModelConfig, Base64ImageSource, CancelMcpAuthRequest, @@ -93,7 +117,7 @@ ContextBreakdownMcpServerEntry, ContextBreakdownSkillEntry, CustomCommandInfo, - DocumentSource, + DesktopSessionSource, ExecToolInfo, ExecuteRewindRequest, ExecuteRewindRequestParams, @@ -126,10 +150,12 @@ InterruptSessionRequestParams, InterruptSessionResponse, InterruptSessionResult, + JiraSessionSource, KillWorkerSessionRequest, KillWorkerSessionRequestParams, KillWorkerSessionResponse, KillWorkerSessionResult, + LinearSessionSource, ListCommandsRequest, ListCommandsRequestParams, ListCommandsResponse, @@ -158,8 +184,15 @@ LoadSessionRequestParams, LoadSessionResponse, LoadSessionResult, + McpOAuthOptions, + MicrosoftTeamsSessionSource, MissionSnapshot, OutputFormat, + PendingAskUserRequest, + PendingPermissionRequest, + QueuedUserMessage, + ReadinessEvaluationSessionSource, + ReadinessRemediationSessionSource, RemoveMcpServerRequest, RemoveMcpServerRequestParams, RemoveMcpServerResponse, @@ -171,11 +204,19 @@ RewindEvictedFile, RewindFileCreation, RewindFileSnapshot, + SandboxStatus, + SessionData, + SessionsApiSessionSource, SessionSettings, SessionSource, SessionTag, + SetSkillDisabledRequest, + SetSkillDisabledRequestParams, + SetSkillDisabledResponse, + SetSkillDisabledResult, SkillInfo, SkillResource, + SlackSessionSource, SseMcpConfig, StdioMcpConfig, SubmitBugReportRequest, @@ -186,6 +227,10 @@ SubmitMcpAuthCodeRequestParams, SubmitMcpAuthCodeResponse, SubmitMcpAuthCodeResult, + SubmitMcpAuthErrorRequest, + SubmitMcpAuthErrorRequestParams, + SubmitMcpAuthErrorResponse, + SubmitMcpAuthErrorResult, ToggleMcpServerRequest, ToggleMcpServerRequestParams, ToggleMcpServerResponse, @@ -195,10 +240,15 @@ ToggleMcpToolResponse, ToggleMcpToolResult, TokenUsage, + TuiSessionSource, + UnknownSessionSource, UpdateSessionSettingsRequest, UpdateSessionSettingsRequestParams, UpdateSessionSettingsResponse, UpdateSessionSettingsResult, + WebSessionSource, + WikiCISetupSessionSource, + WikiGenerationSessionSource, WorkerStateInfo, ) from droid_sdk.schemas.constants import ( @@ -209,9 +259,11 @@ LEGACY_FACTORY_API_VERSION, ) from droid_sdk.schemas.enums import ( + AgentTurnCompletionReason, AutonomyLevel, AutonomyMode, # noqa: F401 # deprecated; kept for backward compat ClientType, + ContextStatsAccuracy, DecompSessionType, DismissalType, DroidClientMethod, @@ -226,7 +278,9 @@ IssueSeverity, JsonRpcErrorCode, JsonRpcMessageType, + LlmRetryReason, McpAuthOutcome, + McpOAuthTokenEndpointAuthMethod, McpServerStatus, McpServerType, McpStatus, @@ -235,13 +289,20 @@ Platform, ProgressLogEntryType, ReasoningEffort, + SandboxMode, + SandboxOperationType, + SandboxViolationReason, + SandboxViolationType, SessionNotificationType, + SessionPlatform, SettingsLevel, SkillLocation, ToolConfirmationOutcome, ToolConfirmationType, + ToolExecutionLifecyclePhase, ) from droid_sdk.schemas.mcp import ( + McpConfigError, McpHttpServerConfigFields, McpRegistryServer, McpServerStatusInfo, @@ -253,18 +314,22 @@ ToolConfirmationListItem, ) from droid_sdk.schemas.messages import ( + Base64PDFSource, ContentBlock, DocumentBlock, + DocumentSource, DocumentSourceType, FactoryDroidMessage, ImageBlock, MessageContentBlockType, MessageRole, MessageVisibility, + PlainTextSource, RedactedThinkingBlock, TextBlock, ThinkingBlock, ToolResultBlock, + ToolResultContent, ToolUseBlock, ) from droid_sdk.schemas.mission import ( @@ -293,6 +358,7 @@ WorkerSelectedFeatureEntry, WorkerStartedEntry, ) +from droid_sdk.schemas.session import LastCallTokenUsage from droid_sdk.schemas.shared import ( BaseNotification, BaseRequest, @@ -307,7 +373,7 @@ TraceContextMeta, ) -__all__: list[str] = [ +__all__: list[str] = [ # noqa: RUF022 # --- constants --- "FACTORY_CLIENT_HEADER", "FACTORY_CLIENT_VERSION", @@ -601,4 +667,70 @@ "WorkerSelectedFeatureEntry", "WorkerStartedEntry", "WorkerStateInfo", + # --- v5 protocol additions --- + "AgentTurnCompletedNotification", + "AgentTurnCompletionReason", + "AssistantTextCompleteNotification", + "Base64PDFSource", + "ChildSessionAvailableNotification", + "DroidShieldViolationConfirmationDetails", + "HookCommand", + "HookExecutionCompletedNotification", + "HookExecutionStartedNotification", + "HookResult", + "LlmRetryNotification", + "LoopStateChangedNotification", + "McpConfigError", + "McpOAuthOptions", + "PlainTextSource", + "QueuedMessagesDiscardedNotification", + "SandboxMode", + "SandboxOperationType", + "SandboxStatus", + "SandboxViolationConfirmationDetails", + "SandboxViolationReason", + "SandboxViolationType", + "SessionCompactedNotification", + "SessionWorkingDirectoryChangedNotification", + "StructuredOutputNotification", + "ThinkingTextCompleteNotification", + "ToolCallNotification", + "ToolExecutionHeartbeatNotification", + "ToolExecutionLifecyclePhase", + "ToolExecutionPhaseChangedNotification", + # --- canonical v5 contract completions --- + "AcpSessionSource", + "ApiSessionSource", + "AutomationSessionSource", + "ContextStatsAccuracy", + "DesktopSessionSource", + "JiraSessionSource", + "LastCallTokenUsage", + "LinearSessionSource", + "LlmRetryReason", + "McpOAuthTokenEndpointAuthMethod", + "MicrosoftTeamsSessionSource", + "PendingAskUserRequest", + "PendingPermissionRequest", + "QueuedUserMessage", + "ReadinessEvaluationSessionSource", + "ReadinessRemediationSessionSource", + "SessionData", + "SessionPlatform", + "SessionsApiSessionSource", + "SetSkillDisabledRequest", + "SetSkillDisabledRequestParams", + "SetSkillDisabledResponse", + "SetSkillDisabledResult", + "SlackSessionSource", + "SubmitMcpAuthErrorRequest", + "SubmitMcpAuthErrorRequestParams", + "SubmitMcpAuthErrorResponse", + "SubmitMcpAuthErrorResult", + "ToolResultContent", + "TuiSessionSource", + "UnknownSessionSource", + "WebSessionSource", + "WikiCISetupSessionSource", + "WikiGenerationSessionSource", ] diff --git a/src/droid_sdk/schemas/cli.py b/src/droid_sdk/schemas/cli.py index 689827e..ac4544a 100644 --- a/src/droid_sdk/schemas/cli.py +++ b/src/droid_sdk/schemas/cli.py @@ -1,3 +1,5 @@ +# pyright: reportIncompatibleVariableOverride=false + """Server→client CLI schemas (notifications, permission requests, ask-user). Ported from TypeScript source: @@ -14,23 +16,28 @@ from typing import Annotated, Any, Literal -from pydantic import BaseModel, ConfigDict, Field, RootModel +from pydantic import BaseModel, ConfigDict, Field, RootModel, model_validator -# Re-use TokenUsage from client module -from droid_sdk.schemas.client import TokenUsage # noqa: TC001 -from droid_sdk.schemas.enums import ( # noqa: TC001 +from droid_sdk.schemas.enums import ( + AgentTurnCompletionReason, AutonomyLevel, AutonomyMode, DroidClientMethod, DroidErrorType, DroidInteractionMode, DroidWorkingState, + LlmRetryReason, McpAuthOutcome, MissionState, ReasoningEffort, + SandboxMode, + SandboxOperationType, + SandboxViolationReason, + SandboxViolationType, SessionNotificationType, ToolConfirmationOutcome, ToolConfirmationType, + ToolExecutionLifecyclePhase, ) from droid_sdk.schemas.mcp import ( # noqa: TC001 McpServerStatusInfo, @@ -42,12 +49,18 @@ MissionFeature, ProgressLogEntry, ) +from droid_sdk.schemas.session import ( # noqa: TC001 + LastCallTokenUsage, + SessionTag, + TokenUsage, +) from droid_sdk.schemas.shared import ( JsonRpcNotification, JsonRpcRequest, ) __all__ = [ + "AgentTurnCompletedNotification", "ApplyPatchToolConfirmationDetails", "AskUserCollectedAnswer", "AskUserConfirmationDetails", @@ -57,10 +70,13 @@ "AskUserRequest", "AskUserRequestParams", "AskUserResult", + "AssistantTextCompleteNotification", "AssistantTextDeltaNotification", + "ChildSessionAvailableNotification", "CliRequestOrNotification", "CreateMessageNotification", "CreateToolConfirmationDetails", + "DroidShieldViolationConfirmationDetails", "DroidWorkingStateChangedNotification", "EditToolConfirmationDetails", "ErrorDetail", @@ -68,6 +84,11 @@ "ExecuteToolConfirmationDetails", "ExitSpecModeConfirmationDetails", "FactoryDroidMessage", + "HookCommand", + "HookExecutionCompletedNotification", + "HookExecutionStartedNotification", + "HookResult", + "LoopStateChangedNotification", "McpAuthCompletedNotification", "McpAuthRequiredNotification", "McpStatusChangedNotification", @@ -80,19 +101,29 @@ "MissionWorkerStartedNotification", "PermissionResolvedNotification", "ProposeMissionConfirmationDetails", + "QueuedMessagesDiscardedNotification", "RequestPermissionRequest", "RequestPermissionRequestParams", "RequestPermissionResult", + "SandboxStatus", + "SandboxViolationConfirmationDetails", + "SessionCompactedNotification", "SessionNotification", "SessionNotificationParams", "SessionTitleUpdatedNotification", "SessionTokenUsageChangedNotification", + "SessionWorkingDirectoryChangedNotification", "SettingsUpdatedNotification", "SettingsUpdatedPayload", "StartMissionRunConfirmationDetails", + "StructuredOutputNotification", + "ThinkingTextCompleteNotification", "ThinkingTextDeltaNotification", + "ToolCallNotification", "ToolConfirmationDetails", "ToolConfirmationInfo", + "ToolExecutionHeartbeatNotification", + "ToolExecutionPhaseChangedNotification", "ToolProgressUpdate", "ToolProgressUpdateNotification", "ToolResultNotification", @@ -173,6 +204,9 @@ class ToolProgressUpdate(BaseModel): subagent_session_id: str | None = Field(default=None, alias="subagentSessionId") """Optional spawned subagent session ID.""" + terminal_id: str | None = Field(default=None, alias="terminalId") + full_output: str | None = Field(default=None, alias="fullOutput") + class SettingsUpdatedPayload(BaseModel): """Settings payload within SettingsUpdatedNotification.""" @@ -206,6 +240,17 @@ class SettingsUpdatedPayload(BaseModel): ) """Optional spec mode reasoning effort override.""" + additional_tool_ids: list[str] | None = Field( + default=None, alias="additionalToolIds" + ) + enabled_tool_ids: list[str] | None = Field(default=None, alias="enabledToolIds") + disabled_tool_ids: list[str] | None = Field(default=None, alias="disabledToolIds") + restrict_tool_ids: list[str] | None = Field(default=None, alias="restrictToolIds") + tags: list[SessionTag] | None = None + compaction_threshold_check_enabled: bool | None = Field( + default=None, alias="compactionThresholdCheckEnabled" + ) + # ============================================================ # 20 notification payload types @@ -309,6 +354,26 @@ class DroidWorkingStateChangedNotification(BaseModel): """New working state.""" +class SessionCompactedNotification(BaseModel): + """Conversation compaction boundary update.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.SESSION_COMPACTED] + summary_id: str = Field(alias="summaryId") + removed_count: int = Field(alias="removedCount", ge=0) + visible_boundary_message_id: str | None = Field(alias="visibleBoundaryMessageId") + + +class LoopStateChangedNotification(BaseModel): + """Deprecated loop-state update retained for wire compatibility.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.LOOP_STATE_CHANGED] + loop_state: dict[str, Any] = Field(alias="loopState") + + class PermissionResolvedNotification(BaseModel): """Permission resolved notification.""" @@ -335,6 +400,7 @@ class SettingsUpdatedNotification(BaseModel): type: Literal[SessionNotificationType.SETTINGS_UPDATED] """Notification type discriminator.""" + request_id: str | None = Field(default=None, alias="requestId") settings: SettingsUpdatedPayload """Updated settings.""" @@ -347,10 +413,33 @@ class SessionTitleUpdatedNotification(BaseModel): type: Literal[SessionNotificationType.SESSION_TITLE_UPDATED] """Notification type discriminator.""" + request_id: str | None = Field(default=None, alias="requestId") title: str """New session title.""" +class SessionWorkingDirectoryChangedNotification(BaseModel): + """Working-directory update.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.SESSION_WORKING_DIRECTORY_CHANGED] + cwd: str + + +class ChildSessionAvailableNotification(BaseModel): + """Notification that a delegated child session is available.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.CHILD_SESSION_AVAILABLE] + child_session_id: str = Field(alias="childSessionId") + tool_use_id: str | None = Field(default=None, alias="toolUseId") + subagent_type: str | None = Field(default=None, alias="subagentType") + description: str | None = None + timestamp: float + + class McpStatusChangedNotification(BaseModel): """MCP status changed notification.""" @@ -384,6 +473,26 @@ class AssistantTextDeltaNotification(BaseModel): """Text delta content.""" +class AssistantTextCompleteNotification(BaseModel): + """Marks completion of a streamed assistant text block.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.ASSISTANT_TEXT_COMPLETE] + message_id: str = Field(alias="messageId") + block_index: int = Field(alias="blockIndex") + + +class StructuredOutputNotification(BaseModel): + """Structured output produced for a message.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.STRUCTURED_OUTPUT] + message_id: str = Field(alias="messageId") + structured_output: dict[str, Any] | None = Field(alias="structuredOutput") + + class ThinkingTextDeltaNotification(BaseModel): """Thinking text delta notification (streaming thinking token).""" @@ -402,6 +511,17 @@ class ThinkingTextDeltaNotification(BaseModel): """Text delta content.""" +class ThinkingTextCompleteNotification(BaseModel): + """Marks completion of a streamed thinking block.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.THINKING_TEXT_COMPLETE] + message_id: str = Field(alias="messageId") + block_index: int = Field(alias="blockIndex") + duration_ms: float | None = Field(default=None, alias="durationMs", ge=0) + + class SessionTokenUsageChangedNotification(BaseModel): """Session token usage changed notification.""" @@ -416,6 +536,32 @@ class SessionTokenUsageChangedNotification(BaseModel): token_usage: TokenUsage = Field(alias="tokenUsage") """Updated token usage.""" + inclusive_token_usage: TokenUsage | None = Field( + default=None, alias="inclusiveTokenUsage" + ) + last_call_token_usage: LastCallTokenUsage | None = Field( + default=None, alias="lastCallTokenUsage" + ) + + +class AgentTurnCompletedNotification(BaseModel): + """Terminal notification for an agent turn.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.AGENT_TURN_COMPLETED] + reason: AgentTurnCompletionReason + turn_id: str | None = Field(default=None, alias="turnId") + token_usage: TokenUsage = Field(alias="tokenUsage") + cumulative_token_usage: TokenUsage | None = Field( + default=None, alias="cumulativeTokenUsage" + ) + child_token_usage: TokenUsage | None = Field(default=None, alias="childTokenUsage") + cumulative_child_token_usage: TokenUsage | None = Field( + default=None, alias="cumulativeChildTokenUsage" + ) + duration_ms: float | None = Field(default=None, alias="durationMs", ge=0) + class MissionStateChangedNotification(BaseModel): """Mission state changed notification.""" @@ -428,6 +574,8 @@ class MissionStateChangedNotification(BaseModel): state: MissionState """New mission state.""" + updated_at: str | None = Field(default=None, alias="updatedAt") + class MissionFeaturesChangedNotification(BaseModel): """Mission features changed notification.""" @@ -531,6 +679,131 @@ class McpAuthCompletedNotification(BaseModel): """Authentication result message.""" +class HookCommand(BaseModel): + """Command configured for a hook.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + command: str + timeout: float | None = None + + +class HookResult(BaseModel): + """Result of a hook command.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + exit_code: int = Field(alias="exitCode") + stdout: str + stderr: str + command: str | None = None + timeout: float | None = None + suppress_output: bool | None = Field(default=None, alias="suppressOutput") + + +class HookExecutionStartedNotification(BaseModel): + """Hook execution began.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.HOOK_EXECUTION_STARTED] + hook_id: str = Field(alias="hookId") + hook_event_name: str = Field(alias="hookEventName") + hook_matcher: str | None = Field(default=None, alias="hookMatcher") + hook_commands: list[HookCommand] = Field(alias="hookCommands") + hook_tool_call_id: str | None = Field(default=None, alias="hookToolCallId") + hook_parent_id: str | None = Field(default=None, alias="hookParentId") + hook_order: int | None = Field(default=None, alias="hookOrder") + hidden_from_user_views: bool | None = Field( + default=None, alias="hiddenFromUserViews" + ) + is_parallel_execution: bool | None = Field( + default=None, alias="isParallelExecution" + ) + parallel_group_id: str | None = Field(default=None, alias="parallelGroupId") + + +class HookExecutionCompletedNotification(BaseModel): + """Hook execution completed.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.HOOK_EXECUTION_COMPLETED] + hook_id: str = Field(alias="hookId") + hook_event_name: str | None = Field(default=None, alias="hookEventName") + hook_matcher: str | None = Field(default=None, alias="hookMatcher") + hook_tool_call_id: str | None = Field(default=None, alias="hookToolCallId") + hook_parent_id: str | None = Field(default=None, alias="hookParentId") + hook_order: int | None = Field(default=None, alias="hookOrder") + hook_prevented_action: bool | None = Field( + default=None, alias="hookPreventedAction" + ) + hidden_from_user_views: bool | None = Field( + default=None, alias="hiddenFromUserViews" + ) + hook_status: Literal["completed", "error"] = Field(alias="hookStatus") + hook_results: list[HookResult] | None = Field(default=None, alias="hookResults") + + +class ToolCallNotification(BaseModel): + """Completed tool-call input notification.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.TOOL_CALL] + tool_use: ToolUse = Field(alias="toolUse") + + +class QueuedMessagesDiscardedNotification(BaseModel): + """Queued messages were discarded.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.QUEUED_MESSAGES_DISCARDED] + text: str + request_id: str | None = Field(default=None, alias="requestId") + + +class ToolExecutionHeartbeatNotification(BaseModel): + """Internal heartbeat for a long-running tool.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.TOOL_EXECUTION_HEARTBEAT] + tool_use_id: str = Field(alias="toolUseId") + tool_name: str = Field(alias="toolName") + + +class ToolExecutionPhaseChangedNotification(BaseModel): + """Tool execution lifecycle update.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.TOOL_EXECUTION_PHASE_CHANGED] + tool_use_id: str = Field(alias="toolUseId") + tool_name: str = Field(alias="toolName") + phase: ToolExecutionLifecyclePhase + + +class LlmRetryNotification(BaseModel): + """Coarse LLM retry status.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[SessionNotificationType.LLM_RETRY] + attempt: int + reason: LlmRetryReason + + +class SandboxStatus(BaseModel): + """Current sandbox status.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + enabled: bool + mode: SandboxMode | None = None + + # ============================================================ # SessionNotification discriminated union # ============================================================ @@ -541,13 +814,21 @@ class McpAuthCompletedNotification(BaseModel): | CreateMessageNotification | ErrorNotification | DroidWorkingStateChangedNotification + | SessionCompactedNotification + | LoopStateChangedNotification | PermissionResolvedNotification | SettingsUpdatedNotification | SessionTitleUpdatedNotification + | SessionWorkingDirectoryChangedNotification + | ChildSessionAvailableNotification | McpStatusChangedNotification | AssistantTextDeltaNotification + | AssistantTextCompleteNotification + | StructuredOutputNotification | ThinkingTextDeltaNotification + | ThinkingTextCompleteNotification | SessionTokenUsageChangedNotification + | AgentTurnCompletedNotification | MissionStateChangedNotification | MissionFeaturesChangedNotification | MissionProgressEntryNotification @@ -555,7 +836,14 @@ class McpAuthCompletedNotification(BaseModel): | MissionWorkerStartedNotification | MissionWorkerCompletedNotification | McpAuthRequiredNotification - | McpAuthCompletedNotification, + | McpAuthCompletedNotification + | HookExecutionStartedNotification + | HookExecutionCompletedNotification + | ToolCallNotification + | QueuedMessagesDiscardedNotification + | ToolExecutionHeartbeatNotification + | ToolExecutionPhaseChangedNotification + | LlmRetryNotification, Field(discriminator="type"), ] @@ -568,6 +856,8 @@ class SessionNotificationParams(BaseModel): notification: SessionNotificationUnion """Discriminated notification payload.""" + session_id: str | None = Field(default=None, alias="sessionId") + class SessionNotification(JsonRpcNotification): """Full session notification with JSON-RPC envelope. @@ -632,6 +922,8 @@ class ExecuteToolConfirmationDetails(BaseModel): impact_level: str | None = Field(default=None, alias="impactLevel") """Optional impact level assessment.""" + risk_level_reason: str | None = Field(default=None, alias="riskLevelReason") + class CreateToolConfirmationDetails(BaseModel): """Create tool confirmation details.""" @@ -763,6 +1055,8 @@ class ApplyPatchToolConfirmationDetails(BaseModel): new_content: str | None = Field(default=None, alias="newContent") """Optional new content.""" + files: list[dict[str, Any]] | None = None + class McpToolConfirmationDetails(BaseModel): """MCP tool confirmation details.""" @@ -778,6 +1072,36 @@ class McpToolConfirmationDetails(BaseModel): impact_level: str = Field(alias="impactLevel") """Impact level assessment.""" + server_name: str | None = Field(default=None, alias="serverName") + actual_tool_name: str | None = Field(default=None, alias="actualToolName") + + +class SandboxViolationConfirmationDetails(BaseModel): + """Sandbox policy violation confirmation details.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[ToolConfirmationType.SandboxViolation] + violating_tool_name: str = Field(alias="violatingToolName") + target: str + operation_type: SandboxOperationType = Field(alias="operationType") + violation_type: SandboxViolationType = Field(alias="violationType") + reason: str + violation_reason: SandboxViolationReason | None = Field( + default=None, alias="violationReason" + ) + is_org_deny: bool = Field(alias="isOrgDeny") + + +class DroidShieldViolationConfirmationDetails(BaseModel): + """DroidShield command-policy violation details.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[ToolConfirmationType.DroidShieldViolation] + command: str + reason: str + ToolConfirmationDetailsUnion = Annotated[ EditToolConfirmationDetails @@ -788,7 +1112,9 @@ class McpToolConfirmationDetails(BaseModel): | ProposeMissionConfirmationDetails | StartMissionRunConfirmationDetails | ApplyPatchToolConfirmationDetails - | McpToolConfirmationDetails, + | McpToolConfirmationDetails + | SandboxViolationConfirmationDetails + | DroidShieldViolationConfirmationDetails, Field(discriminator="type"), ] @@ -831,6 +1157,10 @@ class RequestPermissionRequestParams(BaseModel): options: list[ToolConfirmationListItem] """Available permission options.""" + associated_session_ids: list[str] | None = Field( + default=None, alias="associatedSessionIds" + ) + class RequestPermissionRequest(JsonRpcRequest): """Request for permission from the server (server→client).""" @@ -852,6 +1182,21 @@ class RequestPermissionResult(BaseModel): selected_option: ToolConfirmationOutcome = Field(alias="selectedOption") """Selected permission outcome.""" + comment: str | None = None + edited_spec_content: str | None = Field(default=None, alias="editedSpecContent") + + @model_validator(mode="after") + def require_edited_spec_content(self) -> RequestPermissionResult: + """Require edited content for the proceed-edit outcome.""" + if ( + self.selected_option == ToolConfirmationOutcome.ProceedEdit + and self.edited_spec_content is None + ): + raise ValueError( + "editedSpecContent is required when selectedOption is proceed_edit" + ) + return self + # ============================================================ # AskUserRequest @@ -875,6 +1220,8 @@ class AskUserQuestion(BaseModel): options: list[str] """Available options.""" + multi_select: bool | None = Field(default=None, alias="multiSelect") + class AskUserRequestParams(BaseModel): """Parameters for droid.ask_user request.""" diff --git a/src/droid_sdk/schemas/client.py b/src/droid_sdk/schemas/client.py index 2ba33ce..a24fd1e 100644 --- a/src/droid_sdk/schemas/client.py +++ b/src/droid_sdk/schemas/client.py @@ -1,6 +1,8 @@ +# pyright: reportIncompatibleVariableOverride=false + """Client→server request/response Pydantic schemas for the Factory Droid protocol. -All 29 client→server RPC method request/response pairs, plus supporting types +All supported client→server RPC method request/response pairs, plus supporting types and the ClientRequest discriminated union. Ported from TypeScript source: @@ -9,20 +11,38 @@ from __future__ import annotations +import re from typing import Annotated, Any, Literal +from urllib.parse import urlsplit + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + RootModel, + field_validator, + model_validator, +) -from pydantic import BaseModel, ConfigDict, Field, RootModel - -from droid_sdk.schemas.enums import ( # noqa: TC001 +from droid_sdk.schemas.cli import ( + AskUserRequestParams, + RequestPermissionRequestParams, +) +from droid_sdk.schemas.enums import ( AutonomyLevel, AutonomyMode, + ContextStatsAccuracy, DecompSessionType, DroidInteractionMode, DroidServerMethod, + DroidWorkingState, + McpOAuthTokenEndpointAuthMethod, McpServerType, MissionState, ModelProvider, ReasoningEffort, + SandboxMode, + SessionPlatform, SettingsLevel, SkillLocation, ) @@ -32,17 +52,31 @@ McpStatusSummary, McpToolInfo, ) +from droid_sdk.schemas.messages import ( + DocumentSource, + FactoryDroidMessage, +) from droid_sdk.schemas.mission import ( # noqa: TC001 MissionFeature, ProgressLogEntry, ) +from droid_sdk.schemas.session import ( + LastCallTokenUsage, + SessionTag, + TokenUsage, +) from droid_sdk.schemas.shared import ( JsonRpcRequest, JsonRpcResponseFailure, JsonRpcResponseSuccess, ) -__all__ = [ +_MCP_OAUTH_CLIENT_METADATA_DOT_SEGMENT_RE = re.compile( + r"(?:^|/)(?:\.\.|\.(?:%2e)?|%2e(?:\.|%2e)?)(?:/|$|[?#])", + re.IGNORECASE, +) + +__all__ = [ # noqa: RUF022 # Request schemas "AddMcpServerRequest", # Supporting types @@ -148,8 +182,12 @@ "LoadSessionRequestParams", "LoadSessionResponse", "LoadSessionResult", + "McpOAuthOptions", "MissionSnapshot", "OutputFormat", + "PendingAskUserRequest", + "PendingPermissionRequest", + "QueuedUserMessage", "RemoveMcpServerRequest", "RemoveMcpServerRequestParams", "RemoveMcpServerResponse", @@ -161,8 +199,27 @@ "RewindEvictedFile", "RewindFileCreation", "RewindFileSnapshot", + "SandboxStatus", "SessionSettings", + "SessionData", "SessionSource", + "SessionPlatform", + "SlackSessionSource", + "WebSessionSource", + "ApiSessionSource", + "SessionsApiSessionSource", + "LinearSessionSource", + "JiraSessionSource", + "MicrosoftTeamsSessionSource", + "ReadinessRemediationSessionSource", + "ReadinessEvaluationSessionSource", + "AutomationSessionSource", + "WikiGenerationSessionSource", + "WikiCISetupSessionSource", + "TuiSessionSource", + "DesktopSessionSource", + "AcpSessionSource", + "UnknownSessionSource", "SessionTag", "SkillInfo", "SkillResource", @@ -176,6 +233,14 @@ "SubmitMcpAuthCodeRequestParams", "SubmitMcpAuthCodeResponse", "SubmitMcpAuthCodeResult", + "SubmitMcpAuthErrorRequest", + "SubmitMcpAuthErrorRequestParams", + "SubmitMcpAuthErrorResponse", + "SubmitMcpAuthErrorResult", + "SetSkillDisabledRequest", + "SetSkillDisabledRequestParams", + "SetSkillDisabledResponse", + "SetSkillDisabledResult", "ToggleMcpServerRequest", "ToggleMcpServerRequestParams", "ToggleMcpServerResponse", @@ -215,30 +280,6 @@ class Base64ImageSource(BaseModel): """MIME type of the image.""" -class DocumentSource(BaseModel): - """Document source for user messages (PDF or plain text). - - Simplified schema — captures all document source fields. - """ - - model_config = ConfigDict(populate_by_name=True, extra="forbid") - - type: str - """Document source type ('base64' for PDF, 'text' for plain text).""" - - media_type: str = Field(alias="mediaType") - """MIME type (e.g., 'application/pdf', 'text/plain').""" - - data: str - """Document data (base64-encoded for PDF, raw text for plain text).""" - - name: str | None = None - """Optional file name.""" - - mime: str | None = None - """Optional additional MIME type info.""" - - class OutputFormat(BaseModel): """Structured-output contract for a user message or session. @@ -255,18 +296,6 @@ class OutputFormat(BaseModel): """JSON Schema describing the required output shape.""" -class SessionTag(BaseModel): - """Session tag metadata.""" - - model_config = ConfigDict(populate_by_name=True, extra="forbid") - - name: str - """Tag name.""" - - metadata: dict[str, str] | None = None - """Optional key-value metadata.""" - - class RewindFileSnapshot(BaseModel): """A file snapshot that can be restored during a rewind.""" @@ -303,17 +332,149 @@ class RewindEvictedFile(BaseModel): """Why the file cannot be restored.""" -class SessionSource(BaseModel): - """Session source information. - - Simplified schema that accepts any session source platform. - Uses ``extra='allow'`` to accept platform-specific fields. - """ +class _SessionSourceBase(BaseModel): + """Base for authority-recognized session source variants.""" model_config = ConfigDict(populate_by_name=True, extra="allow") - platform: str - """Source platform identifier (e.g. 'slack', 'web', 'api', 'linear').""" + +class SlackSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.Slack] + delegation_session_id: str = Field(alias="delegationSessionId") + team_id: str | None = Field(default=None, alias="teamId") + channel: str | None = None + thread_ts: str | None = Field(default=None, alias="threadTs") + user_id: str | None = Field(default=None, alias="userId") + automation_id: str | None = Field(default=None, alias="automationId") + + +class WebSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.Web] + delegation_session_id: str = Field(alias="delegationSessionId") + + +class ApiSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.Api] + delegation_session_id: str = Field(alias="delegationSessionId") + + +class SessionsApiSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.SessionsApi] + delegation_session_id: str = Field(alias="delegationSessionId") + + +class LinearSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.Linear] + delegation_session_id: str = Field(alias="delegationSessionId") + agent_session_id: str = Field(alias="agentSessionId") + issue_id: str | None = Field(default=None, alias="issueId") + issue_url: str | None = Field(default=None, alias="issueUrl") + issue_identifier: str | None = Field(default=None, alias="issueIdentifier") + organization_id: str | None = Field(default=None, alias="organizationId") + user_id: str | None = Field(default=None, alias="userId") + + +class JiraSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.Jira] + delegation_session_id: str = Field(alias="delegationSessionId") + cloud_id: str = Field(alias="cloudId") + issue_id: str = Field(alias="issueId") + issue_key: str | None = Field(default=None, alias="issueKey") + site_id: str | None = Field(default=None, alias="siteId") + project_id: str | None = Field(default=None, alias="projectId") + comment_id: str | None = Field(default=None, alias="commentId") + user_id: str | None = Field(default=None, alias="userId") + task_id: str | None = Field(default=None, alias="taskId") + + +class MicrosoftTeamsSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.MicrosoftTeams] + delegation_session_id: str = Field(alias="delegationSessionId") + tenant_id: str = Field(alias="tenantId") + conversation_id: str = Field(alias="conversationId") + service_url: str = Field(alias="serviceUrl") + conversation_type: Literal["personal", "groupChat", "channel"] | None = Field( + default=None, alias="conversationType" + ) + root_message_id: str | None = Field(default=None, alias="rootMessageId") + team_id: str | None = Field(default=None, alias="teamId") + channel_id: str | None = Field(default=None, alias="channelId") + user_id: str | None = Field(default=None, alias="userId") + aad_object_id: str | None = Field(default=None, alias="aadObjectId") + + +class ReadinessRemediationSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.ReadinessRemediation] + report_id: str = Field(alias="reportId") + repo_url: str = Field(alias="repoUrl") + criterion_id: str = Field(alias="criterionId") + + +class ReadinessEvaluationSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.ReadinessEvaluation] + repo_url: str = Field(alias="repoUrl") + + +class AutomationSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.Automation] + automation_id: str = Field(alias="automationId") + computer_id: str = Field(alias="computerId") + + +class WikiGenerationSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.WikiGeneration] + repo_url: str = Field(alias="repoUrl") + + +class WikiCISetupSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.WikiCISetup] + repo_url: str = Field(alias="repoUrl") + + +class TuiSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.Tui] + + +class DesktopSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.Desktop] + + +class AcpSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.Acp] + + +class UnknownSessionSource(_SessionSourceBase): + platform: Literal[SessionPlatform.Unknown] + + +SessionSourceUnion = Annotated[ + SlackSessionSource + | WebSessionSource + | ApiSessionSource + | SessionsApiSessionSource + | LinearSessionSource + | JiraSessionSource + | MicrosoftTeamsSessionSource + | ReadinessRemediationSessionSource + | ReadinessEvaluationSessionSource + | AutomationSessionSource + | WikiGenerationSessionSource + | WikiCISetupSessionSource + | TuiSessionSource + | DesktopSessionSource + | AcpSessionSource + | UnknownSessionSource, + Field(discriminator="platform"), +] + + +class SessionSource(RootModel[SessionSourceUnion]): + """Discriminated authority session-source union.""" + + @property + def platform(self) -> SessionPlatform: + """Return the selected source platform.""" + return self.root.platform class StdioMcpConfig(BaseModel): @@ -333,6 +494,14 @@ class StdioMcpConfig(BaseModel): env: dict[str, str] = Field(default_factory=dict) """Environment variables for the server process.""" + @field_validator("name", "command") + @classmethod + def validate_non_blank(cls, value: str) -> str: + value = value.strip() + if not value: + raise ValueError("MCP server name and command cannot be blank") + return value + class HttpHeader(BaseModel): """HTTP header for MCP server configuration.""" @@ -345,6 +514,127 @@ class HttpHeader(BaseModel): value: str """Header value.""" + @field_validator("name") + @classmethod + def validate_name(cls, value: str) -> str: + if not value or any(character.isspace() for character in value): + raise ValueError("MCP header name cannot be blank or contain whitespace") + return value + + @field_validator("value") + @classmethod + def validate_value(cls, value: str) -> str: + if "\r" in value or "\n" in value: + raise ValueError("MCP header value cannot contain line breaks") + return value + + +class McpOAuthOptions(BaseModel): + """OAuth options for HTTP and SSE MCP transports.""" + + model_config = ConfigDict(populate_by_name=True, extra="forbid") + + scopes: list[str] | None = None + resource: str | Literal[False] | None = None + authorization_server_issuer: str | None = Field( + default=None, alias="authorizationServerIssuer" + ) + client_metadata_url: str | None = Field(default=None, alias="clientMetadataUrl") + client_id: str | None = Field(default=None, alias="clientId") + client_secret: str | None = Field(default=None, alias="clientSecret") + callback_port: int | None = Field( + default=None, alias="callbackPort", ge=1, le=65535 + ) + token_endpoint_auth_method: McpOAuthTokenEndpointAuthMethod | None = Field( + default=None, alias="tokenEndpointAuthMethod" + ) + + @field_validator("scopes") + @classmethod + def validate_scopes(cls, value: list[str] | None) -> list[str] | None: + if value is None: + return None + scopes = [scope.strip() for scope in value] + if any(not scope for scope in scopes): + raise ValueError("OAuth scopes cannot be blank") + return scopes + + @field_validator("client_id") + @classmethod + def validate_client_id(cls, value: str | None) -> str | None: + if value is None: + return None + value = value.strip() + if not value: + raise ValueError("clientId cannot be blank") + return value + + @field_validator("client_secret") + @classmethod + def validate_client_secret(cls, value: str | None) -> str | None: + if value is not None and not value.strip(): + raise ValueError("clientSecret cannot be blank") + return value + + @field_validator("resource", "authorization_server_issuer") + @classmethod + def validate_oauth_url_or_false( + cls, value: str | Literal[False] | None + ) -> str | Literal[False] | None: + if value is None or value is False: + return value + parsed = urlsplit(value) + if not parsed.scheme or not parsed.netloc: + raise ValueError("Expected an absolute URL") + return value + + @field_validator("client_metadata_url") + @classmethod + def validate_client_metadata_url(cls, value: str | None) -> str | None: + if value is None: + return None + if _MCP_OAUTH_CLIENT_METADATA_DOT_SEGMENT_RE.search(value): + raise ValueError("clientMetadataUrl cannot contain dot segments") + parsed = urlsplit(value) + if ( + parsed.scheme != "https" + or not parsed.netloc + or parsed.path == "/" + or not parsed.path + or parsed.username + or parsed.password + or parsed.query + or parsed.fragment + ): + raise ValueError( + "clientMetadataUrl must be an HTTPS URL with a non-root " + "pathname, no credentials, query, fragment, or dot segments" + ) + return value + + @model_validator(mode="after") + def validate_oauth_configuration(self) -> McpOAuthOptions: + has_credentials = self.client_id is not None or self.client_secret is not None + if self.client_metadata_url is not None and has_credentials: + raise ValueError( + "clientMetadataUrl cannot be combined with configured OAuth " + "client credentials" + ) + if ( + self.client_metadata_url is not None + and self.token_endpoint_auth_method + not in {None, McpOAuthTokenEndpointAuthMethod.None_} + ): + raise ValueError( + "clientMetadataUrl requires public OAuth token endpoint authentication" + ) + if has_credentials and self.authorization_server_issuer is None: + raise ValueError( + "authorizationServerIssuer is required with configured OAuth " + "client credentials" + ) + return self + class HttpMcpConfig(BaseModel): """HTTP MCP server configuration for initialization.""" @@ -360,9 +650,29 @@ class HttpMcpConfig(BaseModel): url: str """URL endpoint for the MCP server.""" - headers: list[HttpHeader] = Field(default_factory=list) + headers: list[HttpHeader] = Field(default_factory=lambda: list[HttpHeader]()) """HTTP headers for authentication.""" + oauth: McpOAuthOptions | Literal[False] | None = None + + @field_validator("name") + @classmethod + def validate_name(cls, value: str) -> str: + value = value.strip() + if not value: + raise ValueError("MCP server name cannot be blank") + return value + + @field_validator("url") + @classmethod + def validate_url(cls, value: str) -> str: + parsed = urlsplit(value) + if parsed.scheme not in {"http", "https"} or not parsed.netloc: + raise ValueError("MCP URL must be an absolute HTTP(S) URL") + if parsed.username or parsed.password: + raise ValueError("MCP URL cannot contain credentials") + return value + class SseMcpConfig(BaseModel): """SSE MCP server configuration for initialization.""" @@ -378,9 +688,30 @@ class SseMcpConfig(BaseModel): url: str """URL endpoint for the MCP server.""" - headers: list[HttpHeader] = Field(default_factory=list) + headers: list[HttpHeader] = Field(default_factory=lambda: list[HttpHeader]()) """HTTP headers for authentication.""" + oauth: McpOAuthOptions | Literal[False] | None = None + + @field_validator("name") + @classmethod + def validate_name(cls, value: str) -> str: + return HttpMcpConfig.validate_name(value) + + @field_validator("url") + @classmethod + def validate_url(cls, value: str) -> str: + return HttpMcpConfig.validate_url(value) + + +class SandboxStatus(BaseModel): + """Session sandbox status.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + enabled: bool + mode: SandboxMode | None = None + class SessionSettings(BaseModel): """Session settings returned in init/load results.""" @@ -412,6 +743,18 @@ class SessionSettings(BaseModel): ) """Optional spec mode reasoning effort override.""" + tags: list[SessionTag] | None = None + sandbox: SandboxStatus | None = None + compaction_threshold_check_enabled: bool | None = Field( + default=None, alias="compactionThresholdCheckEnabled" + ) + additional_tool_ids: list[str] | None = Field( + default=None, alias="additionalToolIds" + ) + enabled_tool_ids: list[str] | None = Field(default=None, alias="enabledToolIds") + disabled_tool_ids: list[str] | None = Field(default=None, alias="disabledToolIds") + restrict_tool_ids: list[str] | None = Field(default=None, alias="restrictToolIds") + class GitRepoInfo(BaseModel): """Git repository information.""" @@ -485,27 +828,6 @@ class AvailableModelConfig(BaseModel): """Whether this model uses US-based inference.""" -class TokenUsage(BaseModel): - """Token usage information for a session.""" - - model_config = ConfigDict(populate_by_name=True, extra="allow") - - input_tokens: int = Field(alias="inputTokens") - """Number of input tokens consumed.""" - - output_tokens: int = Field(alias="outputTokens") - """Number of output tokens generated.""" - - cache_creation_tokens: int = Field(alias="cacheCreationTokens") - """Number of tokens used for cache creation.""" - - cache_read_tokens: int = Field(alias="cacheReadTokens") - """Number of tokens read from cache.""" - - thinking_tokens: int = Field(alias="thinkingTokens") - """Number of tokens used for thinking/reasoning.""" - - class WorkerStateInfo(BaseModel): """Worker state information for mission snapshots.""" @@ -568,6 +890,8 @@ class SkillInfo(BaseModel): resources: list[SkillResource] | None = None """Other files in the skill folder.""" + disabled_by: dict[str, Any] | None = Field(default=None, alias="disabledBy") + # ============================================================ # Request params schemas @@ -642,6 +966,24 @@ class InitializeSessionRequestParams(BaseModel): disabled_tool_ids: list[str] | None = Field(default=None, alias="disabledToolIds") """Tool IDs to disable (subtractive; applied on top of the default set).""" + additional_tool_ids: list[str] | None = Field( + default=None, alias="additionalToolIds" + ) + """Additional tool IDs to add to the catalog.""" + + restrict_tool_ids: list[str] | None = Field(default=None, alias="restrictToolIds") + """Restrictive tool allowlist.""" + + compaction_threshold_check_enabled: bool | None = Field( + default=None, alias="compactionThresholdCheckEnabled" + ) + auto_reject_permission_requests: bool | None = Field( + default=None, alias="autoRejectPermissionRequests" + ) + disable_builtin_skills: bool | None = Field( + default=None, alias="disableBuiltinSkills" + ) + session_location: str | None = Field(default=None, alias="sessionLocation") """Session metadata location.""" @@ -675,6 +1017,20 @@ class LoadSessionRequestParams(BaseModel): ) """OAuth callback URI for MCP auth relay.""" + additional_tool_ids: list[str] | None = Field( + default=None, alias="additionalToolIds" + ) + enabled_tool_ids: list[str] | None = Field(default=None, alias="enabledToolIds") + disabled_tool_ids: list[str] | None = Field(default=None, alias="disabledToolIds") + auto_reject_permission_requests: bool | None = Field( + default=None, alias="autoRejectPermissionRequests" + ) + disable_builtin_skills: bool | None = Field( + default=None, alias="disableBuiltinSkills" + ) + session_location: str | None = Field(default=None, alias="sessionLocation") + session_source: SessionSource | None = Field(default=None, alias="sessionSource") + class AddUserMessageRequestParams(BaseModel): """Parameters for droid.add_user_message request.""" @@ -750,6 +1106,18 @@ class UpdateSessionSettingsRequestParams(BaseModel): disabled_tool_ids: list[str] | None = Field(default=None, alias="disabledToolIds") """Tool IDs to disable (subtractive).""" + additional_tool_ids: list[str] | None = Field( + default=None, alias="additionalToolIds" + ) + restrict_tool_ids: list[str] | None = Field(default=None, alias="restrictToolIds") + tags: list[SessionTag] | None = None + compaction_token_limit: int | None = Field( + default=None, alias="compactionTokenLimit" + ) + compaction_threshold_check_enabled: bool | None = Field( + default=None, alias="compactionThresholdCheckEnabled" + ) + class ToggleMcpServerRequestParams(BaseModel): """Parameters for droid.toggle_mcp_server request.""" @@ -808,6 +1176,17 @@ class SubmitMcpAuthCodeRequestParams(BaseModel): """Authentication state token.""" +class SubmitMcpAuthErrorRequestParams(BaseModel): + """Parameters for reporting an MCP OAuth callback error.""" + + model_config = ConfigDict(populate_by_name=True, extra="forbid") + + server_name: str = Field(alias="serverName") + error: str + error_description: str | None = Field(default=None, alias="errorDescription") + state: str + + class AddMcpServerRequestParams(BaseModel): """Parameters for droid.add_mcp_server request. @@ -830,6 +1209,8 @@ class AddMcpServerRequestParams(BaseModel): headers: dict[str, str] | None = None """HTTP headers (for http servers).""" + oauth: McpOAuthOptions | Literal[False] | None = None + # Stdio config fields command: str | None = None """Command to spawn (for stdio servers).""" @@ -892,6 +1273,18 @@ class ListSkillsRequestParams(BaseModel): model_config = ConfigDict(populate_by_name=True, extra="forbid") +class SetSkillDisabledRequestParams(BaseModel): + """Parameters for enabling or disabling a skill.""" + + model_config = ConfigDict(populate_by_name=True, extra="forbid") + + skill_name: str = Field(alias="skillName") + disabled: bool + settings_level: Literal[SettingsLevel.User, SettingsLevel.Project] | None = Field( + default=None, alias="settingsLevel" + ) + + class SubmitBugReportRequestParams(BaseModel): """Parameters for droid.submit_bug_report request.""" @@ -915,6 +1308,21 @@ class ListToolsRequestParams(BaseModel): disabled_tool_ids: list[str] | None = Field(default=None, alias="disabledToolIds") """Optional hypothetical disabled tool IDs.""" + model_id: str | None = Field(default=None, alias="modelId") + autonomy_mode: AutonomyMode | None = Field(default=None, alias="autonomyMode") + interaction_mode: DroidInteractionMode | None = Field( + default=None, alias="interactionMode" + ) + autonomy_level: AutonomyLevel | None = Field(default=None, alias="autonomyLevel") + spec_mode_model_id: str | None = Field(default=None, alias="specModeModelId") + additional_tool_ids: list[str] | None = Field( + default=None, alias="additionalToolIds" + ) + restrict_tool_ids: list[str] | None = Field(default=None, alias="restrictToolIds") + skip_permissions_unsafe: bool | None = Field( + default=None, alias="skipPermissionsUnsafe" + ) + class ListCommandsRequestParams(BaseModel): """Parameters for droid.list_commands request (empty).""" @@ -1143,6 +1551,14 @@ class SubmitMcpAuthCodeRequest(JsonRpcRequest): """Typed request parameters.""" +class SubmitMcpAuthErrorRequest(JsonRpcRequest): + """Request to report an MCP OAuth callback error.""" + + model_config = ConfigDict(populate_by_name=True, extra="forbid") + method: Literal[DroidServerMethod.SUBMIT_MCP_AUTH_ERROR] + params: SubmitMcpAuthErrorRequestParams # type: ignore[assignment] + + class AddMcpServerRequest(JsonRpcRequest): """Request to add an MCP server.""" @@ -1227,6 +1643,14 @@ class ListSkillsRequest(JsonRpcRequest): """Typed request parameters.""" +class SetSkillDisabledRequest(JsonRpcRequest): + """Request to enable or disable a skill.""" + + model_config = ConfigDict(populate_by_name=True, extra="forbid") + method: Literal[DroidServerMethod.SET_SKILL_DISABLED] + params: SetSkillDisabledRequestParams # type: ignore[assignment] + + class SubmitBugReportRequest(JsonRpcRequest): """Request to submit a bug report.""" @@ -1328,6 +1752,33 @@ class ExecuteRewindRequest(JsonRpcRequest): # ============================================================ +class SessionData(BaseModel): + """Typed session snapshot returned by initialize and load.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + messages: list[FactoryDroidMessage] + title: str | None = None + + +class PendingPermissionRequest(RequestPermissionRequestParams): + """Pending permission request restored with its JSON-RPC request ID.""" + + request_id: str = Field(alias="requestId") + + +class PendingAskUserRequest(AskUserRequestParams): + """Pending ask-user request restored with its JSON-RPC request ID.""" + + request_id: str = Field(alias="requestId") + + +class QueuedUserMessage(AddUserMessageRequestParams): + """Queued user message restored with its queue request ID.""" + + request_id: str = Field(alias="requestId") + + class InitializeSessionResult(BaseModel): """Result for droid.initialize_session response.""" @@ -1336,8 +1787,8 @@ class InitializeSessionResult(BaseModel): session_id: str = Field(alias="sessionId") """Created session ID.""" - session: dict[str, Any] - """Session data (messages, etc.).""" + session: SessionData + """Typed session snapshot.""" mcp_servers: list[StdioMcpConfig | HttpMcpConfig | SseMcpConfig] | None = Field( default=None, alias="mcpServers" @@ -1392,20 +1843,20 @@ class LoadSessionResult(BaseModel): model_config = ConfigDict(populate_by_name=True, extra="allow") - session: dict[str, Any] - """Session data (messages, etc.).""" + session: SessionData + """Typed session snapshot.""" mcp_servers: list[StdioMcpConfig | HttpMcpConfig | SseMcpConfig] | None = Field( default=None, alias="mcpServers" ) """MCP server configurations.""" - pending_permissions: list[dict[str, Any]] | None = Field( + pending_permissions: list[PendingPermissionRequest] | None = Field( default=None, alias="pendingPermissions" ) """Pending permission requests.""" - pending_ask_user_requests: list[dict[str, Any]] | None = Field( + pending_ask_user_requests: list[PendingAskUserRequest] | None = Field( default=None, alias="pendingAskUserRequests" ) """Pending ask-user requests.""" @@ -1418,7 +1869,7 @@ class LoadSessionResult(BaseModel): ) """Whether the agent loop is currently running.""" - queued_messages: list[dict[str, Any]] | None = Field( + queued_messages: list[QueuedUserMessage] | None = Field( default=None, alias="queuedMessages" ) """Queued user messages.""" @@ -1451,6 +1902,14 @@ class LoadSessionResult(BaseModel): ) """Session type for mission decomposition.""" + working_state: DroidWorkingState | None = Field(default=None, alias="workingState") + inclusive_token_usage: TokenUsage | None = Field( + default=None, alias="inclusiveTokenUsage" + ) + last_call_token_usage: LastCallTokenUsage | None = Field( + default=None, alias="lastCallTokenUsage" + ) + class AddUserMessageResult(BaseModel): """Result for droid.add_user_message response (empty).""" @@ -1521,6 +1980,14 @@ class SubmitMcpAuthCodeResult(BaseModel): """Whether the operation succeeded.""" +class SubmitMcpAuthErrorResult(BaseModel): + """Result for droid.submit_mcp_auth_error response.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + success: bool + + class AddMcpServerResult(BaseModel): """Result for droid.add_mcp_server response.""" @@ -1586,6 +2053,16 @@ class ListSkillsResult(BaseModel): skills: list[SkillInfo] """Available skills.""" + project_available: bool | None = Field(default=None, alias="projectAvailable") + + +class SetSkillDisabledResult(BaseModel): + """Result for droid.set_skill_disabled response.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + success: bool + class SubmitBugReportResult(BaseModel): """Result for droid.submit_bug_report response.""" @@ -1724,8 +2201,8 @@ class GetContextStatsResult(BaseModel): limit: int """Total context window size.""" - accuracy: str - """Accuracy of the estimate (server-driven string enum).""" + accuracy: ContextStatsAccuracy + """Accuracy of the context measurement.""" updated_at: str = Field(alias="updatedAt") """ISO 8601 timestamp of the last update.""" @@ -1952,6 +2429,13 @@ class _SubmitMcpAuthCodeResponseSuccess(JsonRpcResponseSuccess): result: SubmitMcpAuthCodeResult # type: ignore[assignment] +class _SubmitMcpAuthErrorResponseSuccess(JsonRpcResponseSuccess): + """Success response for submit_mcp_auth_error.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + result: SubmitMcpAuthErrorResult # type: ignore[assignment] + + class _AddMcpServerResponseSuccess(JsonRpcResponseSuccess): """Success response for add_mcp_server.""" @@ -2001,6 +2485,13 @@ class _ListSkillsResponseSuccess(JsonRpcResponseSuccess): result: ListSkillsResult # type: ignore[assignment] +class _SetSkillDisabledResponseSuccess(JsonRpcResponseSuccess): + """Success response for set_skill_disabled.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + result: SetSkillDisabledResult # type: ignore[assignment] + + class _SubmitBugReportResponseSuccess(JsonRpcResponseSuccess): """Success response for submit_bug_report.""" @@ -2075,6 +2566,7 @@ class _ExecuteRewindResponseSuccess(JsonRpcResponseSuccess): CancelMcpAuthResponse = _CancelMcpAuthResponseSuccess | JsonRpcResponseFailure ClearMcpAuthResponse = _ClearMcpAuthResponseSuccess | JsonRpcResponseFailure SubmitMcpAuthCodeResponse = _SubmitMcpAuthCodeResponseSuccess | JsonRpcResponseFailure +SubmitMcpAuthErrorResponse = _SubmitMcpAuthErrorResponseSuccess | JsonRpcResponseFailure AddMcpServerResponse = _AddMcpServerResponseSuccess | JsonRpcResponseFailure RemoveMcpServerResponse = _RemoveMcpServerResponseSuccess | JsonRpcResponseFailure ListMcpRegistryResponse = _ListMcpRegistryResponseSuccess | JsonRpcResponseFailure @@ -2082,6 +2574,7 @@ class _ExecuteRewindResponseSuccess(JsonRpcResponseSuccess): ListMcpServersResponse = _ListMcpServersResponseSuccess | JsonRpcResponseFailure ToggleMcpToolResponse = _ToggleMcpToolResponseSuccess | JsonRpcResponseFailure ListSkillsResponse = _ListSkillsResponseSuccess | JsonRpcResponseFailure +SetSkillDisabledResponse = _SetSkillDisabledResponseSuccess | JsonRpcResponseFailure SubmitBugReportResponse = _SubmitBugReportResponseSuccess | JsonRpcResponseFailure ListToolsResponse = _ListToolsResponseSuccess | JsonRpcResponseFailure ListCommandsResponse = _ListCommandsResponseSuccess | JsonRpcResponseFailure @@ -2098,7 +2591,7 @@ class _ExecuteRewindResponseSuccess(JsonRpcResponseSuccess): # ============================================================ -# ClientRequest discriminated union over all 29 request types +# ClientRequest discriminated union over all request types # ============================================================ ClientRequestUnion = Annotated[ @@ -2113,6 +2606,7 @@ class _ExecuteRewindResponseSuccess(JsonRpcResponseSuccess): | CancelMcpAuthRequest | ClearMcpAuthRequest | SubmitMcpAuthCodeRequest + | SubmitMcpAuthErrorRequest | AddMcpServerRequest | RemoveMcpServerRequest | ListMcpRegistryRequest @@ -2120,6 +2614,7 @@ class _ExecuteRewindResponseSuccess(JsonRpcResponseSuccess): | ListMcpServersRequest | ToggleMcpToolRequest | ListSkillsRequest + | SetSkillDisabledRequest | SubmitBugReportRequest | ListToolsRequest | ListCommandsRequest @@ -2136,7 +2631,7 @@ class _ExecuteRewindResponseSuccess(JsonRpcResponseSuccess): class ClientRequest(RootModel[ClientRequestUnion]): - """Discriminated union over all 29 client→server request types. + """Discriminated union over all client→server request types. Dispatches on the ``method`` field to the appropriate request model. """ diff --git a/src/droid_sdk/schemas/enums.py b/src/droid_sdk/schemas/enums.py index f3c9488..ec6f000 100644 --- a/src/droid_sdk/schemas/enums.py +++ b/src/droid_sdk/schemas/enums.py @@ -11,11 +11,13 @@ from enum import Enum -__all__ = [ +__all__ = [ # noqa: RUF022 + "AgentTurnCompletionReason", "AutonomyLevel", # AutonomyMode intentionally excluded — deprecated in favor of # DroidInteractionMode + AutonomyLevel. Kept for protocol compat only. "ClientType", + "ContextStatsAccuracy", "DecompSessionType", "DismissalType", "DroidClientMethod", @@ -30,7 +32,9 @@ "IssueSeverity", "JsonRpcErrorCode", "JsonRpcMessageType", + "LlmRetryReason", "McpAuthOutcome", + "McpOAuthTokenEndpointAuthMethod", "McpServerStatus", "McpServerType", "McpStatus", @@ -39,11 +43,17 @@ "Platform", "ProgressLogEntryType", "ReasoningEffort", + "SandboxMode", + "SandboxOperationType", + "SandboxViolationReason", + "SandboxViolationType", + "SessionPlatform", "SessionNotificationType", "SettingsLevel", "SkillLocation", "ToolConfirmationOutcome", "ToolConfirmationType", + "ToolExecutionLifecyclePhase", ] @@ -67,7 +77,9 @@ class DroidServerMethod(str, Enum): LIST_MCP_SERVERS = "droid.list_mcp_servers" TOGGLE_MCP_TOOL = "droid.toggle_mcp_tool" SUBMIT_MCP_AUTH_CODE = "droid.submit_mcp_auth_code" + SUBMIT_MCP_AUTH_ERROR = "droid.submit_mcp_auth_error" LIST_SKILLS = "droid.list_skills" + SET_SKILL_DISABLED = "droid.set_skill_disabled" SUBMIT_BUG_REPORT = "droid.submit_bug_report" LIST_TOOLS = "droid.list_tools" LIST_COMMANDS = "droid.list_commands" @@ -97,13 +109,21 @@ class SessionNotificationType(str, Enum): CREATE_MESSAGE = "create_message" ERROR = "error" DROID_WORKING_STATE_CHANGED = "droid_working_state_changed" + SESSION_COMPACTED = "session_compacted" + LOOP_STATE_CHANGED = "loop_state_changed" PERMISSION_RESOLVED = "permission_resolved" SETTINGS_UPDATED = "settings_updated" SESSION_TITLE_UPDATED = "session_title_updated" + SESSION_WORKING_DIRECTORY_CHANGED = "session_working_directory_changed" + CHILD_SESSION_AVAILABLE = "child_session_available" MCP_STATUS_CHANGED = "mcp_status_changed" ASSISTANT_TEXT_DELTA = "assistant_text_delta" + ASSISTANT_TEXT_COMPLETE = "assistant_text_complete" + STRUCTURED_OUTPUT = "structured_output" THINKING_TEXT_DELTA = "thinking_text_delta" + THINKING_TEXT_COMPLETE = "thinking_text_complete" SESSION_TOKEN_USAGE_CHANGED = "session_token_usage_changed" + AGENT_TURN_COMPLETED = "agent_turn_completed" MISSION_STATE_CHANGED = "mission_state_changed" MISSION_FEATURES_CHANGED = "mission_features_changed" MISSION_PROGRESS_ENTRY = "mission_progress_entry" @@ -112,6 +132,13 @@ class SessionNotificationType(str, Enum): MISSION_WORKER_COMPLETED = "mission_worker_completed" MCP_AUTH_REQUIRED = "mcp_auth_required" MCP_AUTH_COMPLETED = "mcp_auth_completed" + HOOK_EXECUTION_STARTED = "hook_execution_started" + HOOK_EXECUTION_COMPLETED = "hook_execution_completed" + TOOL_CALL = "tool_call" + QUEUED_MESSAGES_DISCARDED = "queued_messages_discarded" + TOOL_EXECUTION_HEARTBEAT = "tool_execution_heartbeat" + LLM_RETRY = "llm_retry" + TOOL_EXECUTION_PHASE_CHANGED = "tool_execution_phase_changed" class ToolConfirmationOutcome(str, Enum): @@ -122,11 +149,18 @@ class ToolConfirmationOutcome(str, Enum): ProceedOnce = "proceed_once" ProceedAlways = "proceed_always" + ProceedAlwaysForExactPath = "proceed_always_file" ProceedAutoRun = "proceed_auto_run" ProceedAutoRunLow = "proceed_auto_run_low" ProceedAutoRunMedium = "proceed_auto_run_medium" ProceedAutoRunHigh = "proceed_auto_run_high" + ProceedNewSession = "proceed_new_session" + ProceedNewSessionLow = "proceed_new_session_low" + ProceedNewSessionMedium = "proceed_new_session_medium" + ProceedNewSessionHigh = "proceed_new_session_high" ProceedEdit = "proceed_edit" + ProceedAlwaysTools = "proceed_always_tools" + ProceedAlwaysServer = "proceed_always_server" Cancel = "cancel" @@ -142,12 +176,47 @@ class ToolConfirmationType(str, Enum): StartMissionRun = "start_mission_run" ApplyPatch = "apply_patch" McpTool = "mcp_tool" + SandboxViolation = "sandbox_violation" + DroidShieldViolation = "droid_shield_violation" + + +class SandboxViolationType(str, Enum): + """Kind of access blocked by the sandbox.""" + + FilesystemRead = "filesystem-read" + FilesystemWrite = "filesystem-write" + Network = "network" + Tool = "tool" + + +class SandboxViolationReason(str, Enum): + """Reason sandbox access was denied.""" + + DenyList = "deny-list" + NotAllowed = "not-allowed" + + +class SandboxOperationType(str, Enum): + """Operation attempted by a sandboxed tool.""" + + Read = "read" + Write = "write" + Network = "network" + Tool = "tool" + + +class SandboxMode(str, Enum): + """Sandbox execution mode.""" + + PerCommand = "per-command" + WholeProcess = "whole-process" class DroidWorkingState(str, Enum): """Droid working state (represents what the agent is currently doing).""" Idle = "idle" + Thinking = "thinking" StreamingAssistantMessage = "streaming_assistant_message" WaitingForToolConfirmation = "waiting_for_tool_confirmation" ExecutingTool = "executing_tool" @@ -181,6 +250,40 @@ class McpServerType(str, Enum): Stdio = "stdio" Http = "http" + Sse = "sse" + + +class AgentTurnCompletionReason(str, Enum): + """Canonical terminal reasons for an agent turn.""" + + Completed = "completed" + Cancelled = "cancelled" + PermissionRejected = "permission_rejected" + Error = "error" + ProcessExit = "process_exit" + SpecHandoff = "spec_handoff" + StructuredOutputMissing = "structured_output_missing" + StructuredOutputInvalid = "structured_output_invalid" + StructuredOutputSchemaInvalid = "structured_output_schema_invalid" + ModelUsageExhausted = "model_usage_exhausted" + ModelAuthenticationFailed = "model_authentication_failed" + ModelRequestRejected = "model_request_rejected" + ModelProviderUnreachable = "model_provider_unreachable" + ModelProviderUnavailable = "model_provider_unavailable" + PromptRejected = "prompt_rejected" + CompletionPersistenceFailed = "completion_persistence_failed" + NoApproverAvailable = "no_approver_available" + + +class ToolExecutionLifecyclePhase(str, Enum): + """Objective lifecycle phase for a tool call.""" + + StreamingInput = "streaming_input" + Queued = "queued" + Executing = "executing" + SettledAfterExecution = "settled_after_execution" + SettledWithoutExecution = "settled_without_execution" + SettledUnknown = "settled_unknown" class McpStatus(str, Enum): @@ -201,6 +304,53 @@ class McpAuthOutcome(str, Enum): Failed = "failed" +class McpOAuthTokenEndpointAuthMethod(str, Enum): + """OAuth client authentication method used at the token endpoint.""" + + None_ = "none" + ClientSecretBasic = "client_secret_basic" + ClientSecretPost = "client_secret_post" + + +class LlmRetryReason(str, Enum): + """Coarse, content-free reason for retrying an LLM request.""" + + Overloaded = "overloaded" + RateLimited = "rate_limited" + Timeout = "timeout" + Network = "network" + EmptyResponse = "empty_response" + Unknown = "unknown" + + +class ContextStatsAccuracy(str, Enum): + """Accuracy of the current context-window measurement.""" + + Exact = "exact" + Estimated = "estimated" + + +class SessionPlatform(str, Enum): + """Authority-recognized origin platform for a session.""" + + Slack = "slack" + Web = "web" + Api = "api" + SessionsApi = "sessions_api" + Jira = "jira" + Linear = "linear" + MicrosoftTeams = "microsoft-teams" + ReadinessRemediation = "readiness-remediation" + ReadinessEvaluation = "readiness-evaluation" + Automation = "automation" + WikiGeneration = "wiki-generation" + WikiCISetup = "wiki-ci-setup" + Tui = "tui" + Desktop = "desktop" + Acp = "acp" + Unknown = "unknown" + + class DecompSessionType(str, Enum): """Session type for mission decomposition (orchestrator manages workers).""" @@ -428,3 +578,4 @@ class SkillLocation(str, Enum): Project = "project" Personal = "personal" Builtin = "builtin" + Automation = "automation" diff --git a/src/droid_sdk/schemas/mcp.py b/src/droid_sdk/schemas/mcp.py index 99f58e6..b801a1c 100644 --- a/src/droid_sdk/schemas/mcp.py +++ b/src/droid_sdk/schemas/mcp.py @@ -17,6 +17,7 @@ ) __all__ = [ + "McpConfigError", "McpHttpServerConfigFields", "McpRegistryServer", "McpServerStatusInfo", @@ -113,12 +114,26 @@ class McpServerStatusInfo(BaseModel): tool_count: int | None = Field(default=None, alias="toolCount") """Number of tools provided by this server.""" - server_type: McpServerType | None = Field(default=None, alias="serverType") + server_type: McpServerType = Field(alias="serverType") """Transport type (stdio or http).""" has_auth_tokens: bool | None = Field(default=None, alias="hasAuthTokens") """Whether authentication tokens are stored for this server.""" + requires_auth: bool | None = Field(default=None, alias="requiresAuth") + pending_auth_url: str | None = Field(default=None, alias="pendingAuthUrl") + pending_auth_message: str | None = Field(default=None, alias="pendingAuthMessage") + pending_auth_state: str | None = Field(default=None, alias="pendingAuthState") + + +class McpConfigError(BaseModel): + """MCP configuration parse error.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + path: str + message: str + class McpStatusSummary(BaseModel): """MCP status summary. @@ -143,6 +158,8 @@ class McpStatusSummary(BaseModel): disabled: int | None = None """Number of disabled servers.""" + config_error: McpConfigError | None = Field(default=None, alias="configError") + # ============================================================ # MCP registry server diff --git a/src/droid_sdk/schemas/messages.py b/src/droid_sdk/schemas/messages.py index 1cee5fb..aaf0845 100644 --- a/src/droid_sdk/schemas/messages.py +++ b/src/droid_sdk/schemas/messages.py @@ -12,24 +12,28 @@ from __future__ import annotations from enum import Enum -from typing import Annotated, Literal +from typing import Annotated, Any, Literal from pydantic import BaseModel, ConfigDict, Field __all__ = [ "Base64ImageSource", + "Base64PDFSource", "ContentBlock", "DocumentBlock", + "DocumentSource", "DocumentSourceType", "FactoryDroidMessage", "ImageBlock", "MessageContentBlockType", "MessageRole", "MessageVisibility", + "PlainTextSource", "RedactedThinkingBlock", "TextBlock", "ThinkingBlock", "ToolResultBlock", + "ToolResultContent", "ToolUseBlock", ] @@ -126,6 +130,9 @@ class ImageBlock(BaseModel): id: str | None = None """Optional content block ID.""" + generated: bool | None = None + """Whether this image was generated by the model.""" + class ThinkingBlock(BaseModel): """Thinking content block.""" @@ -147,6 +154,9 @@ class ThinkingBlock(BaseModel): signature_provider: str | None = Field(default=None, alias="signatureProvider") """Optional model provider or 'unknown'.""" + duration_ms: float | None = Field(default=None, alias="durationMs", ge=0) + """Optional thinking duration in milliseconds.""" + class RedactedThinkingBlock(BaseModel): """Redacted thinking content block.""" @@ -184,25 +194,33 @@ class ToolUseBlock(BaseModel): """Optional Gemini thought signature.""" -class ToolResultBlock(BaseModel): - """Tool result content block.""" +class Base64PDFSource(BaseModel): + """Base64-encoded PDF source.""" model_config = ConfigDict(populate_by_name=True, extra="allow") - type: Literal[MessageContentBlockType.ToolResult] - """Content block type, always 'tool_result'.""" + type: Literal[DocumentSourceType.Base64] + media_type: Literal["application/pdf"] = Field(alias="mediaType") + data: str + parsed_data: str | None = Field(default=None, alias="parsedData") + name: str | None = None + path: str | None = None - tool_use_id: str = Field(alias="toolUseId") - """Tool use ID this result corresponds to.""" - content: str | list[object] | None = None - """Tool result content (string or array of content blocks).""" +class PlainTextSource(BaseModel): + """Plain-text document source.""" - is_error: bool | None = Field(default=None, alias="isError") - """Whether this result represents an error.""" + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[DocumentSourceType.Text] + media_type: Literal["text/plain"] = Field(alias="mediaType") + data: str + name: str | None = None + mime: str | None = None - id: str | None = None - """Optional content block ID.""" + +DocumentSource = Base64PDFSource | PlainTextSource +"""Canonical PDF or plain-text document source.""" class DocumentBlock(BaseModel): @@ -213,13 +231,29 @@ class DocumentBlock(BaseModel): type: Literal[MessageContentBlockType.Document] """Content block type, always 'document'.""" - source: dict[str, object] - """Document source (Base64PDF or PlainText — uses dict for flexibility).""" + source: DocumentSource + """PDF or plain-text document source.""" id: str | None = None """Optional content block ID.""" +ToolResultContent = TextBlock | ImageBlock | DocumentBlock +"""Content block shapes supported inside a tool result array.""" + + +class ToolResultBlock(BaseModel): + """Tool result content block.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + type: Literal[MessageContentBlockType.ToolResult] + tool_use_id: str = Field(alias="toolUseId") + content: str | list[ToolResultContent] | None = None + is_error: bool | None = Field(default=None, alias="isError") + id: str | None = None + + ContentBlock = Annotated[ TextBlock | ImageBlock @@ -307,3 +341,33 @@ class FactoryDroidMessage(BaseModel): is_error: bool | None = Field(default=None, alias="isError") """Whether this message represents an error.""" + + user_message_source: str | None = Field(default=None, alias="userMessageSource") + interaction_mode: str | None = Field(default=None, alias="interactionMode") + model_id: str | None = Field(default=None, alias="modelId") + router_id: str | None = Field(default=None, alias="routerId") + reasoning_effort: str | None = Field(default=None, alias="reasoningEffort") + hook_event_name: str | None = Field(default=None, alias="hookEventName") + hook_matcher: str | None = Field(default=None, alias="hookMatcher") + hook_commands: list[dict[str, Any]] | None = Field( + default=None, alias="hookCommands" + ) + hook_status: Literal["executing", "completed", "error"] | None = Field( + default=None, alias="hookStatus" + ) + hook_results: list[dict[str, Any]] | None = Field(default=None, alias="hookResults") + hook_tool_call_id: str | None = Field(default=None, alias="hookToolCallId") + hook_parent_id: str | None = Field(default=None, alias="hookParentId") + hook_order: int | None = Field(default=None, alias="hookOrder") + hook_prevented_action: bool | None = Field( + default=None, alias="hookPreventedAction" + ) + hidden_from_user_views: bool | None = Field( + default=None, alias="hiddenFromUserViews" + ) + hook_start_time: float | None = Field(default=None, alias="hookStartTime") + hook_end_time: float | None = Field(default=None, alias="hookEndTime") + is_parallel_execution: bool | None = Field( + default=None, alias="isParallelExecution" + ) + parallel_group_id: str | None = Field(default=None, alias="parallelGroupId") diff --git a/src/droid_sdk/schemas/session.py b/src/droid_sdk/schemas/session.py new file mode 100644 index 0000000..1a84720 --- /dev/null +++ b/src/droid_sdk/schemas/session.py @@ -0,0 +1,43 @@ +"""Session metadata and token usage schemas shared across protocol directions.""" + +from __future__ import annotations + +from pydantic import BaseModel, ConfigDict, Field + +__all__ = [ + "LastCallTokenUsage", + "SessionTag", + "TokenUsage", +] + + +class SessionTag(BaseModel): + """Session tag metadata.""" + + model_config = ConfigDict(populate_by_name=True, extra="forbid") + + name: str + metadata: dict[str, str] | None = None + + +class TokenUsage(BaseModel): + """Complete cumulative token usage information.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + input_tokens: int = Field(alias="inputTokens") + output_tokens: int = Field(alias="outputTokens") + cache_creation_tokens: int = Field(alias="cacheCreationTokens") + cache_read_tokens: int = Field(alias="cacheReadTokens") + thinking_tokens: int = Field(alias="thinkingTokens") + factory_credits: float | None = Field(default=None, alias="factoryCredits") + + +class LastCallTokenUsage(BaseModel): + """Provider usage fields used by the context and compaction meter.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + input_tokens: int = Field(alias="inputTokens") + cache_read_tokens: int = Field(alias="cacheReadTokens") + output_tokens: int | None = Field(default=None, alias="outputTokens") diff --git a/src/droid_sdk/stream.py b/src/droid_sdk/stream.py index 42fd04a..ee952b0 100644 --- a/src/droid_sdk/stream.py +++ b/src/droid_sdk/stream.py @@ -1,3 +1,5 @@ +# pyright: reportUnknownArgumentType=false, reportUnknownMemberType=false + """Typed stream message dataclasses and notification-to-stream-message converter. Provides simple ``@dataclass`` wrappers (NOT Pydantic models) that map diff --git a/src/droid_sdk/transport.py b/src/droid_sdk/transport.py index 5a648de..cbe3458 100644 --- a/src/droid_sdk/transport.py +++ b/src/droid_sdk/transport.py @@ -1,3 +1,5 @@ +# pyright: reportUnnecessaryComparison=false + """ProcessTransport implementation for the Factory Droid SDK. Spawns a ``droid exec`` subprocess with piped stdin/stdout/stderr and provides @@ -11,12 +13,12 @@ import json import logging import os +import re import signal from collections.abc import AsyncIterator # noqa: TC003 from typing import Any -from droid_sdk.errors import ConnectionError as DroidConnectionError -from droid_sdk.errors import ProcessExitError +from droid_sdk.errors import DroidConnectionError, DroidProcessError logger = logging.getLogger(__name__) @@ -27,6 +29,25 @@ # Must be large enough to handle multi-MB JSON-RPC messages. _STDOUT_BUFFER_LIMIT = 10 * 1024 * 1024 +# Stderr is drained continuously to prevent a full child pipe from blocking the +# protocol. Only a small, redacted prefix is retained for exit diagnostics. +_STDERR_CAPTURE_LIMIT = 16 * 1024 +_STDERR_REDACTION_LOOKAHEAD = 512 +_SENSITIVE_ENV_MARKERS = ( + "API_KEY", + "AUTH", + "CREDENTIAL", + "PASSWORD", + "SECRET", + "TOKEN", +) +_SENSITIVE_ASSIGNMENT = re.compile( + r"(?i)((?:api[_-]?key|authorization|credential|password|secret|token)" + r"\s*[:=]\s*)(?:\"[^\"]*\"|'[^']*'|[^\s,;]*)" +) +_BEARER_TOKEN = re.compile(r"(?i)\bbearer\s+\S+") +_KEY_LIKE_TOKEN = re.compile(r"(?i)\b(?:api|pk|sk)[_-][A-Za-z0-9_-]{8,}\b") + # Default arguments for droid exec subprocess _DEFAULT_EXEC_ARGS = [ "exec", @@ -81,6 +102,9 @@ def __init__( self._is_connected = False self._is_closing = False self._process_error: Exception | None = None + self._stderr_task: asyncio.Task[None] | None = None + self._stderr_capture = "" + self._stderr_redaction_values: tuple[str, ...] = () @property def is_connected(self) -> bool: @@ -109,12 +133,15 @@ async def connect(self) -> None: ) # Reset state for reconnection + await self._finish_stderr_task(cancel=True) self._process_error = None self._is_closing = False + self._stderr_capture = "" env: dict[str, str] | None = None if self._env is not None: env = {**os.environ, **self._env} + self._stderr_redaction_values = self._collect_redaction_values(env) try: self._process = await asyncio.create_subprocess_exec( @@ -138,6 +165,11 @@ async def connect(self) -> None: self._is_connected = True self._write_lock = asyncio.Lock() + if self._process.stderr is not None: + self._stderr_task = asyncio.create_task( + self._drain_stderr(self._process.stderr), + name="droid-sdk-process-stderr", + ) async def send(self, message: str) -> None: """Send a message to the subprocess stdin. @@ -150,7 +182,7 @@ async def send(self, message: str) -> None: Raises: ConnectionError: If the transport is not connected. - ProcessExitError: If the subprocess has exited. + DroidProcessError: If the subprocess has exited. """ if self._process_error is not None: raise self._process_error @@ -201,22 +233,22 @@ async def read_messages(self) -> AsyncIterator[dict[str, Any]]: Non-JSON lines (e.g., debug output) are silently skipped. Malformed JSON lines are logged and skipped. - When stdout reaches EOF (process exit), the iterator checks the - exit code. Normal exit (code 0) terminates the iterator naturally. - Abnormal exit raises ``ProcessExitError``. + When stdout reaches EOF (process exit), the iterator raises + ``DroidProcessError`` for both normal and abnormal process exits. Yields: Parsed JSON-RPC message dicts. Raises: - ProcessExitError: If the subprocess exited abnormally. + DroidProcessError: If the subprocess exited abnormally. """ - if self._process is None or self._process.stdout is None: + process = self._process + if process is None or process.stdout is None: return try: while True: - line_bytes = await self._process.stdout.readline() + line_bytes = await process.stdout.readline() if not line_bytes: # EOF — process closed stdout break @@ -233,8 +265,8 @@ async def read_messages(self) -> AsyncIterator[dict[str, Any]]: except json.JSONDecodeError as e: logger.warning("Malformed JSON on stdout: %s", e) else: - # Non-JSON output (e.g. debug logging) — skip - logger.debug("Non-JSON stdout output: %s", line[:200]) + # Raw child output can contain environment secrets. + logger.debug("Skipped non-JSON child stdout") except asyncio.CancelledError: raise @@ -242,67 +274,53 @@ async def read_messages(self) -> AsyncIterator[dict[str, Any]]: if self._is_closing: return - if self._process is not None and self._process.returncode is None: + if process.returncode is None: # Process hasn't exited yet, wait briefly with contextlib.suppress(asyncio.TimeoutError): - await asyncio.wait_for(self._process.wait(), timeout=2.0) - - if self._process is not None: - return_code = self._process.returncode - - if return_code is not None: - # Capture stderr - stderr_text = "" - if self._process.stderr is not None: - try: - stderr_data = await self._process.stderr.read() - stderr_text = stderr_data.decode( - "utf-8", errors="replace" - ).strip() - except Exception: - pass - - # Determine exit_code and signal - exit_code: int | None = None - sig: int | None = None - if return_code < 0: - sig = -return_code - else: - exit_code = return_code - - self._is_connected = False - - # Normal exit (code 0) — just terminate the iterator - if exit_code == 0: - # Build error for sticky pattern (send after exit) - error = ProcessExitError( - "Droid process exited normally", - exit_code=0, - ) - self._process_error = error - return - - # Abnormal exit — raise ProcessExitError - if sig is not None: - message = f"Droid process was killed (signal {sig})" - elif exit_code is not None: - message = ( - f"Droid process exited unexpectedly (exit code {exit_code})" - ) - else: - message = "Droid process exited unexpectedly" - - if stderr_text: - message += f": {stderr_text[:500]}" - - error = ProcessExitError( - message, - exit_code=exit_code, - signal=sig, + await asyncio.wait_for(process.wait(), timeout=2.0) + + return_code = process.returncode + + if return_code is not None: + await self._finish_stderr_task() + + # Determine exit_code and signal + exit_code: int | None = None + sig: int | None = None + if return_code < 0: + sig = -return_code + else: + exit_code = return_code + + self._is_connected = False + + # Even a normal exit is a broken transport while the protocol + # engine is active. Raise so pending and future requests fail + # immediately with the same sticky process error. + if exit_code == 0: + error = DroidProcessError( + self._with_stderr_diagnostic("Droid process exited normally"), + exit_code=0, ) self._process_error = error raise error + # Abnormal exit — raise DroidProcessError + if sig is not None: + message = f"Droid process was killed (signal {sig})" + elif exit_code is not None: + message = f"Droid process exited unexpectedly (exit code {exit_code})" + else: + message = "Droid process exited unexpectedly" + + error = DroidProcessError( + self._with_stderr_diagnostic(message), + exit_code=exit_code, + signal=sig, + ) + self._process_error = error + raise error + async def close(self) -> None: """Close the transport and terminate the subprocess. @@ -318,27 +336,127 @@ async def close(self) -> None: process = self._process self._process = None - if process is not None and process.returncode is None: - # Process is still running — terminate gracefully - with contextlib.suppress(ProcessLookupError, OSError): - process.send_signal(signal.SIGTERM) - - try: - await asyncio.wait_for(process.wait(), timeout=self._grace_period) - except asyncio.TimeoutError: - # Escalate to SIGKILL + cancelled: asyncio.CancelledError | None = None + try: + if process is not None and process.returncode is None: + # Process is still running — terminate gracefully with contextlib.suppress(ProcessLookupError, OSError): - process.kill() - with contextlib.suppress(asyncio.TimeoutError): - await asyncio.wait_for(process.wait(), timeout=2.0) + process.send_signal(signal.SIGTERM) - # Close stdin if still open - if process is not None and process.stdin is not None: - with contextlib.suppress(Exception): - process.stdin.close() + try: + await asyncio.wait_for( + process.wait(), + timeout=self._grace_period, + ) + except asyncio.TimeoutError: + # Escalate to SIGKILL + with contextlib.suppress(ProcessLookupError, OSError): + process.kill() + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(process.wait(), timeout=2.0) + except asyncio.CancelledError as exc: + cancelled = exc + with contextlib.suppress(ProcessLookupError, OSError): + process.kill() + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(process.wait(), timeout=2.0) + + # Close stdin if still open + if process is not None and process.stdin is not None: + with contextlib.suppress(Exception): + process.stdin.close() + finally: + try: + await self._finish_stderr_task( + cancel=process is not None and process.returncode is None + ) + except asyncio.CancelledError as exc: + cancelled = exc + # Reset closing flag to allow reconnection + self._is_closing = False + if cancelled is not None: + raise cancelled + + def _collect_redaction_values( + self, + child_env: dict[str, str] | None, + ) -> tuple[str, ...]: + values: set[str] = set(self._env.values()) if self._env is not None else set() + if child_env is not None: + values.update( + value + for key, value in child_env.items() + if any(marker in key.upper() for marker in _SENSITIVE_ENV_MARKERS) + ) + values.discard("") + return tuple(sorted(values, key=len, reverse=True)) - # Reset closing flag to allow reconnection - self._is_closing = False + async def _drain_stderr( + self, + stderr: asyncio.StreamReader, + ) -> None: + max_secret_length = max( + (len(value) for value in self._stderr_redaction_values), + default=0, + ) + if max_secret_length > _STDERR_CAPTURE_LIMIT: + capture_limit = 0 + else: + capture_limit = _STDERR_CAPTURE_LIMIT + max( + _STDERR_REDACTION_LOOKAHEAD, max_secret_length + ) + captured = "" + try: + while True: + chunk = await stderr.read(8192) + if not chunk: + break + if len(captured) < capture_limit: + captured += chunk.decode("utf-8", errors="replace")[ + : capture_limit - len(captured) + ] + except asyncio.CancelledError: + raise + except Exception: + logger.debug("Failed while draining child stderr", exc_info=True) + finally: + self._stderr_capture = self._redact_stderr(captured)[:_STDERR_CAPTURE_LIMIT] + + def _redact_stderr(self, text: str) -> str: + for value in self._stderr_redaction_values: + text = text.replace(value, "[REDACTED]") + text = _BEARER_TOKEN.sub("Bearer [REDACTED]", text) + text = _SENSITIVE_ASSIGNMENT.sub(r"\1[REDACTED]", text) + return _KEY_LIKE_TOKEN.sub("[REDACTED]", text) + + async def _finish_stderr_task(self, *, cancel: bool = False) -> None: + task = self._stderr_task + self._stderr_task = None + if task is None: + return + if cancel and not task.done(): + task.cancel() + try: + await asyncio.shield(task) + except asyncio.CancelledError: + if not task.done(): + task.add_done_callback(_consume_task_result) + raise + with contextlib.suppress(asyncio.CancelledError): + task.result() + except Exception: + pass + + def _with_stderr_diagnostic(self, message: str) -> str: + diagnostic = " ".join(self._stderr_capture.split()) + if not diagnostic: + return message + return f"{message}; stderr: {diagnostic}" + + +def _consume_task_result(task: asyncio.Task[None]) -> None: + with contextlib.suppress(BaseException): + task.result() __all__ = [ diff --git a/src/droid_sdk/types.py b/src/droid_sdk/types.py index 7fd1f26..4bb1c15 100644 --- a/src/droid_sdk/types.py +++ b/src/droid_sdk/types.py @@ -63,7 +63,7 @@ def read_messages(self) -> AsyncIterator[dict[str, Any]]: Parsed JSON-RPC message dicts. Raises: - ProcessExitError: If the underlying process exited abnormally. + DroidProcessError: If the underlying process exits. """ ... diff --git a/tests/mock_droid_subprocess.py b/tests/mock_droid_subprocess.py index bf7aaa1..9ab0362 100644 --- a/tests/mock_droid_subprocess.py +++ b/tests/mock_droid_subprocess.py @@ -123,6 +123,7 @@ def init_session_result(session_id: str = "test-session-1") -> dict: # type: ig "id": session_id, "createdAt": "2025-01-01T00:00:00Z", "settings": {}, + "messages": [], }, "settings": { "modelId": "test-model", @@ -138,6 +139,7 @@ def load_session_result(session_id: str = "test-session-1") -> dict: # type: ig "id": session_id, "createdAt": "2025-01-01T00:00:00Z", "settings": {}, + "messages": [], }, "settings": { "modelId": "test-model", diff --git a/tests/test_cli_schemas.py b/tests/test_cli_schemas.py index f11928d..7734146 100644 --- a/tests/test_cli_schemas.py +++ b/tests/test_cli_schemas.py @@ -415,6 +415,7 @@ def test_valid_mcp_status_changed(self) -> None: "status": "connected", "source": "user", "isManaged": False, + "serverType": "stdio", } ], "summary": { @@ -810,13 +811,11 @@ def test_dispatch_all_20_types( notif = SessionNotification.model_validate(_make_notification(payload)) assert isinstance(notif.params.notification, expected_class) - def test_exactly_20_types_covered(self) -> None: - """Ensure we test all 20 SessionNotificationType values.""" + def test_legacy_types_remain_covered(self) -> None: + """Ensure the original notification payloads remain supported.""" tested_types = {t[0] for t in _NOTIFICATION_TYPE_PAYLOADS} all_types = {member.value for member in SessionNotificationType} - assert tested_types == all_types, ( - f"Missing: {all_types - tested_types}, Extra: {tested_types - all_types}" - ) + assert tested_types <= all_types def test_unknown_type_rejected(self) -> None: payload = {"type": "unknown_type", "data": "test"} diff --git a/tests/test_client.py b/tests/test_client.py index 8a23729..2ff2f06 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -16,6 +16,7 @@ from typing import TYPE_CHECKING, Any import pytest +from pydantic import ValidationError from droid_sdk.errors import ( ConnectionError as DroidConnectionError, @@ -27,7 +28,13 @@ SessionNotFoundError, ) from droid_sdk.protocol import SESSION_INIT_TIMEOUT -from droid_sdk.schemas.enums import DroidServerMethod, JsonRpcErrorCode +from droid_sdk.schemas.client import Base64ImageSource +from droid_sdk.schemas.enums import ( + DroidServerMethod, + JsonRpcErrorCode, + SettingsLevel, +) +from droid_sdk.schemas.messages import DocumentSourceType, PlainTextSource if TYPE_CHECKING: from collections.abc import AsyncIterator @@ -199,6 +206,77 @@ async def do_init() -> Any: return client, transport +class TestCanonicalV5Mutations: + """Coverage for v5 mutation methods added to the raw client.""" + + @pytest.mark.asyncio + async def test_submit_mcp_auth_error(self) -> None: + client, transport = await create_client_with_session() + task = asyncio.create_task( + client.submit_mcp_auth_error( + server_name="oauth-server", + error="access_denied", + error_description="User denied access", + state="state-1", + ) + ) + await asyncio.sleep(0.01) + request = transport.get_last_sent_parsed() + assert request["method"] == "droid.submit_mcp_auth_error" + assert request["params"] == { + "serverName": "oauth-server", + "error": "access_denied", + "errorDescription": "User denied access", + "state": "state-1", + } + transport.inject_message( + make_success_response(request["id"], {"success": True}) + ) + result = await task + assert result.success is True + await client.close() + + +@pytest.mark.asyncio +async def test_session_start_mcp_configs_are_validated_before_send() -> None: + client, transport = await create_connected_client() + invalid = [{"name": "bad", "url": "relative", "type": "http"}] + + with pytest.raises(ValidationError): + await client.initialize_session( + cwd="/repo", + machine_id=None, + mcp_servers=invalid, + ) + with pytest.raises(ValidationError): + await client.load_session(session_id="session", mcp_servers=invalid) + assert transport.sent_messages == [] + + +@pytest.mark.asyncio +async def test_set_skill_disabled() -> None: + client, transport = await create_client_with_session() + task = asyncio.create_task( + client.set_skill_disabled( + skill_name="example-skill", + disabled=True, + settings_level=SettingsLevel.Project, + ) + ) + await asyncio.sleep(0.01) + request = transport.get_last_sent_parsed() + assert request["method"] == "droid.set_skill_disabled" + assert request["params"] == { + "skillName": "example-skill", + "disabled": True, + "settingsLevel": "project", + } + transport.inject_message(make_success_response(request["id"], {"success": True})) + result = await task + assert result.success is True + await client.close() + + # ============================================================ # Tests # ============================================================ @@ -603,6 +681,28 @@ async def do_msg() -> Any: transport.inject_message(make_success_response(sent["id"], {})) await task + @pytest.mark.asyncio + async def test_sends_explicit_null_fields(self) -> None: + """Explicit null fields clear nullable settings on the wire.""" + client, transport = await create_client_with_session() + + task = asyncio.create_task( + client.update_session_settings( + explicit_null_fields=[ + "specModeModelId", + "specModeReasoningEffort", + ] + ) + ) + await asyncio.sleep(0.01) + + sent = transport.get_last_sent_parsed() + assert sent["params"]["specModeModelId"] is None + assert sent["params"]["specModeReasoningEffort"] is None + + transport.inject_message(make_success_response(sent["id"], {})) + await task + @pytest.mark.asyncio async def test_sends_images_and_files(self) -> None: """add_user_message sends images and files.""" @@ -634,6 +734,78 @@ async def do_msg() -> Any: transport.inject_message(make_success_response(sent["id"], {})) await task + @pytest.mark.asyncio + async def test_sends_message_id_and_typed_attachments(self) -> None: + """Typed attachments serialize to JSON-safe wire aliases.""" + client, transport = await create_client_with_session() + + async def do_msg() -> Any: + return await client.add_user_message( + text="See attached", + message_id="message-1", + images=[ + Base64ImageSource( + type="base64", + data="abc123", + media_type="image/png", + ) + ], + files=[ + PlainTextSource( + type=DocumentSourceType.Text, + media_type="text/plain", + data="notes", + name="notes.txt", + ) + ], + ) + + task = asyncio.create_task(do_msg()) + await asyncio.sleep(0.01) + + sent = transport.get_last_sent_parsed() + assert sent["params"] == { + "messageId": "message-1", + "text": "See attached", + "images": [ + { + "type": "base64", + "data": "abc123", + "mediaType": "image/png", + } + ], + "files": [ + { + "type": "text", + "mediaType": "text/plain", + "data": "notes", + "name": "notes.txt", + } + ], + } + + transport.inject_message(make_success_response(sent["id"], {})) + await task + + @pytest.mark.asyncio + async def test_complete_message_payload_is_validated_before_send(self) -> None: + client, transport = await create_client_with_session() + sent_before = len(transport.sent_messages) + + with pytest.raises(ValidationError): + await client.add_user_message( + text="invalid", + images=[ + { + "type": "base64", + "data": "abc123", + "mediaType": "image/png", + "unsupported": True, + } + ], + ) + assert len(transport.sent_messages) == sent_before + @pytest.mark.asyncio async def test_supports_custom_request_id(self) -> None: """add_user_message supports custom request_id.""" diff --git a/tests/test_client_mcp.py b/tests/test_client_mcp.py index 7966f36..3fa7025 100644 --- a/tests/test_client_mcp.py +++ b/tests/test_client_mcp.py @@ -19,6 +19,7 @@ from typing import TYPE_CHECKING, Any import pytest +from pydantic import ValidationError from droid_sdk.errors import ( ConnectionError as DroidConnectionError, @@ -28,6 +29,7 @@ SessionError, ) from droid_sdk.protocol import MCP_AUTH_TIMEOUT +from droid_sdk.schemas.client import McpOAuthOptions from droid_sdk.schemas.enums import DroidServerMethod, SettingsLevel if TYPE_CHECKING: @@ -558,6 +560,116 @@ async def do_call() -> Any: result = await task assert result.success is True + @pytest.mark.asyncio + async def test_add_http_server_with_typed_oauth(self) -> None: + client, transport = await create_client_with_session() + + async def do_call() -> Any: + return await client.add_mcp_server( + name="oauth-server", + type="http", + url="https://mcp.example.com/api", + oauth=McpOAuthOptions( + scopes=["read", "write"], + resource=False, + client_metadata_url="https://client.example.com/metadata", + callback_port=8765, + ), + ) + + task = asyncio.create_task(do_call()) + await asyncio.sleep(0.01) + + sent = transport.get_last_sent_parsed() + assert sent["params"]["oauth"] == { + "scopes": ["read", "write"], + "resource": False, + "clientMetadataUrl": "https://client.example.com/metadata", + "callbackPort": 8765, + } + + transport.inject_message(make_success_response(sent["id"], {"success": True})) + await task + + @pytest.mark.asyncio + async def test_add_http_server_validates_and_serializes_oauth_dict(self) -> None: + client, transport = await create_client_with_session() + oauth = { + "clientId": "client-1", + "clientSecret": "secret-1", + "authorizationServerIssuer": "https://auth.example.com", + "tokenEndpointAuthMethod": "client_secret_post", + } + + task = asyncio.create_task( + client.add_mcp_server( + name="oauth-server", + type="http", + url="https://mcp.example.com/api", + oauth=oauth, + ) + ) + await asyncio.sleep(0.01) + + sent = transport.get_last_sent_parsed() + assert sent["params"]["oauth"] == oauth + + transport.inject_message(make_success_response(sent["id"], {"success": True})) + await task + + @pytest.mark.asyncio + @pytest.mark.parametrize( + "oauth", + [ + { + "clientId": "client-1", + "tokenEndpointAuthMethod": "client_secret_post", + }, + { + "clientMetadataUrl": "https://client.example.com/metadata", + "clientId": "client-1", + "authorizationServerIssuer": "https://auth.example.com", + }, + ], + ) + async def test_add_http_server_rejects_invalid_oauth_mappings( + self, + oauth: dict[str, Any], + ) -> None: + client, transport = await create_client_with_session() + sent_count = len(transport.sent_messages) + + with pytest.raises(ValidationError): + await client.add_mcp_server( + name="oauth-server", + type="http", + url="https://mcp.example.com/api", + oauth=oauth, + ) + + assert len(transport.sent_messages) == sent_count + await client.close() + + @pytest.mark.asyncio + async def test_add_http_server_preserves_explicit_false_oauth(self) -> None: + client, transport = await create_client_with_session() + + task = asyncio.create_task( + client.add_mcp_server( + name="no-oauth-server", + type="http", + url="https://mcp.example.com/api", + oauth=False, + ) + ) + await asyncio.sleep(0.01) + + sent = transport.get_last_sent_parsed() + assert sent["params"]["oauth"] is False + + transport.inject_message(make_success_response(sent["id"], {"success": True})) + await task + @pytest.mark.asyncio async def test_add_stdio_server_minimal(self) -> None: """Add a stdio server with only required fields.""" @@ -746,6 +858,7 @@ async def do_call() -> Any: "status": "connected", "source": "user", "isManaged": False, + "serverType": "stdio", } ], "summary": { diff --git a/tests/test_client_protocol_surface.py b/tests/test_client_protocol_surface.py index af2173f..2fd48cf 100644 --- a/tests/test_client_protocol_surface.py +++ b/tests/test_client_protocol_surface.py @@ -17,12 +17,20 @@ from droid_sdk.errors import SessionError from droid_sdk.protocol import COMPACTION_TIMEOUT from droid_sdk.schemas.client import ( + ApiSessionSource, OutputFormat, RewindFileCreation, RewindFileSnapshot, + SessionSource, SessionTag, ) -from droid_sdk.schemas.enums import DroidServerMethod +from droid_sdk.schemas.enums import ( + AutonomyLevel, + AutonomyMode, + DroidInteractionMode, + DroidServerMethod, + SessionPlatform, +) from tests.helpers import InMemoryTransport, make_success_response _background_tasks: set[asyncio.Task[Any]] = set() @@ -50,7 +58,7 @@ async def _setup_client(transport: InMemoryTransport) -> DroidClient: sent["id"], { "sessionId": "sess-1", - "session": {"id": "sess-1"}, + "session": {"id": "sess-1", "messages": []}, "settings": {"modelId": "claude-sonnet-4", "reasoningEffort": "medium"}, }, ) @@ -96,6 +104,44 @@ async def test_works_before_session_initialization(self) -> None: await client.close() + @pytest.mark.asyncio + async def test_sends_all_hypothetical_settings_and_tool_controls(self) -> None: + transport = InMemoryTransport() + client = DroidClient(transport=transport) + await client.connect() + + sent, _ = await _call( + transport, + client.list_tools( + model_id="model-1", + autonomy_mode=AutonomyMode.AutoHigh, + interaction_mode=DroidInteractionMode.Auto, + autonomy_level=AutonomyLevel.High, + spec_mode_model_id="spec-model", + additional_tool_ids=["custom-tool"], + enabled_tool_ids=[], + disabled_tool_ids=["execute"], + restrict_tool_ids=["read", "custom-tool"], + skip_permissions_unsafe=False, + ), + {"tools": []}, + ) + + assert sent["params"] == { + "modelId": "model-1", + "autonomyMode": "auto-high", + "interactionMode": "auto", + "autonomyLevel": "high", + "specModeModelId": "spec-model", + "additionalToolIds": ["custom-tool"], + "enabledToolIds": [], + "disabledToolIds": ["execute"], + "restrictToolIds": ["read", "custom-tool"], + "skipPermissionsUnsafe": False, + } + + await client.close() + @pytest.mark.asyncio async def test_sends_method_and_parses_result(self) -> None: transport = InMemoryTransport() @@ -448,6 +494,83 @@ async def test_execute_rewind_rejects_malformed_files_locally(self) -> None: class TestNewRequestFields: + @pytest.mark.asyncio + async def test_initialize_session_sends_all_tool_control_settings(self) -> None: + transport = InMemoryTransport() + client = DroidClient(transport=transport) + await client.connect() + + sent, _ = await _call( + transport, + client.initialize_session( + machine_id="m", + cwd="/tmp", + compaction_threshold_check_enabled=False, + additional_tool_ids=["custom-tool"], + restrict_tool_ids=[], + auto_reject_permission_requests=False, + disable_builtin_skills=False, + ), + { + "sessionId": "sess-1", + "session": {"id": "sess-1", "messages": []}, + "settings": {"modelId": "model-1", "reasoningEffort": "medium"}, + }, + ) + + assert sent["params"]["compactionThresholdCheckEnabled"] is False + assert sent["params"]["additionalToolIds"] == ["custom-tool"] + assert sent["params"]["restrictToolIds"] == [] + assert sent["params"]["autoRejectPermissionRequests"] is False + assert sent["params"]["disableBuiltinSkills"] is False + + await client.close() + + @pytest.mark.asyncio + async def test_load_session_sends_all_tool_control_settings(self) -> None: + transport = InMemoryTransport() + client = DroidClient(transport=transport) + await client.connect() + + sent, _ = await _call( + transport, + client.load_session( + session_id="sess-1", + additional_tool_ids=["custom-tool"], + enabled_tool_ids=[], + disabled_tool_ids=["execute"], + auto_reject_permission_requests=False, + disable_builtin_skills=False, + session_location="api", + session_source=SessionSource( + root=ApiSessionSource( + platform=SessionPlatform.Api, + delegation_session_id="delegation-1", + ) + ), + ), + { + "session": {"id": "sess-1", "messages": []}, + "settings": {"modelId": "model-1", "reasoningEffort": "medium"}, + }, + ) + + assert sent["params"] == { + "sessionId": "sess-1", + "additionalToolIds": ["custom-tool"], + "enabledToolIds": [], + "disabledToolIds": ["execute"], + "autoRejectPermissionRequests": False, + "disableBuiltinSkills": False, + "sessionLocation": "api", + "sessionSource": { + "platform": "api", + "delegationSessionId": "delegation-1", + }, + } + + await client.close() + @pytest.mark.asyncio async def test_initialize_session_sends_disabled_tool_ids(self) -> None: transport = InMemoryTransport() @@ -464,7 +587,7 @@ async def test_initialize_session_sends_disabled_tool_ids(self) -> None: ), { "sessionId": "sess-1", - "session": {"id": "sess-1"}, + "session": {"id": "sess-1", "messages": []}, "settings": {"modelId": "claude-sonnet-4", "reasoningEffort": "medium"}, }, ) @@ -489,6 +612,45 @@ async def test_update_session_settings_sends_disabled_tool_ids(self) -> None: await client.close() + @pytest.mark.asyncio + async def test_update_session_settings_sends_all_tool_control_settings( + self, + ) -> None: + transport = InMemoryTransport() + client = await _setup_client(transport) + + sent, _ = await _call( + transport, + client.update_session_settings( + additional_tool_ids=["custom-tool"], + enabled_tool_ids=[], + disabled_tool_ids=["execute"], + restrict_tool_ids=["read", "custom-tool"], + tags=[ + SessionTag(name="typed"), + {"name": "raw", "metadata": {"source": "sdk"}}, + ], + compaction_token_limit=12_000, + compaction_threshold_check_enabled=False, + ), + {}, + ) + + assert sent["params"] == { + "additionalToolIds": ["custom-tool"], + "enabledToolIds": [], + "disabledToolIds": ["execute"], + "restrictToolIds": ["read", "custom-tool"], + "tags": [ + {"name": "typed"}, + {"name": "raw", "metadata": {"source": "sdk"}}, + ], + "compactionTokenLimit": 12_000, + "compactionThresholdCheckEnabled": False, + } + + await client.close() + @pytest.mark.asyncio async def test_add_user_message_output_format_dict(self) -> None: transport = InMemoryTransport() diff --git a/tests/test_client_schemas.py b/tests/test_client_schemas.py index 6204b86..86f587e 100644 --- a/tests/test_client_schemas.py +++ b/tests/test_client_schemas.py @@ -5,7 +5,7 @@ import json import pytest -from pydantic import ValidationError +from pydantic import TypeAdapter, ValidationError from droid_sdk.schemas.client import ( AddMcpServerRequest, @@ -88,6 +88,7 @@ SettingsLevel, SkillLocation, ) +from droid_sdk.schemas.messages import Base64PDFSource, PlainTextSource from droid_sdk.schemas.shared import ( JsonRpcResponseFailure, ) @@ -163,23 +164,23 @@ class TestDocumentSource: """Tests for DocumentSource.""" def test_pdf_source(self) -> None: - doc = DocumentSource( + doc = Base64PDFSource( type="base64", media_type="application/pdf", data="base64data" ) assert doc.type == "base64" assert doc.media_type == "application/pdf" def test_text_source(self) -> None: - doc = DocumentSource( + doc = PlainTextSource( type="text", media_type="text/plain", data="hello", name="test.txt" ) assert doc.name == "test.txt" def test_camel_case_roundtrip(self) -> None: - doc = DocumentSource(type="base64", media_type="application/pdf", data="xyz") + doc = Base64PDFSource(type="base64", media_type="application/pdf", data="xyz") d = doc.model_dump(by_alias=True) assert "mediaType" in d - doc2 = DocumentSource.model_validate(d) + doc2 = TypeAdapter(DocumentSource).validate_python(d) assert doc2.media_type == doc.media_type @@ -200,13 +201,20 @@ class TestSessionSource: """Tests for SessionSource.""" def test_basic_source(self) -> None: - src = SessionSource(platform="web") + src = SessionSource.model_validate( + {"platform": "web", "delegationSessionId": "delegation-1"} + ) assert src.platform == "web" def test_extra_fields_allowed(self) -> None: """SessionSource allows platform-specific extra fields.""" src = SessionSource.model_validate( - {"platform": "slack", "teamId": "T123", "channel": "C456"} + { + "platform": "slack", + "delegationSessionId": "delegation-1", + "teamId": "T123", + "channel": "C456", + } ) assert src.platform == "slack" @@ -429,7 +437,9 @@ def test_all_optional_params(self) -> None: skip_permissions_unsafe=True, enabled_tool_ids=["slackPostMessageTool"], session_location="linear://issue/123", - session_source=SessionSource(platform="web"), + session_source=SessionSource.model_validate( + {"platform": "web", "delegationSessionId": "delegation-1"} + ), tags=[SessionTag(name="mission:worker")], mcp_oauth_callback_uri="https://example.com/callback", ) @@ -472,7 +482,9 @@ def test_camel_case_serialization_includes_all_fields(self) -> None: skip_permissions_unsafe=False, enabled_tool_ids=["t1"], session_location="loc", - session_source=SessionSource(platform="api"), + session_source=SessionSource.model_validate( + {"platform": "api", "delegationSessionId": "delegation-1"} + ), tags=[SessionTag(name="tag1")], mcp_oauth_callback_uri="https://cb.com", ) @@ -531,7 +543,7 @@ def test_with_images_and_files(self) -> None: Base64ImageSource(type="base64", data="abc", media_type="image/png"), ], files=[ - DocumentSource(type="text", media_type="text/plain", data="content"), + PlainTextSource(type="text", media_type="text/plain", data="content"), ], ) assert p.text == "Hello" @@ -1161,7 +1173,7 @@ def test_invalid_settings_level(self) -> None: InitializeSessionResult, { "sessionId": "s1", - "session": {}, + "session": {"messages": []}, "settings": {"modelId": "m", "reasoningEffort": "medium"}, }, ), @@ -1169,7 +1181,7 @@ def test_invalid_settings_level(self) -> None: "load_session", LoadSessionResult, { - "session": {}, + "session": {"messages": []}, "settings": {"modelId": "m", "reasoningEffort": "medium"}, }, ), diff --git a/tests/test_client_transport_abstraction.py b/tests/test_client_transport_abstraction.py index 46c7412..2490ba0 100644 --- a/tests/test_client_transport_abstraction.py +++ b/tests/test_client_transport_abstraction.py @@ -114,9 +114,9 @@ def test_importable_from_types_module(self) -> None: assert Transport is not None - def test_importable_from_top_level(self) -> None: - """DroidClientTransport can be imported from droid_sdk.""" - from droid_sdk import DroidClientTransport as Transport + def test_importable_from_low_level(self) -> None: + """DroidClientTransport can be imported from droid_sdk.low_level.""" + from droid_sdk.low_level import DroidClientTransport as Transport assert Transport is not None diff --git a/tests/test_enums.py b/tests/test_enums.py index 6eb5e27..0e855ed 100644 --- a/tests/test_enums.py +++ b/tests/test_enums.py @@ -77,15 +77,15 @@ def test_factory_client_version(self) -> None: ENUM_MEMBER_COUNTS: list[tuple[type[Enum], int]] = [ - (DroidServerMethod, 29), + (DroidServerMethod, 31), (DroidClientMethod, 3), - (SessionNotificationType, 20), - (ToolConfirmationOutcome, 8), - (ToolConfirmationType, 9), - (DroidWorkingState, 5), + (SessionNotificationType, 35), + (ToolConfirmationOutcome, 15), + (ToolConfirmationType, 11), + (DroidWorkingState, 6), (DroidErrorType, 7), (McpServerStatus, 5), - (McpServerType, 2), + (McpServerType, 3), (McpStatus, 5), (McpAuthOutcome, 3), (DecompSessionType, 2), @@ -107,7 +107,7 @@ def test_factory_client_version(self) -> None: (ReasoningEffort, 9), (ModelProvider, 7), (SettingsLevel, 7), - (SkillLocation, 3), + (SkillLocation, 4), ] diff --git a/tests/test_errors.py b/tests/test_errors.py index d677471..146eb73 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -409,7 +409,7 @@ def test_errors_do_not_shadow_builtins(self) -> None: def test_error_repr_includes_class_name(self) -> None: """repr() includes the class name for debugging.""" err = DroidClientError("test") - assert "DroidClientError" in repr(err) + assert "DroidError" in repr(err) def test_str_of_each_error_with_metadata(self) -> None: """Verify str() of each error type includes its metadata.""" diff --git a/tests/test_integration.py b/tests/test_integration.py index deede93..9273f07 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -328,7 +328,7 @@ async def inject_init_response() -> None: request["id"], { "sessionId": "struct-session", - "session": {"id": "struct-session"}, + "session": {"id": "struct-session", "messages": []}, "settings": { "modelId": "test-model", "reasoningEffort": "medium", diff --git a/tests/test_live_droid_exec.py b/tests/test_live_droid_exec.py index 6083791..6fd5769 100644 --- a/tests/test_live_droid_exec.py +++ b/tests/test_live_droid_exec.py @@ -14,13 +14,9 @@ import pytest -from droid_sdk import ( - AssistantTextDelta, - DroidClient, - ProcessTransport, - ToolConfirmationOutcome, - TurnComplete, -) +from droid_sdk import ToolConfirmationOutcome +from droid_sdk.low_level import DroidClient, ProcessTransport +from droid_sdk.stream import AssistantTextDelta, TurnComplete if TYPE_CHECKING: from collections.abc import AsyncIterator diff --git a/tests/test_low_level_example.py b/tests/test_low_level_example.py new file mode 100644 index 0000000..d569a5e --- /dev/null +++ b/tests/test_low_level_example.py @@ -0,0 +1,100 @@ +"""Offline test for the public low-level example.""" + +from __future__ import annotations + +import asyncio +import json +from typing import TYPE_CHECKING, Any + +import pytest +from examples.low_level_session import run_session + +from droid_sdk.low_level import DroidClient, ListToolsResult + +if TYPE_CHECKING: + from collections.abc import AsyncIterator + + +_STOP = object() + + +class ExampleTransport: + """Deterministic in-memory responder for the example flow.""" + + def __init__(self) -> None: + self._connected = False + self._queue: asyncio.Queue[dict[str, Any] | object] = asyncio.Queue() + self.methods: list[str] = [] + + @property + def is_connected(self) -> bool: + return self._connected + + async def connect(self) -> None: + self._connected = True + + async def send(self, message: str) -> None: + request = json.loads(message) + method = request["method"] + self.methods.append(method) + if method == "droid.initialize_session": + result: dict[str, Any] = { + "sessionId": "example-session", + "session": {"messages": []}, + "settings": { + "modelId": "example-model", + "reasoningEffort": "medium", + }, + } + elif method == "droid.list_tools": + result = { + "tools": [ + { + "id": "read", + "displayName": "Read", + "defaultAllowed": True, + "currentlyAllowed": True, + } + ] + } + else: + raise AssertionError(f"Unexpected method: {method}") + self._queue.put_nowait( + { + "jsonrpc": "2.0", + "factoryApiVersion": "1.0.0", + "factoryProtocolVersion": "1.1.0", + "type": "response", + "id": request["id"], + "result": result, + } + ) + + async def read_messages(self) -> AsyncIterator[dict[str, Any]]: + while True: + message = await self._queue.get() + if message is _STOP: + return + assert isinstance(message, dict) + yield message + + async def close(self) -> None: + self._connected = False + self._queue.put_nowait(_STOP) + + +@pytest.mark.asyncio +async def test_low_level_example_flow(capsys: pytest.CaptureFixture[str]) -> None: + transport = ExampleTransport() + result = await run_session( + DroidClient(transport=transport), + cwd="/tmp/example", + machine_id="test-machine", + ) + + assert isinstance(result, ListToolsResult) + assert result.tools[0].id == "read" + assert transport.methods == ["droid.initialize_session", "droid.list_tools"] + output = capsys.readouterr().out + assert "Session: example-session" in output + assert "Available tools: 1" in output diff --git a/tests/test_mcp_schemas.py b/tests/test_mcp_schemas.py index ab72a66..e66439f 100644 --- a/tests/test_mcp_schemas.py +++ b/tests/test_mcp_schemas.py @@ -204,6 +204,7 @@ def test_construction_minimal(self) -> None: status=McpServerStatus.Connected, source=SettingsLevel.User, is_managed=True, + server_type=McpServerType.Stdio, ) assert info.name == "my-server" assert info.status == McpServerStatus.Connected @@ -211,7 +212,7 @@ def test_construction_minimal(self) -> None: assert info.is_managed is True assert info.error is None assert info.tool_count is None - assert info.server_type is None + assert info.server_type == McpServerType.Stdio assert info.has_auth_tokens is None def test_construction_all_fields(self) -> None: @@ -272,6 +273,7 @@ def test_json_roundtrip(self) -> None: status=McpServerStatus.Connecting, source=SettingsLevel.Runtime, is_managed=False, + server_type=McpServerType.Stdio, tool_count=0, ) roundtripped = McpServerStatusInfo.model_validate_json( @@ -287,6 +289,7 @@ def test_extra_field_allowed(self) -> None: "status": "connected", "source": "user", "isManaged": True, + "serverType": "stdio", "unknown": "tolerated", } ) @@ -637,6 +640,7 @@ def test_mcp_server_status_info_enum_serialization(self) -> None: status=McpServerStatus.Disabled, source=SettingsLevel.Org, is_managed=False, + server_type=McpServerType.Stdio, ) data = json.loads(info.model_dump_json(by_alias=True)) assert data["status"] == "disabled" diff --git a/tests/test_messages.py b/tests/test_messages.py index 60b32e0..38c56d3 100644 --- a/tests/test_messages.py +++ b/tests/test_messages.py @@ -160,7 +160,7 @@ def test_construction(self) -> None: }, } ) - assert block.source["type"] == "text" + assert block.source.type == "text" class TestImageBlock: diff --git a/tests/test_protocol.py b/tests/test_protocol.py index 5711d2c..8497604 100644 --- a/tests/test_protocol.py +++ b/tests/test_protocol.py @@ -36,6 +36,7 @@ ) from droid_sdk.errors import ( DroidClientError, + InvalidWorkingDirectoryError, ProtocolError, SessionNotFoundError, ) @@ -47,7 +48,9 @@ MCP_AUTH_TIMEOUT, SESSION_INIT_TIMEOUT, ProtocolEngine, + ProtocolTiming, ) +from droid_sdk.schemas.cli import RequestPermissionResult from droid_sdk.schemas.constants import ( FACTORY_PROTOCOL_VERSION, JSONRPC_VERSION, @@ -412,6 +415,47 @@ async def test_out_of_order_responses( assert result2["result"]["servers"] == ["s1"] +class TestProtocolObservability: + """Tests for content-free tracing and timing hooks.""" + + @pytest.mark.asyncio + async def test_trace_metadata_and_timing_callback( + self, transport: MockTransport + ) -> None: + timings: list[ProtocolTiming] = [] + + def inject(carrier: dict[str, str]) -> None: + carrier["traceparent"] = "00-trace-parent" + carrier["ignored"] = "secret" + + traced_engine = ProtocolEngine( + transport=transport, + trace_meta_injector=inject, + timing_callback=timings.append, + ) + await traced_engine.start() + try: + task = asyncio.create_task( + traced_engine.send_request( + "droid.list_skills", {"sensitive": "not-observed"} + ) + ) + await asyncio.sleep(0.01) + sent = transport.get_last_sent() + assert sent["_meta"] == {"traceparent": "00-trace-parent"} + + transport.deliver_message(make_success_response(sent["id"])) + await task + + assert len(timings) == 1 + assert timings[0].method == "droid.list_skills" + assert timings[0].outcome == "success" + assert timings[0].duration_seconds >= 0 + assert not hasattr(timings[0], "params") + finally: + await traced_engine.close() + + # ============================================================ # VAL-PROTOCOL-004: Timeout handling with metadata # ============================================================ @@ -596,6 +640,34 @@ async def handler(params: dict[str, Any]) -> str: assert resp["type"] == "response" assert resp["result"]["selectedOption"] == "proceed_once" + @pytest.mark.asyncio + async def test_complete_permission_result_is_serialized( + self, engine: ProtocolEngine, transport: MockTransport + ) -> None: + async def handler(params: dict[str, Any]) -> RequestPermissionResult: + return RequestPermissionResult( + selectedOption="proceed_edit", + comment="approved", + editedSpecContent="updated spec", + ) + + engine.set_permission_handler(handler) + transport.deliver_message( + make_server_request( + "perm-complete", + "droid.request_permission", + {"toolUses": [], "options": []}, + ) + ) + await asyncio.sleep(0.05) + + response = json.loads(transport.sent_messages[-1]) + assert response["result"] == { + "selectedOption": "proceed_edit", + "comment": "approved", + "editedSpecContent": "updated spec", + } + @pytest.mark.asyncio async def test_permission_no_handler_returns_cancel( self, engine: ProtocolEngine, transport: MockTransport @@ -638,6 +710,42 @@ async def bad_handler(params: dict[str, Any]) -> str: resp = json.loads(response_msgs[0]) assert resp["error"]["code"] == JsonRpcErrorCode.INTERNAL_ERROR.value + @pytest.mark.asyncio + async def test_handler_exception_diagnostics_do_not_disclose_secrets( + self, + engine: ProtocolEngine, + transport: MockTransport, + caplog: pytest.LogCaptureFixture, + ) -> None: + secret = "SENTINEL-handler-secret-4f81" + + async def bad_handler(params: dict[str, Any]) -> str: + raise RuntimeError(f"credential={secret}") + + engine.set_permission_handler(bad_handler) + caplog.set_level(logging.WARNING, logger="droid_sdk.protocol") + engine._handle_message( + json.loads( + make_server_request( + "perm-private", + "droid.request_permission", + {"toolUses": [], "options": []}, + ) + ) + ) + task = next(iter(engine._background_tasks)) + await task + + response = next( + json.loads(message) + for message in transport.sent_messages + if "perm-private" in message + ) + assert response["error"]["data"] == {"exceptionType": "RuntimeError"} + surfaces = (caplog.text, json.dumps(response), str(response), repr(response)) + assert all(secret not in surface for surface in surfaces) + assert "RuntimeError" in caplog.text + # ============================================================ # VAL-PROTOCOL-007: Server→client request handling — ask_user @@ -772,6 +880,45 @@ async def test_other_error_maps_to_protocol_error( await task assert exc_info.value.code == JsonRpcErrorCode.INTERNAL_ERROR.value + @pytest.mark.asyncio + async def test_entity_not_found_for_other_method_remains_protocol_error( + self, engine: ProtocolEngine, transport: MockTransport + ) -> None: + task = asyncio.create_task(engine.send_request("droid.list_skills", {})) + await asyncio.sleep(0.01) + sent = transport.get_last_sent() + transport.deliver_message( + make_error_response( + sent["id"], + JsonRpcErrorCode.ENTITY_NOT_FOUND.value, + "Tool not found", + ) + ) + + with pytest.raises(ProtocolError): + await task + + @pytest.mark.asyncio + async def test_invalid_initialize_cwd_maps_to_specific_error( + self, engine: ProtocolEngine, transport: MockTransport + ) -> None: + task = asyncio.create_task( + engine.send_request("droid.initialize_session", {"cwd": "/missing/project"}) + ) + await asyncio.sleep(0.01) + sent = transport.get_last_sent() + transport.deliver_message( + make_error_response( + sent["id"], + JsonRpcErrorCode.INVALID_PARAMS.value, + "Invalid working directory", + ) + ) + + with pytest.raises(InvalidWorkingDirectoryError) as exc_info: + await task + assert exc_info.value.cwd == "/missing/project" + @pytest.mark.asyncio async def test_error_response_contains_metadata( self, engine: ProtocolEngine, transport: MockTransport diff --git a/tests/test_public_api.py b/tests/test_public_api.py index 85cbf87..a738145 100644 --- a/tests/test_public_api.py +++ b/tests/test_public_api.py @@ -1,530 +1,277 @@ -"""Tests for the public API surface of droid_sdk. - -Verifies: -- All __all__ exports are importable from the top-level package -- __version__ exists and matches pyproject.toml -- All error classes are importable from top level -- Key enums are importable from top level -- DroidClientTransport is importable from top level -- schemas __init__ re-exports all schema models -- No bare Any in public method signatures of DroidClient -- examples/interactive_session.py is valid Python -""" +"""Exact v5 root and low-level namespace checks.""" from __future__ import annotations -import ast -import importlib -import re -from pathlib import Path -from typing import Any, ClassVar +import inspect import droid_sdk -import droid_sdk.schemas as schemas_pkg - -# ============================================================ -# __all__ exports -# ============================================================ - - -class TestTopLevelAllExports: - """All symbols in droid_sdk.__all__ are importable.""" - - def test_all_is_a_list(self) -> None: - """__all__ is a list of strings.""" - assert isinstance(droid_sdk.__all__, list) - assert len(droid_sdk.__all__) > 0 - for name in droid_sdk.__all__: - assert isinstance(name, str) - - def test_all_exports_importable(self) -> None: - """Every name in __all__ resolves to a real object.""" - for name in droid_sdk.__all__: - obj = getattr(droid_sdk, name, None) - assert obj is not None, f"{name!r} listed in __all__ but not importable" - - def test_version_in_all(self) -> None: - """__version__ is listed in __all__.""" - assert "__version__" in droid_sdk.__all__ - - def test_droid_client_in_all(self) -> None: - """DroidClient is listed in __all__.""" - assert "DroidClient" in droid_sdk.__all__ - - def test_process_transport_in_all(self) -> None: - """ProcessTransport is listed in __all__.""" - assert "ProcessTransport" in droid_sdk.__all__ - - def test_droid_client_transport_in_all(self) -> None: - """DroidClientTransport is listed in __all__.""" - assert "DroidClientTransport" in droid_sdk.__all__ - - -# ============================================================ -# __version__ -# ============================================================ - - -class TestVersion: - """__version__ exists and matches pyproject.toml.""" - - def test_version_exists(self) -> None: - """__version__ is a non-empty string.""" - assert hasattr(droid_sdk, "__version__") - assert isinstance(droid_sdk.__version__, str) - assert len(droid_sdk.__version__) > 0 - - def test_version_matches_pyproject(self) -> None: - """__version__ matches the version in pyproject.toml.""" - pyproject_path = Path(__file__).parent.parent / "pyproject.toml" - content = pyproject_path.read_text() - match = re.search(r'version\s*=\s*"([^"]+)"', content) - assert match is not None, "Could not find version in pyproject.toml" - expected = match.group(1) - assert droid_sdk.__version__ == expected - - -# ============================================================ -# Error classes importable from top level -# ============================================================ - - -class TestErrorClassesImportable: - """All error classes are importable from the top-level package.""" - - ERROR_CLASSES: ClassVar[list[str]] = [ - "DroidClientError", - "ConnectionError", - "TimeoutError", - "ProtocolError", - "SessionError", - "SessionNotFoundError", - "ProcessExitError", - ] - - def test_all_error_classes_in_all(self) -> None: - """All error classes are listed in __all__.""" - for name in self.ERROR_CLASSES: - assert name in droid_sdk.__all__, f"{name} not in __all__" - - def test_all_error_classes_importable(self) -> None: - """All error classes are actual importable classes.""" - for name in self.ERROR_CLASSES: - cls = getattr(droid_sdk, name) - assert isinstance(cls, type), f"{name} is not a class" - - def test_error_hierarchy(self) -> None: - """Error classes have correct inheritance hierarchy.""" - base = droid_sdk.DroidClientError - assert issubclass(droid_sdk.ConnectionError, base) - assert issubclass(droid_sdk.TimeoutError, base) - assert issubclass(droid_sdk.ProtocolError, base) - assert issubclass(droid_sdk.SessionError, base) - assert issubclass(droid_sdk.SessionNotFoundError, base) - assert issubclass( - droid_sdk.SessionNotFoundError, - droid_sdk.SessionError, - ) - assert issubclass(droid_sdk.ProcessExitError, base) - - -# ============================================================ -# Key enums importable from top level -# ============================================================ - - -class TestEnumsImportable: - """Key enums are importable from the top-level package.""" - - ENUM_NAMES: ClassVar[list[str]] = [ - "ToolConfirmationOutcome", - "SessionNotificationType", +from droid_sdk import ( + Document, + Image, + McpServerStatus, + Session, + ToolConfirmationOutcome, + ToolConfirmationType, + list_sessions, + run, +) +from droid_sdk.low_level import DroidClient, DroidClientTransport, ProcessTransport + + +def test_v5_entry_points_are_exported() -> None: + assert droid_sdk.Session is Session + assert droid_sdk.run is run + assert droid_sdk.list_sessions is list_sessions + assert {"Session", "run", "list_sessions"} <= set(droid_sdk.__all__) + + +def test_root_exports_are_unique_and_present() -> None: + assert len(droid_sdk.__all__) == len(set(droid_sdk.__all__)) + assert all(hasattr(droid_sdk, name) for name in droid_sdk.__all__) + + +def test_root_export_snapshot_is_exact() -> None: + expected = { + name + for name in [ + "MAX_ATTACHMENT_BYTES", + "MAX_PDF_ATTACHMENT_BYTES", + "ApplyPatchAction", + "ApplyPatchFile", + "AskUserAction", + "AskUserParseError", + "AssistantMessage", + "Autonomy", + "Base64ImageSource", + "CompactOutcome", + "ContentBlock", + "ContextAccuracy", + "ContextUsage", + "ConversationMessage", + "CreateFile", + "Document", + "DocumentBlock", + "DocumentSource", + "DroidConnectionError", + "DroidError", + "DroidProcessError", + "DroidProtocolError", + "DroidShieldViolationAction", + "DroidTool", + "EditAction", + "ErrorEvent", + "ErrorType", + "ExecuteAction", + "ExitSpecModeAction", + "FrozenJsonObject", + "FrozenJsonValue", + "HookExecution", + "HttpHeader", + "HttpMcpServerConfig", + "Image", + "ImageBlock", + "ImageMediaType", + "InteractionHandlers", + "InvalidAttachmentError", + "InvalidWorkingDirectoryError", + "JsonObject", + "JsonSchema", + "JsonValue", + "ListToolsOptions", + "McpAuthCompleted", + "McpAuthOutcome", + "McpAuthRequired", + "McpConfigError", + "McpMutationResult", + "McpOAuthOptions", + "McpServerConfig", + "McpServerStatus", + "McpServerStatusInfo", + "McpServerType", + "McpServersResult", + "McpStatusChanged", + "McpStatusSummary", + "McpToolAction", + "McpToolInfo", + "McpToolInputSchema", + "Message", + "Mode", + "OAuthTokenEndpointAuthMethod", + "PdfDocumentSource", + "PermissionAction", + "PermissionHandler", + "PermissionOption", + "PermissionRequest", + "PermissionResolved", + "PermissionResponse", + "Plan", + "Question", + "QuestionAnswer", + "QuestionHandler", + "QuestionRequest", + "QuestionResponse", + "ReasoningEffort", + "RedactedThinkingBlock", + "RewindEvictedFile", + "RewindFileCreation", + "RewindFileSnapshot", + "RewindInfo", + "RewindOutcome", + "RunFailure", + "RunInterrupted", + "RunResult", + "RunStream", + "RunSuccess", + "RunTimeoutError", + "Runtime", + "SandboxOperation", + "SandboxSettings", + "SandboxViolationAction", + "SandboxViolationReason", + "SandboxViolationType", + "SavedSession", + "SdkMcpServer", + "SessionBusyError", + "SessionClosedError", + "SessionConfig", + "SessionNotFoundError", + "SessionNotOpenError", + "Session", + "SessionPlatform", + "SessionReplacedError", + "SessionReplacementError", + "SessionSettings", + "SessionSettingsUpdate", + "SessionSource", + "SessionTag", + "SessionTitleUpdated", + "SessionWorkingDirectoryChanged", + "SettingsUpdated", + "SkillInfo", + "SkillMutationResult", + "SkillResource", + "SkillsResult", + "SseMcpServerConfig", + "StdioMcpServerConfig", + "StreamEvent", + "StreamIncompleteError", + "StreamMessage", + "StructuredOutputError", + "TextBlock", + "TextComplete", + "TextDelta", + "TextDocumentSource", + "ThinkingBlock", + "ThinkingComplete", + "ThinkingDelta", + "TokenUsageUpdate", + "ToolCall", + "ToolCallDelta", + "ToolCategory", + "ToolConfirmationOutcome", + "ToolConfirmationType", + "ToolInfo", + "ToolProgress", + "ToolProgressUpdate", + "ToolResponse", + "ToolResult", + "ToolResultBlock", + "ToolUseBlock", + "Transport", + "UpdateSettingsResult", + "Usage", + "UserMessage", + "WorkingState", + "WorkingStateChanged", + "list_sessions", + "run", + "__version__", + ] + } + assert set(droid_sdk.__all__) == expected + assert not hasattr(droid_sdk, "SessionError") + + +def test_enum_member_snapshots_are_exact() -> None: + assert tuple(ToolConfirmationOutcome.__members__) == ( + "PROCEED_ONCE", + "PROCEED_ALWAYS", + "PROCEED_ALWAYS_EXACT_PATH", + "PROCEED_AUTO_RUN", + "PROCEED_AUTO_RUN_LOW", + "PROCEED_AUTO_RUN_MEDIUM", + "PROCEED_AUTO_RUN_HIGH", + "PROCEED_NEW_SESSION", + "PROCEED_NEW_SESSION_LOW", + "PROCEED_NEW_SESSION_MEDIUM", + "PROCEED_NEW_SESSION_HIGH", + "PROCEED_EDIT", + "PROCEED_ALWAYS_TOOLS", + "PROCEED_ALWAYS_SERVER", + "CANCEL", + ) + assert tuple(ToolConfirmationType.__members__) == ( + "EDIT", + "EXECUTE", + "CREATE", + "ASK_USER", + "EXIT_SPEC_MODE", + "APPLY_PATCH", + "MCP_TOOL", + "SANDBOX_VIOLATION", + "DROID_SHIELD_VIOLATION", + ) + assert tuple(McpServerStatus.__members__) == ( + "CONNECTING", + "CONNECTED", + "DISCONNECTED", + "FAILED", + "DISABLED", + ) + + +def test_exact_public_signatures_exclude_unsupported_extras() -> None: + assert tuple(inspect.signature(list_sessions).parameters) == ( + "cwd", + "all_workspaces", + "limit", + ) + assert not hasattr(Image, "from_file") + assert not hasattr(Document, "from_file") + assert "path" not in inspect.signature(Document.from_bytes).parameters + for method in ( + Session.remove_mcp_server, + Session.enable_mcp_server, + Session.disable_mcp_server, + ): + assert "scope" not in inspect.signature(method).parameters + + +def test_legacy_low_level_names_are_absent_from_root() -> None: + legacy = { + "AssistantTextDelta", + "DroidClient", + "DroidClientTransport", + "DroidQueryOptions", "DroidWorkingState", "MissionState", - "McpServerStatus", - "ToolConfirmationType", - ] - - def test_all_enums_in_all(self) -> None: - """All key enums are listed in __all__.""" - for name in self.ENUM_NAMES: - assert name in droid_sdk.__all__, f"{name} not in __all__" - - def test_all_enums_importable(self) -> None: - """All key enums are actual importable enum classes.""" - import enum - - for name in self.ENUM_NAMES: - cls = getattr(droid_sdk, name) - assert issubclass(cls, enum.Enum), f"{name} is not an Enum" - - def test_enum_members_accessible(self) -> None: - """Enum members are accessible.""" - assert droid_sdk.DroidWorkingState.Idle.value == "idle" - assert ( - droid_sdk.SessionNotificationType.ASSISTANT_TEXT_DELTA.value - == "assistant_text_delta" - ) - assert droid_sdk.MissionState.Running.value == "running" - assert droid_sdk.McpServerStatus.Connected.value == "connected" - assert droid_sdk.ToolConfirmationOutcome.Cancel.value == "cancel" - assert droid_sdk.ToolConfirmationType.Edit.value == "edit" - - -# ============================================================ -# DroidClientTransport importable -# ============================================================ - - -class TestTransportProtocol: - """DroidClientTransport is importable and is a Protocol.""" - - def test_importable(self) -> None: - """DroidClientTransport is importable from top level.""" - assert hasattr(droid_sdk, "DroidClientTransport") - - def test_is_runtime_checkable(self) -> None: - """DroidClientTransport is runtime_checkable.""" - - transport_cls = droid_sdk.DroidClientTransport - assert hasattr(transport_cls, "__protocol_attrs__") or hasattr( - transport_cls, "_is_runtime_protocol" - ) - - -# ============================================================ -# Schemas __init__ re-exports -# ============================================================ - - -class TestSchemasReExports: - """schemas __init__ re-exports all public models.""" - - def test_schemas_all_is_populated(self) -> None: - """schemas.__all__ has entries.""" - assert isinstance(schemas_pkg.__all__, list) - assert len(schemas_pkg.__all__) > 0 - - def test_all_schemas_exports_importable(self) -> None: - """Every name in schemas.__all__ resolves to a real object.""" - for name in schemas_pkg.__all__: - obj = getattr(schemas_pkg, name, None) - assert obj is not None, ( - f"{name!r} listed in schemas.__all__ but not importable" - ) - - def test_constants_reexported(self) -> None: - """Protocol constants are re-exported.""" - assert schemas_pkg.JSONRPC_VERSION == "2.0" - assert schemas_pkg.FACTORY_PROTOCOL_VERSION == "1.1.0" - assert schemas_pkg.LEGACY_FACTORY_API_VERSION == "1.0.0" - - def test_enums_reexported(self) -> None: - """Key enums are re-exported from schemas.""" - assert hasattr(schemas_pkg, "DroidServerMethod") - assert hasattr(schemas_pkg, "SessionNotificationType") - assert hasattr(schemas_pkg, "JsonRpcErrorCode") - - def test_client_models_reexported(self) -> None: - """Client request/response models are re-exported.""" - assert hasattr(schemas_pkg, "InitializeSessionRequest") - assert hasattr(schemas_pkg, "InitializeSessionResult") - assert hasattr(schemas_pkg, "ClientRequest") - - def test_cli_models_reexported(self) -> None: - """CLI (notification/permission) models are re-exported.""" - assert hasattr(schemas_pkg, "SessionNotification") - assert hasattr(schemas_pkg, "RequestPermissionRequest") - assert hasattr(schemas_pkg, "AskUserRequest") - - def test_mcp_models_reexported(self) -> None: - """MCP models are re-exported.""" - assert hasattr(schemas_pkg, "McpServerStatusInfo") - assert hasattr(schemas_pkg, "McpToolInfo") - - def test_mission_models_reexported(self) -> None: - """Mission decomposition models are re-exported.""" - assert hasattr(schemas_pkg, "MissionFeature") - assert hasattr(schemas_pkg, "ProgressLogEntry") - assert hasattr(schemas_pkg, "Handoff") - - def test_message_models_reexported(self) -> None: - """Message models are re-exported.""" - assert hasattr(schemas_pkg, "FactoryDroidMessage") - assert hasattr(schemas_pkg, "TextBlock") - - def test_shared_models_reexported(self) -> None: - """Shared JSON-RPC models are re-exported.""" - assert hasattr(schemas_pkg, "JsonRpcRequest") - assert hasattr(schemas_pkg, "JsonRpcResponseSuccess") - assert hasattr(schemas_pkg, "JsonRpcResponseFailure") - - -# ============================================================ -# No bare Any in public DroidClient signatures -# ============================================================ - - -class TestNoBareAnyInPublicSignatures: - """Public method signatures of DroidClient should not use bare Any.""" - - def _get_public_methods(self) -> list[tuple[str, Any]]: - """Return (name, method) for public methods on DroidClient.""" - cls = droid_sdk.DroidClient - methods = [] - for name in dir(cls): - if name.startswith("_"): - continue - attr = getattr(cls, name) - if callable(attr) or isinstance(attr, property): - methods.append((name, attr)) - return methods - - def test_public_method_return_annotations_no_bare_any(self) -> None: - """Public methods don't return bare Any.""" - for name, method in self._get_public_methods(): - if isinstance(method, property): - continue - hints = getattr(method, "__annotations__", {}) - ret = hints.get("return") - if ret is None: - continue - # Check the string representation — bare Any appears as - # 'typing.Any' or just 'Any' - ret_str = str(ret) - # Allow dict[str, Any] and similar — only reject bare 'Any' - if ret_str == "typing.Any" or ret_str == "Any": - raise AssertionError(f"DroidClient.{name} returns bare Any") - - -# ============================================================ -# examples/interactive_session.py is valid Python -# ============================================================ - - -class TestExampleScript: - """examples/interactive_session.py is valid Python.""" - - def test_example_exists(self) -> None: - """The example script file exists.""" - path = Path(__file__).parent.parent / "examples" / "interactive_session.py" - assert path.exists(), f"Example not found: {path}" - - def test_example_parses(self) -> None: - """The example script is syntactically valid Python.""" - path = Path(__file__).parent.parent / "examples" / "interactive_session.py" - source = path.read_text() - # ast.parse will raise SyntaxError if invalid - ast.parse(source, filename=str(path)) - - def test_example_imports_sdk(self) -> None: - """The example script imports from droid_sdk.""" - path = Path(__file__).parent.parent / "examples" / "interactive_session.py" - source = path.read_text() - assert "droid_sdk" in source - - def test_example_is_importable(self) -> None: - """The example script's module can be loaded (syntax + import check).""" - path = Path(__file__).parent.parent / "examples" / "interactive_session.py" - # We don't run it (it requires droid CLI), but we can compile it - source = path.read_text() - compile(source, str(path), "exec") - - -# ============================================================ -# py.typed marker exists (PEP 561) -# ============================================================ - - -class TestPyTypedMarker: - """py.typed marker file exists for PEP 561 compliance.""" - - def test_py_typed_exists(self) -> None: - """py.typed file exists in the package directory.""" - # Find the installed package location - pkg_dir = Path(droid_sdk.__file__).parent - py_typed = pkg_dir / "py.typed" - assert py_typed.exists(), f"py.typed not found at {py_typed}" - - -# ============================================================ -# Sub-module __all__ consistency -# ============================================================ - - -# ============================================================ -# Stream types importable from top level (VAL-DX-010) -# ============================================================ - - -class TestStreamTypesImportable: - """All stream message types are importable from the top-level package.""" - - STREAM_TYPE_NAMES: ClassVar[list[str]] = [ - "AssistantTextDelta", + "ProcessTransport", + "SessionNotificationType", "ThinkingTextDelta", "ToolUse", - "ToolResult", - "ToolProgress", - "WorkingStateChanged", - "TokenUsageUpdate", "TurnComplete", - "ErrorEvent", - "StreamMessage", - ] - - def test_all_stream_types_in_all(self) -> None: - """All stream types are listed in __all__.""" - for name in self.STREAM_TYPE_NAMES: - assert name in droid_sdk.__all__, f"{name} not in __all__" - - def test_all_stream_types_importable(self) -> None: - """All stream types resolve to real objects via top-level import.""" - for name in self.STREAM_TYPE_NAMES: - obj = getattr(droid_sdk, name, None) - assert obj is not None, ( - f"{name!r} listed in __all__ but not importable from top level" - ) - - def test_stream_message_is_type_alias(self) -> None: - """StreamMessage is the union type alias of all stream types.""" - # StreamMessage should be importable as a type - sm = droid_sdk.StreamMessage - assert sm is not None - - def test_stream_dataclasses_are_classes(self) -> None: - """Stream dataclasses (excluding StreamMessage) are actual classes.""" - import dataclasses - - for name in self.STREAM_TYPE_NAMES: - if name == "StreamMessage": - continue # StreamMessage is a type alias, not a class - cls = getattr(droid_sdk, name) - assert isinstance(cls, type), f"{name} is not a class" - assert dataclasses.is_dataclass(cls), f"{name} is not a dataclass" - - def test_isinstance_checking_works(self) -> None: - """isinstance() works with stream types imported from top level.""" - delta = droid_sdk.AssistantTextDelta(text="hello") - assert isinstance(delta, droid_sdk.AssistantTextDelta) - - tc = droid_sdk.TurnComplete() - assert isinstance(tc, droid_sdk.TurnComplete) - - err = droid_sdk.ErrorEvent(message="oops", error_type="error") - assert isinstance(err, droid_sdk.ErrorEvent) - - -# ============================================================ -# Query API importable from top level -# ============================================================ - - -class TestQueryApiImportable: - """query() and DroidQueryOptions are importable from the top-level package.""" - - def test_query_in_all(self) -> None: - """query is listed in __all__.""" - assert "query" in droid_sdk.__all__ - - def test_query_importable(self) -> None: - """query is importable and is a callable.""" - assert hasattr(droid_sdk, "query") - assert callable(droid_sdk.query) - - def test_droid_query_options_in_all(self) -> None: - """DroidQueryOptions is listed in __all__.""" - assert "DroidQueryOptions" in droid_sdk.__all__ - - def test_droid_query_options_importable(self) -> None: - """DroidQueryOptions is importable and is a dataclass.""" - import dataclasses - - assert hasattr(droid_sdk, "DroidQueryOptions") - cls = droid_sdk.DroidQueryOptions - assert isinstance(cls, type) - assert dataclasses.is_dataclass(cls) - - def test_droid_query_options_defaults(self) -> None: - """DroidQueryOptions has correct defaults.""" - opts = droid_sdk.DroidQueryOptions() - assert opts.cwd == "." - assert opts.machine_id == "default" - assert opts.model_id is None - assert opts.autonomy_level is None - assert opts.interaction_mode is None - assert opts.reasoning_effort is None - assert opts.mcp_servers is None - assert opts.enabled_tool_ids is None - - -# ============================================================ -# Combined import statement test (VAL-DX-010) -# ============================================================ - - -class TestCombinedImportStatement: - """The exact import statement from the verification step works.""" - - def test_combined_import(self) -> None: - """All key DX types importable in a single import statement.""" - from droid_sdk import ( - AssistantTextDelta, - DroidQueryOptions, - StreamMessage, - TurnComplete, - query, - ) - - assert query is not None - assert AssistantTextDelta is not None - assert TurnComplete is not None - assert DroidQueryOptions is not None - assert StreamMessage is not None - - -# ============================================================ -# Sub-module __all__ consistency -# ============================================================ - - -class TestSubModuleConsistency: - """Sub-module __all__ lists are consistent with actual exports.""" + "query", + } + assert legacy.isdisjoint(droid_sdk.__all__) + # Importing a submodule makes Python attach it to its parent package. + assert all(not hasattr(droid_sdk, name) for name in legacy if name != "query") - MODULES: ClassVar[list[str]] = [ - "droid_sdk.errors", - "droid_sdk.client", - "droid_sdk.transport", - "droid_sdk.types", - "droid_sdk.stream", - "droid_sdk.query", - "droid_sdk.schemas.enums", - "droid_sdk.schemas.constants", - "droid_sdk.schemas.shared", - "droid_sdk.schemas.client", - "droid_sdk.schemas.cli", - "droid_sdk.schemas.mcp", - "droid_sdk.schemas.mission", - "droid_sdk.schemas.messages", - ] - def test_all_modules_importable(self) -> None: - """All sub-modules can be imported.""" - for mod_name in self.MODULES: - mod = importlib.import_module(mod_name) - assert mod is not None, f"Failed to import {mod_name}" +def test_mission_and_daemon_surfaces_are_absent() -> None: + assert not any("Mission" in name or "Daemon" in name for name in droid_sdk.__all__) - def test_all_modules_have_all(self) -> None: - """All sub-modules define __all__.""" - for mod_name in self.MODULES: - mod = importlib.import_module(mod_name) - assert hasattr(mod, "__all__"), f"{mod_name} missing __all__" - def test_all_exports_exist(self) -> None: - """Every name in each module's __all__ is an actual attribute.""" - for mod_name in self.MODULES: - mod = importlib.import_module(mod_name) - for name in mod.__all__: - assert hasattr(mod, name), ( - f"{mod_name}.__all__ contains {name!r} but it is not an attribute" - ) +def test_low_level_escape_hatch() -> None: + assert DroidClient is not None + assert DroidClientTransport is not None + assert ProcessTransport is not None diff --git a/tests/test_query.py b/tests/test_query.py index 9899720..e32f539 100644 --- a/tests/test_query.py +++ b/tests/test_query.py @@ -73,7 +73,7 @@ def _make_init_response(request_id: str) -> dict[str, Any]: request_id=request_id, result={ "sessionId": "test-session", - "session": {"id": "test-session"}, + "session": {"id": "test-session", "messages": []}, "settings": { "modelId": "claude-sonnet-4", "reasoningEffort": "medium", @@ -330,7 +330,7 @@ async def handle_requests() -> None: autonomy_level=AutonomyLevel.High, reasoning_effort=ReasoningEffort.Medium, interaction_mode=DroidInteractionMode.Auto, - mcp_servers=[{"name": "test", "type": "stdio"}], + mcp_servers=[{"name": "test", "command": "server"}], enabled_tool_ids=["tool1"], ), ): @@ -345,7 +345,9 @@ async def handle_requests() -> None: assert params["autonomyLevel"] == "high" assert params["reasoningEffort"] == "medium" assert params["interactionMode"] == "auto" - assert params["mcpServers"] == [{"name": "test", "type": "stdio"}] + assert params["mcpServers"] == [ + {"name": "test", "command": "server", "args": [], "env": {}} + ] assert params["enabledToolIds"] == ["tool1"] @pytest.mark.asyncio diff --git a/tests/test_receive_response.py b/tests/test_receive_response.py index 631e0bb..427ae67 100644 --- a/tests/test_receive_response.py +++ b/tests/test_receive_response.py @@ -66,7 +66,7 @@ def _make_init_response(request_id: str) -> dict[str, Any]: request_id=request_id, result={ "sessionId": "test-session", - "session": {"id": "test-session"}, + "session": {"id": "test-session", "messages": []}, "settings": { "modelId": "claude-sonnet-4", "reasoningEffort": "medium", diff --git a/tests/test_transport.py b/tests/test_transport.py index 3e57663..09344e2 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -172,6 +172,19 @@ def make_exit_script(code: int) -> str: pass """ +# Script that fills stderr beyond a typical OS pipe before protocol output. +LARGE_STDERR_SCRIPT = """ +import sys +sys.stderr.write("diagnostic " * 200000) +sys.stderr.flush() +sys.stdout.write('{"ready": true}\\n') +sys.stdout.flush() +try: + sys.stdin.read() +except: + pass +""" + # Script that waits for input and echoes JSON-RPC style WAIT_AND_ECHO_SCRIPT = """ import sys, json @@ -567,17 +580,47 @@ async def test_exit_drains_remaining_stdout(self) -> None: assert messages[1]["id"] == "2" @pytest.mark.asyncio - async def test_stderr_captured_on_exit(self) -> None: - """Stderr output is captured when process exits abnormally.""" - script = """ + @pytest.mark.parametrize("exit_code", [0, 23]) + async def test_exit_includes_bounded_stderr_diagnostics( + self, + exit_code: int, + ) -> None: + script = f""" import sys -sys.stderr.write("error output\\n") +sys.stderr.write("useful diagnostic " * 5000) +sys.stderr.flush() +sys.exit({exit_code}) +""" + transport = ProcessTransport( + exec_path=sys.executable, + exec_args=["-c", script], + ) + await transport.connect() + _messages, errors = await _read_until_done(transport, timeout=5.0) + + assert len(errors) == 1 + assert isinstance(errors[0], ProcessExitError) + assert "useful diagnostic" in str(errors[0]) + assert len(str(errors[0])) < 17_000 + assert transport._stderr_task is None + + @pytest.mark.asyncio + async def test_stderr_secrets_are_never_exposed( + self, + caplog: pytest.LogCaptureFixture, + ) -> None: + """Raw child stderr and explicit environment secrets stay private.""" + secret = "factory-secret-value" + script = """ +import os, sys +sys.stderr.write(os.environ["PRIVATE_RUNTIME_VALUE"] + "\\n") sys.stderr.flush() sys.exit(1) """ transport = ProcessTransport( exec_path=sys.executable, exec_args=["-c", script], + env={"PRIVATE_RUNTIME_VALUE": secret, "FACTORY_API_KEY": secret}, ) await transport.connect() _messages, errors = await _read_until_done(transport, timeout=5.0) @@ -585,6 +628,36 @@ async def test_stderr_captured_on_exit(self) -> None: exit_errors = [e for e in errors if isinstance(e, ProcessExitError)] assert len(exit_errors) >= 1 assert exit_errors[0].exit_code == 1 + assert secret not in str(exit_errors[0]) + assert secret not in repr(exit_errors[0]) + assert secret not in caplog.text + + @pytest.mark.asyncio + async def test_stderr_redacts_configured_values_and_key_patterns(self) -> None: + configured = "ordinary-configured-value" + api_key = "sk_live_unconfigured_api_key" + script = f""" +import sys +sys.stderr.write( + "configured={configured} API_KEY={api_key} " + "Authorization: Bearer bearer-secret-value" +) +sys.stderr.flush() +sys.exit(1) +""" + transport = ProcessTransport( + exec_path=sys.executable, + exec_args=["-c", script], + env={"DISPLAY_NAME": configured}, + ) + await transport.connect() + _messages, errors = await _read_until_done(transport, timeout=5.0) + + diagnostic = str(errors[0]) + assert "[REDACTED]" in diagnostic + assert configured not in diagnostic + assert api_key not in diagnostic + assert "bearer-secret-value" not in diagnostic # --------------------------------------------------------------------------- @@ -671,6 +744,33 @@ async def test_close_completes_within_bounded_time(self) -> None: # Should complete within grace_period(1s) + 2s buffer assert elapsed < 3.0 + @pytest.mark.asyncio + async def test_close_cancellation_cleans_stderr_task_and_allows_reconnect( + self, + ) -> None: + transport = ProcessTransport( + exec_path=sys.executable, + exec_args=["-c", STUBBORN_SCRIPT], + grace_period=5, + ) + await transport.connect() + await asyncio.sleep(0.2) + stderr_task = transport._stderr_task + assert stderr_task is not None + + close_task = asyncio.create_task(transport.close()) + await asyncio.sleep(0) + close_task.cancel() + with pytest.raises(asyncio.CancelledError): + await close_task + + assert stderr_task.done() + assert transport._stderr_task is None + transport._exec_args = ["-c", ECHO_SCRIPT] + await transport.connect() + await transport.close() + assert transport._stderr_task is None + # --------------------------------------------------------------------------- # ProcessTransport: Reconnection tests @@ -809,6 +909,20 @@ async def test_large_message_send_and_receive(self) -> None: assert messages[0]["id"] == "large" assert len(messages[0]["data"]) == 200_000 + @pytest.mark.asyncio + async def test_large_stderr_before_protocol_output_cannot_deadlock(self) -> None: + transport = ProcessTransport( + exec_path=sys.executable, + exec_args=["-c", LARGE_STDERR_SCRIPT], + ) + await transport.connect() + reader = transport.read_messages() + message = await asyncio.wait_for(anext(reader), timeout=5) + assert message == {"ready": True} + await reader.aclose() + await transport.close() + assert transport._stderr_task is None + # --------------------------------------------------------------------------- # ProcessTransport: Edge cases diff --git a/tests/test_v5_compliance.py b/tests/test_v5_compliance.py new file mode 100644 index 0000000..b18636a --- /dev/null +++ b/tests/test_v5_compliance.py @@ -0,0 +1,304 @@ +"""Regression tests for the canonical v5 compliance gaps.""" + +from __future__ import annotations + +import sys + +import pytest +from pydantic import ValidationError + +import droid_sdk.errors as errors +from droid_sdk.errors import DroidProcessError +from droid_sdk.low_level import ( + ClientRequest, + ContextStatsAccuracy, + DroidServerMethod, + LastCallTokenUsage, + LlmRetryNotification, + LlmRetryReason, + LoadSessionResult, + McpOAuthOptions, + McpOAuthTokenEndpointAuthMethod, + PendingAskUserRequest, + PendingPermissionRequest, + ProcessTransport, + ProtocolEngine, + QueuedUserMessage, + RequestPermissionResult, + SessionData, + SessionPlatform, + SessionSource, + SetSkillDisabledRequest, + SubmitMcpAuthErrorRequest, + ToolConfirmationOutcome, + ToolResultBlock, +) + + +def test_legacy_exception_aliases_are_not_star_exports() -> None: + legacy_names = { + "ConnectionError", + "DroidClientError", + "ProcessExitError", + "ProtocolError", + "TimeoutError", + } + assert legacy_names.isdisjoint(errors.__all__) + assert hasattr(errors, "ProcessExitError") + + +@pytest.mark.parametrize( + ("model", "method", "params"), + [ + ( + SetSkillDisabledRequest, + DroidServerMethod.SET_SKILL_DISABLED, + { + "skillName": "skill", + "disabled": True, + "settingsLevel": "project", + }, + ), + ( + SubmitMcpAuthErrorRequest, + DroidServerMethod.SUBMIT_MCP_AUTH_ERROR, + { + "serverName": "server", + "error": "access_denied", + "errorDescription": "Denied", + "state": "state", + }, + ), + ], +) +def test_new_rpc_requests_are_in_client_union( + model: type[object], + method: DroidServerMethod, + params: dict[str, object], +) -> None: + raw = { + "jsonrpc": "2.0", + "factoryApiVersion": "1.0.0", + "factoryProtocolVersion": "1.1.0", + "type": "request", + "id": "request-1", + "method": method.value, + "params": params, + } + parsed = ClientRequest.model_validate(raw) + assert isinstance(parsed.root, model) + + +@pytest.mark.parametrize( + "source", + [ + {"platform": "slack", "delegationSessionId": "d"}, + {"platform": "web", "delegationSessionId": "d"}, + {"platform": "api", "delegationSessionId": "d"}, + {"platform": "sessions_api", "delegationSessionId": "d"}, + { + "platform": "linear", + "delegationSessionId": "d", + "agentSessionId": "a", + }, + { + "platform": "jira", + "delegationSessionId": "d", + "cloudId": "c", + "issueId": "i", + }, + { + "platform": "microsoft-teams", + "delegationSessionId": "d", + "tenantId": "t", + "conversationId": "c", + "serviceUrl": "https://teams.example", + }, + { + "platform": "readiness-remediation", + "reportId": "r", + "repoUrl": "https://example/repo", + "criterionId": "c", + }, + { + "platform": "readiness-evaluation", + "repoUrl": "https://example/repo", + }, + {"platform": "automation", "automationId": "a", "computerId": "c"}, + {"platform": "wiki-generation", "repoUrl": "https://example/repo"}, + {"platform": "wiki-ci-setup", "repoUrl": "https://example/repo"}, + {"platform": "tui"}, + {"platform": "desktop"}, + {"platform": "acp"}, + {"platform": "unknown"}, + ], +) +def test_session_source_variants(source: dict[str, str]) -> None: + parsed = SessionSource.model_validate(source) + assert isinstance(parsed.platform, SessionPlatform) + + +def test_session_source_requires_platform_specific_fields() -> None: + with pytest.raises(ValidationError): + SessionSource.model_validate({"platform": "web"}) + with pytest.raises(ValidationError): + SessionSource.model_validate({"platform": "linear", "delegationSessionId": "d"}) + with pytest.raises(ValidationError): + SessionSource.model_validate({"platform": "unrecognized"}) + + +def test_tool_result_content_is_a_typed_union() -> None: + result = ToolResultBlock.model_validate( + { + "type": "tool_result", + "toolUseId": "tool-1", + "content": [ + {"type": "text", "text": "done"}, + { + "type": "document", + "source": { + "type": "text", + "mediaType": "text/plain", + "data": "contents", + }, + }, + ], + } + ) + assert isinstance(result.content, list) + with pytest.raises(ValidationError): + ToolResultBlock.model_validate( + { + "type": "tool_result", + "toolUseId": "tool-1", + "content": [{"type": "thinking", "thinking": "not supported"}], + } + ) + + +def test_load_result_uses_typed_snapshots_and_last_call_usage() -> None: + result = LoadSessionResult.model_validate( + { + "session": { + "messages": [ + { + "id": "message-1", + "role": "user", + "content": [{"type": "text", "text": "hello"}], + "createdAt": 1, + "updatedAt": 1, + } + ] + }, + "settings": {"modelId": "model", "reasoningEffort": "medium"}, + "pendingPermissions": [ + {"requestId": "permission-1", "toolUses": [], "options": []} + ], + "pendingAskUserRequests": [ + { + "requestId": "question-1", + "toolCallId": "tool-1", + "questions": [], + } + ], + "queuedMessages": [{"requestId": "message-1", "text": "queued"}], + "lastCallTokenUsage": {"inputTokens": 12, "cacheReadTokens": 3}, + } + ) + assert isinstance(result.session, SessionData) + assert isinstance(result.pending_permissions[0], PendingPermissionRequest) + assert isinstance(result.pending_ask_user_requests[0], PendingAskUserRequest) + assert isinstance(result.queued_messages[0], QueuedUserMessage) + assert isinstance(result.last_call_token_usage, LastCallTokenUsage) + assert result.last_call_token_usage.output_tokens is None + + +def test_canonical_retry_and_context_enums() -> None: + retry = LlmRetryNotification.model_validate( + {"type": "llm_retry", "attempt": 2, "reason": "rate_limited"} + ) + assert retry.reason is LlmRetryReason.RateLimited + assert ContextStatsAccuracy.Exact.value == "exact" + + +@pytest.mark.parametrize( + "oauth", + [ + {"scopes": [" "]}, + {"resource": "not-a-url"}, + {"authorizationServerIssuer": "not-a-url"}, + {"clientId": " "}, + {"clientSecret": " "}, + {"callbackPort": 0}, + {"callbackPort": 65536}, + { + "clientMetadataUrl": "https://client.example/oauth/%2e%2e/metadata.json", + }, + { + "clientMetadataUrl": "https://client.example/oauth/metadata.json", + "clientId": "client", + "authorizationServerIssuer": "https://issuer.example", + }, + { + "clientMetadataUrl": "https://client.example/oauth/metadata.json", + "tokenEndpointAuthMethod": "client_secret_post", + }, + {"clientId": "client"}, + ], +) +def test_oauth_validation_rejects_invalid_combinations( + oauth: dict[str, object], +) -> None: + with pytest.raises(ValidationError): + McpOAuthOptions.model_validate(oauth) + + +def test_oauth_validation_accepts_typed_public_client() -> None: + oauth = McpOAuthOptions.model_validate( + { + "scopes": [" read "], + "clientMetadataUrl": "https://client.example/oauth/metadata.json", + "tokenEndpointAuthMethod": "none", + } + ) + assert oauth.scopes == ["read"] + assert oauth.token_endpoint_auth_method is McpOAuthTokenEndpointAuthMethod.None_ + + +def test_permission_edit_requires_edited_content() -> None: + with pytest.raises(ValidationError): + RequestPermissionResult.model_validate( + {"selectedOption": ToolConfirmationOutcome.ProceedEdit.value} + ) + result = RequestPermissionResult.model_validate( + { + "selectedOption": ToolConfirmationOutcome.ProceedEdit.value, + "editedSpecContent": "edited", + } + ) + assert result.edited_spec_content == "edited" + + +@pytest.mark.asyncio +async def test_normal_process_exit_rejects_pending_and_future_requests() -> None: + transport = ProcessTransport( + exec_path=sys.executable, + exec_args=["-c", "import time; time.sleep(0.2)"], + ) + await transport.connect() + protocol = ProtocolEngine(transport=transport) + await protocol.start() + try: + with pytest.raises(DroidProcessError) as first: + await protocol.send_request( + method="droid.never_responds", + params={}, + timeout=2, + ) + assert first.value.exit_code == 0 + with pytest.raises(DroidProcessError) as second: + await protocol.send_request(method="droid.future", params={}) + assert second.value is first.value + finally: + await protocol.close() + await transport.close() diff --git a/tests/test_v5_discovery.py b/tests/test_v5_discovery.py new file mode 100644 index 0000000..77ac22e --- /dev/null +++ b/tests/test_v5_discovery.py @@ -0,0 +1,97 @@ +from __future__ import annotations + +import json +import os +from typing import TYPE_CHECKING + +import pytest + +import droid_sdk._high_level.discovery as discovery_module +from droid_sdk import list_sessions + +if TYPE_CHECKING: + from pathlib import Path + + +def write_session( + root: Path, + session_id: str, + cwd: Path, + *, + title: str, + mtime: float, + messages: int = 0, +) -> None: + lines = [ + json.dumps( + { + "type": "session_start", + "title": title, + "cwd": str(cwd), + "owner": "owner@example.com", + } + ), + *(json.dumps({"type": "message"}) for _ in range(messages)), + ] + path = root / f"{session_id}.jsonl" + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + os.utime(path, (mtime, mtime)) + + +@pytest.mark.asyncio +async def test_list_sessions_filters_sorts_limits_and_marks_favorites( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + root = tmp_path / "sessions" + root.mkdir() + monkeypatch.setattr(discovery_module, "_sessions_root", lambda: root) + cwd = tmp_path / "project" + cwd.mkdir() + write_session(root, "older", cwd, title="Older", mtime=100, messages=2) + write_session(root, "newer", cwd, title="Newer", mtime=200, messages=1) + write_session(root, "other", tmp_path, title="Other", mtime=300) + (root / "malformed.jsonl").write_text("{bad json", encoding="utf-8") + (root / ".favorites").write_text('["older"]', encoding="utf-8") + + sessions = await list_sessions(cwd=cwd) + assert [session.id for session in sessions] == ["newer", "older"] + assert sessions[1].message_count == 2 + assert sessions[1].is_favorite is True + assert [ + session.id + for session in await list_sessions( + cwd=cwd, + limit=1, + ) + ] == ["newer"] + + +@pytest.mark.asyncio +async def test_list_sessions_skips_archived_and_supports_all_workspaces( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + root = tmp_path / "sessions" + root.mkdir() + monkeypatch.setattr(discovery_module, "_sessions_root", lambda: root) + cwd = tmp_path / "project" + cwd.mkdir() + write_session(root, "active", cwd, title="Active", mtime=100) + write_session(root, "archived", cwd, title="Archived", mtime=200) + (root / "archived.settings.json").write_text( + '{"archivedAt":"2025-01-01T00:00:00Z"}', + encoding="utf-8", + ) + + sessions = await list_sessions( + cwd=tmp_path, + all_workspaces=True, + ) + assert [session.id for session in sessions] == ["active"] + + +@pytest.mark.asyncio +async def test_list_sessions_rejects_invalid_options(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="non-negative"): + await list_sessions(cwd=tmp_path, limit=-1) diff --git a/tests/test_v5_foundation.py b/tests/test_v5_foundation.py new file mode 100644 index 0000000..8def88f --- /dev/null +++ b/tests/test_v5_foundation.py @@ -0,0 +1,130 @@ +"""Focused contract tests for the SDK v5 low-level foundation.""" + +from __future__ import annotations + +from pathlib import Path + +from droid_sdk.errors import ( + DroidConnectionError, + DroidError, + DroidProcessError, + DroidProtocolError, + InvalidAttachmentError, + InvalidWorkingDirectoryError, + RunTimeoutError, + SessionBusyError, + SessionClosedError, + SessionNotFoundError, + SessionNotOpenError, + SessionReplacedError, + SessionReplacementError, + StreamIncompleteError, +) +from droid_sdk.low_level import ( + AgentTurnCompletedNotification, + AgentTurnCompletionReason, + McpOAuthOptions, + ProcessTransport, + ProtocolEngine, + SandboxMode, + SessionNotification, + SessionNotificationType, + ToolExecutionLifecyclePhase, + Transport, +) +from droid_sdk.schemas.client import TokenUsage + + +def test_v5_exception_hierarchy_and_metadata() -> None: + exception_types = ( + RunTimeoutError, + StreamIncompleteError, + InvalidAttachmentError, + SessionNotOpenError, + SessionBusyError, + SessionClosedError, + SessionReplacedError, + SessionReplacementError, + SessionNotFoundError, + InvalidWorkingDirectoryError, + DroidConnectionError, + DroidProcessError, + DroidProtocolError, + ) + assert all(issubclass(error_type, DroidError) for error_type in exception_types) + + timeout = RunTimeoutError( + "timed out", request_id="req-1", method="droid.test", timeout_duration=1.5 + ) + assert (timeout.request_id, timeout.method, timeout.timeout_duration) == ( + "req-1", + "droid.test", + 1.5, + ) + assert DroidProcessError("exited", exit_code=9).exit_code == 9 + assert DroidProtocolError("bad", code=-32602, data={"field": "cwd"}).data == { + "field": "cwd" + } + + +def test_canonical_enum_values() -> None: + assert SessionNotificationType.AGENT_TURN_COMPLETED.value == "agent_turn_completed" + assert AgentTurnCompletionReason.StructuredOutputInvalid.value == ( + "structured_output_invalid" + ) + assert ToolExecutionLifecyclePhase.SettledAfterExecution.value == ( + "settled_after_execution" + ) + assert SandboxMode.WholeProcess.value == "whole-process" + + +def test_turn_completion_schema_and_aliases() -> None: + payload = { + "type": "agent_turn_completed", + "reason": "completed", + "turnId": "turn-1", + "tokenUsage": { + "inputTokens": 1, + "outputTokens": 2, + "cacheCreationTokens": 3, + "cacheReadTokens": 4, + "thinkingTokens": 5, + }, + "durationMs": 12.5, + } + notification = SessionNotification.model_validate( + { + "jsonrpc": "2.0", + "factoryApiVersion": "1.0.0", + "factoryProtocolVersion": "1.1.0", + "type": "notification", + "method": "droid.session_notification", + "params": {"notification": payload}, + } + ) + completed = notification.params.notification + assert isinstance(completed, AgentTurnCompletedNotification) + assert completed.token_usage == TokenUsage.model_validate(payload["tokenUsage"]) + assert completed.model_dump(by_alias=True)["durationMs"] == 12.5 + + +def test_mcp_oauth_aliases_and_low_level_exports() -> None: + options = McpOAuthOptions.model_validate( + { + "clientId": "client", + "callbackPort": 8123, + "authorizationServerIssuer": "https://issuer.example", + } + ) + assert options.client_id == "client" + assert options.model_dump(by_alias=True)["callbackPort"] == 8123 + assert ProcessTransport is not None + assert ProtocolEngine is not None + assert Transport is not None + + +def test_dependency_and_pyright_metadata() -> None: + pyproject = (Path(__file__).parents[1] / "pyproject.toml").read_text() + assert '"mcp>=1.27,<2"' in pyproject + assert '"pyright"' in pyproject + assert 'typeCheckingMode = "strict"' in pyproject diff --git a/tests/test_v5_mcp.py b/tests/test_v5_mcp.py new file mode 100644 index 0000000..58b60df --- /dev/null +++ b/tests/test_v5_mcp.py @@ -0,0 +1,271 @@ +from __future__ import annotations + +import asyncio +from datetime import datetime, timezone +from typing import TYPE_CHECKING + +import httpx +import jsonschema +import pytest +from mcp import ClientSession +from mcp.client.streamable_http import streamable_http_client +from pydantic import BaseModel, Field, ValidationError + +import droid_sdk.mcp as mcp_module +from droid_sdk.mcp import ToolResponse, create_sdk_mcp_server, tool + +if TYPE_CHECKING: + from collections.abc import Mapping + + +@tool("add", "Add two integers") +def add(a: int, b: int) -> ToolResponse: + return ToolResponse(str(a + b), structured_content={"result": a + b}) + + +@tool("echo_async", "Echo text asynchronously") +async def echo_async(text: str) -> str: + return text + + +class SumOutput(BaseModel): + result: int + + +@tool("typed_add", "Return a typed sum") +def typed_add(a: int, b: int) -> SumOutput: + return SumOutput(result=a + b) + + +class AliasedOutput(BaseModel): + result_value: int = Field(serialization_alias="resultValue") + generated_at: datetime = Field(serialization_alias="generatedAt") + + +@tool("aliased", "Return aliased, JSON-safe structured content") +def aliased() -> AliasedOutput: + return AliasedOutput( + result_value=7, + generated_at=datetime(2025, 1, 2, 3, 4, tzinfo=timezone.utc), + ) + + +@pytest.mark.asyncio +async def test_tool_validates_arguments_for_sync_and_async_handlers() -> None: + result = await add.handler({"a": 2, "b": 3}) + assert result.content == "5" + assert result.structured_content == {"result": 5} + assert await echo_async.handler({"text": "hello"}) == "hello" + + with pytest.raises(ValidationError): + await add.handler({"a": "not-an-integer", "b": 3}) + + assert typed_add.output_schema is not None + assert typed_add.output_schema["type"] == "object" + typed = await typed_add.handler({"a": 4, "b": 5}) + assert isinstance(typed, ToolResponse) + assert typed.structured_content == {"result": 9} + + +def test_tool_rejects_unsupported_return_schema() -> None: + with pytest.raises(TypeError, match="must describe an object"): + + @tool("bad", "Bad output") + def bad() -> list[str]: + return [] + + +@pytest.mark.asyncio +async def test_sdk_mcp_server_supports_official_client() -> None: + server = create_sdk_mcp_server("calculator", [add, typed_add, aliased]) + config = await server.start() + headers: Mapping[str, str] = { + header.name: header.value for header in config.headers + } + + try: + async with ( + httpx.AsyncClient(headers=headers) as http_client, + streamable_http_client( + config.url, + http_client=http_client, + ) as streams, + ClientSession(streams[0], streams[1]) as client, + ): + await client.initialize() + tools = await client.list_tools() + assert [item.name for item in tools.tools] == [ + "add", + "typed_add", + "aliased", + ] + output_schema = tools.tools[1].outputSchema + assert output_schema is not None + assert output_schema["type"] == "object" + assert output_schema["properties"]["result"]["type"] == "integer" + assert output_schema["required"] == ["result"] + + result = await client.call_tool("add", {"a": 2, "b": 3}) + assert result.isError is False + assert result.structuredContent == {"result": 5} + + typed_result = await client.call_tool( + "typed_add", + {"a": 4, "b": 5}, + ) + assert typed_result.structuredContent == {"result": 9} + + aliased_tool = tools.tools[2] + aliased_schema = aliased_tool.outputSchema + assert aliased_schema is not None + assert set(aliased_schema["properties"]) == { + "resultValue", + "generatedAt", + } + aliased_result = await client.call_tool("aliased", {}) + assert aliased_result.structuredContent == { + "resultValue": 7, + "generatedAt": "2025-01-02T03:04:00Z", + } + jsonschema.validate( + instance=aliased_result.structuredContent, + schema=aliased_schema, + ) + + invalid = await client.call_tool( + "add", + {"a": "invalid", "b": 3}, + ) + assert invalid.isError is True + finally: + await server.close() + + +@pytest.mark.asyncio +async def test_sdk_mcp_server_restarts_with_rotated_auth() -> None: + server = create_sdk_mcp_server("calculator", [add]) + first = await server.start() + await server.close() + second = await server.start() + try: + assert first.url != second.url + assert first.headers != second.headers + finally: + await server.close() + + +@pytest.mark.asyncio +async def test_sdk_mcp_concurrent_start_and_cancellation_share_runtime( + monkeypatch: pytest.MonkeyPatch, +) -> None: + server = create_sdk_mcp_server("calculator", [add]) + entered = asyncio.Event() + release = asyncio.Event() + calls = 0 + original = mcp_module._start_sdk_server_impl + + async def gated_start(server_value: object) -> object: + nonlocal calls + calls += 1 + entered.set() + await release.wait() + return await original(server_value) # type: ignore[arg-type] + + monkeypatch.setattr(mcp_module, "_start_sdk_server_impl", gated_start) + first = asyncio.create_task(server.start()) + await entered.wait() + second = asyncio.create_task(server.start()) + first.cancel() + with pytest.raises(asyncio.CancelledError): + await first + assert not second.done() + + release.set() + config = await second + try: + assert calls == 1 + assert server.config is config + runtime = server._runtime + assert runtime is not None + assert not runtime.task.done() # type: ignore[attr-defined] + assert runtime.listener.fileno() >= 0 # type: ignore[attr-defined] + finally: + await server.close() + + +@pytest.mark.asyncio +async def test_sdk_mcp_lone_cancelled_start_is_cleaned_and_retryable( + monkeypatch: pytest.MonkeyPatch, +) -> None: + server = create_sdk_mcp_server("calculator", [add]) + entered = asyncio.Event() + release = asyncio.Event() + original = mcp_module._start_sdk_server_impl + + async def gated_start(server_value: object) -> object: + entered.set() + await release.wait() + return await original(server_value) # type: ignore[arg-type] + + monkeypatch.setattr(mcp_module, "_start_sdk_server_impl", gated_start) + start = asyncio.create_task(server.start()) + await entered.wait() + start.cancel() + with pytest.raises(asyncio.CancelledError): + await start + + release.set() + await server.close() + assert server.config is None + lifecycle = server._lifecycle + assert lifecycle is not None + assert lifecycle.close_task.done() # type: ignore[attr-defined] + + restarted = await server.start() + try: + assert restarted.url + finally: + await server.close() + + +@pytest.mark.asyncio +async def test_sdk_mcp_cancelled_close_finishes_once_and_restarts( + monkeypatch: pytest.MonkeyPatch, +) -> None: + server = create_sdk_mcp_server("calculator", [add]) + await server.start() + runtime = server._runtime + assert runtime is not None + entered = asyncio.Event() + release = asyncio.Event() + calls = 0 + original = mcp_module._close_sdk_server_impl + + async def gated_close(server_value: object, runtime_value: object) -> None: + nonlocal calls + calls += 1 + entered.set() + await release.wait() + await original(server_value, runtime_value) # type: ignore[arg-type] + + monkeypatch.setattr(mcp_module, "_close_sdk_server_impl", gated_close) + first = asyncio.create_task(server.close()) + await entered.wait() + second = asyncio.create_task(server.close()) + first.cancel() + with pytest.raises(asyncio.CancelledError): + await first + assert not second.done() + + release.set() + await second + assert calls == 1 + assert server.config is None + assert runtime.task.done() # type: ignore[attr-defined] + assert runtime.listener.fileno() == -1 # type: ignore[attr-defined] + + restarted = await server.start() + try: + assert restarted.url + finally: + await server.close() diff --git a/tests/test_v5_public_models.py b/tests/test_v5_public_models.py new file mode 100644 index 0000000..85f2c93 --- /dev/null +++ b/tests/test_v5_public_models.py @@ -0,0 +1,913 @@ +from __future__ import annotations + +import base64 +import dataclasses +import os +import subprocess +import sys +from datetime import timedelta +from pathlib import Path +from types import MappingProxyType +from typing import Literal + +import pytest +from pydantic import BaseModel, RootModel, ValidationError + +import droid_sdk._high_level.attachments as attachment_module +from droid_sdk import ( + MAX_ATTACHMENT_BYTES, + ApplyPatchAction, + ApplyPatchFile, + AskUserAction, + AskUserParseError, + Autonomy, + Base64ImageSource, + ContextAccuracy, + CreateFile, + Document, + DocumentBlock, + DroidShieldViolationAction, + EditAction, + ErrorEvent, + ErrorType, + ExecuteAction, + ExitSpecModeAction, + HttpHeader, + Image, + ImageBlock, + InvalidAttachmentError, + JsonSchema, + McpConfigError, + McpOAuthOptions, + McpServerStatus, + McpServerStatusInfo, + McpServerType, + McpStatusChanged, + McpStatusSummary, + McpToolAction, + Mode, + PdfDocumentSource, + PermissionRequest, + ReasoningEffort, + RunFailure, + RunInterrupted, + RunResult, + RunSuccess, + Runtime, + SandboxOperation, + SandboxViolationAction, + SandboxViolationType, + SessionConfig, + SessionSettings, + SessionTag, + StdioMcpServerConfig, + StructuredOutputError, + TextBlock, + TextDocumentSource, + ToolCategory, + ToolConfirmationOutcome, + ToolConfirmationType, + ToolInfo, + ToolResult, + ToolResultBlock, + ToolUseBlock, +) +from droid_sdk._high_level.output import prepare_output_adapter +from droid_sdk.observability import ( + LogEvent, + MetricEvent, + Observability, + ObservabilityAdapter, + TraceContext, + emit_log, + inject_trace_context, + record_metric, + serialize_error, +) +from droid_sdk.protocol import ProtocolTiming + +PNG = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGNg" + "YAAAAAMAASsJTYQAAAAASUVORK5CYII=" +) +GIF = b"GIF89a" + (b"\0" * 20) +JPEG = b"\xff\xd8\xff\xe0" + (b"\0" * 20) +WEBP = b"RIFF\x04\x00\x00\x00WEBP" + + +@pytest.mark.parametrize( + ("data", "media_type"), + [ + (PNG, "image/png"), + (GIF, "image/gif"), + (JPEG, "image/jpeg"), + (WEBP, "image/webp"), + ], +) +def test_image_bytes_and_content_detection(data: bytes, media_type: str) -> None: + image = Image.from_bytes(data, media_type=media_type) # type: ignore[arg-type] + assert image.source.media_type == media_type + assert base64.b64decode(image.source.data) == data + + +def test_image_path_ignores_misleading_extension(tmp_path: Path) -> None: + path = tmp_path / "not-a-jpeg.jpg" + path.write_bytes(PNG) + assert Image.from_path(path).source.media_type == "image/png" + + +@pytest.mark.parametrize( + "factory", + [ + lambda path: Image.from_path(path), + lambda path: Document.from_path(path), + ], +) +def test_attachment_rejects_missing_and_directory( + tmp_path: Path, factory: object +) -> None: + call = factory # keep parametrization readable + with pytest.raises(InvalidAttachmentError): + call(tmp_path / "missing") # type: ignore[operator] + with pytest.raises(InvalidAttachmentError): + call(tmp_path) # type: ignore[operator] + + +def test_attachment_errors_do_not_include_bytes() -> None: + secret = b"private-file-content" + with pytest.raises(InvalidAttachmentError) as raised: + Image.from_bytes(secret, media_type="image/png") + assert secret.decode() not in str(raised.value) + + +def test_attachment_size_boundary_and_oversize( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(attachment_module, "MAX_ATTACHMENT_BYTES", len(PNG)) + + boundary = tmp_path / "boundary.png" + boundary.write_bytes(PNG) + assert Image.from_path(boundary).source.media_type == "image/png" + + oversized = tmp_path / "oversized.png" + oversized.write_bytes(PNG + b"private-file-content") + with pytest.raises(InvalidAttachmentError) as raised: + Image.from_path(oversized) + assert "exceeds" in str(raised.value) + assert "private-file-content" not in str(raised.value) + with pytest.raises(InvalidAttachmentError, match="exceeds"): + Image.from_bytes(PNG + b"x", media_type="image/png") + assert Document.from_text("x" * len(PNG)).source.data == "x" * len(PNG) + with pytest.raises(InvalidAttachmentError, match="exceeds"): + Document.from_text("x" * (len(PNG) + 1)) + + +def test_attachment_rejects_sparse_oversize_without_reading(tmp_path: Path) -> None: + sparse = tmp_path / "sparse.pdf" + with sparse.open("wb") as file: + file.truncate(MAX_ATTACHMENT_BYTES + 1) + with pytest.raises(InvalidAttachmentError, match="exceeds"): + Document.from_path(sparse) + + +def test_pdf_path_enforces_pdf_specific_size_boundary( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + boundary_bytes = b"%PDF-" + b"x" * 11 + monkeypatch.setattr( + attachment_module, "MAX_PDF_ATTACHMENT_BYTES", len(boundary_bytes) + ) + boundary = tmp_path / "boundary.pdf" + boundary.write_bytes(boundary_bytes) + document = Document.from_path(boundary) + assert isinstance(document.source, PdfDocumentSource) + assert base64.b64decode(document.source.data) == boundary_bytes + + oversized_bytes = boundary_bytes + b"x" + oversized = tmp_path / "oversized.pdf" + oversized.write_bytes(oversized_bytes) + with pytest.raises(InvalidAttachmentError) as from_path: + Document.from_path(oversized) + with pytest.raises(InvalidAttachmentError) as from_bytes: + Document.from_bytes(oversized_bytes) + assert str(from_path.value) == str(from_bytes.value) + assert str(from_path.value) == ( + f"PDF attachment exceeds the {len(boundary_bytes)}-byte limit" + ) + + +def test_attachment_rejects_file_changed_during_read( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + path = tmp_path / "changing.txt" + path.write_text("safe", encoding="utf-8") + original_open = Path.open + + class ChangingFile: + def __init__(self, file_path: Path) -> None: + self._path = file_path + self._file = original_open(file_path, "rb") + + def __enter__(self) -> ChangingFile: + return self + + def __exit__(self, *args: object) -> None: + self._file.close() + + def fileno(self) -> int: + return self._file.fileno() + + def read(self, size: int = -1) -> bytes: + data = self._file.read(size) + descriptor = os.open(self._path, os.O_WRONLY | os.O_APPEND) + try: + os.write(descriptor, b"x") + finally: + os.close(descriptor) + return data + + def changing_open( + file_path: Path, mode: str = "r", *args: object, **kwargs: object + ) -> ChangingFile: + assert mode == "rb" + return ChangingFile(file_path) + + monkeypatch.setattr(Path, "open", changing_open) + with pytest.raises(InvalidAttachmentError, match="changed while"): + Document.from_path(path) + + +def test_attachment_rejects_file_replaced_between_stat_and_open( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + path = tmp_path / "replaced.txt" + replacement = tmp_path / "replacement.txt" + path.write_text("original", encoding="utf-8") + replacement.write_text("replacement", encoding="utf-8") + original_open = Path.open + replaced = False + + def replacing_open( + file_path: Path, mode: str = "r", *args: object, **kwargs: object + ) -> object: + nonlocal replaced + if file_path == path and not replaced: + replaced = True + os.replace(replacement, path) + return original_open(file_path, mode, *args, **kwargs) + + monkeypatch.setattr(Path, "open", replacing_open) + with pytest.raises(InvalidAttachmentError, match="changed before"): + Document.from_path(path) + + +def test_image_direct_source_validates_base64_and_signature() -> None: + with pytest.raises(InvalidAttachmentError): + Base64ImageSource(data="not base64", media_type="image/png") + with pytest.raises(InvalidAttachmentError): + Image.from_bytes(PNG, media_type="image/jpeg") + + +def test_document_text_pdf_and_encoding(tmp_path: Path) -> None: + text_path = tmp_path / "hello.md" + text_path.write_text("hello", encoding="utf-8") + text = Document.from_path(text_path) + assert text.source == TextDocumentSource( + data="hello", name="hello.md", mime="text/plain" + ) + + pdf_path = tmp_path / "report.pdf" + pdf_bytes = b"%PDF-1.7\n%%EOF\n" + pdf_path.write_bytes(pdf_bytes) + pdf = Document.from_path(pdf_path) + assert isinstance(pdf.source, PdfDocumentSource) + assert base64.b64decode(pdf.source.data) == pdf_bytes + assert pdf.source.name == "report.pdf" + assert pdf.source.path == str(pdf_path) + + bad_path = tmp_path / "binary.bin" + bad_path.write_bytes(b"\xff\xfe") + with pytest.raises(InvalidAttachmentError): + Document.from_path(bad_path) + with pytest.raises(InvalidAttachmentError): + Document.from_bytes(b"not pdf") + + +def test_configuration_is_recursively_immutable() -> None: + metadata = {"owner": "sdk"} + tags = [SessionTag("test", metadata)] + disabled = {"Execute"} + config = SessionConfig( + mode=Mode.SPEC, + autonomy=Autonomy.LOW, + spec_reasoning_effort=ReasoningEffort.HIGH, + tags=tags, + disabled_tools=disabled, + ) + tags.clear() + metadata["owner"] = "changed" + disabled.add("Edit") + assert config.tags[0].metadata == {"owner": "sdk"} + assert config.disabled_tools == frozenset({"Execute"}) + assert isinstance(config.tags[0].metadata, MappingProxyType) + with pytest.raises(dataclasses.FrozenInstanceError): + config.mode = Mode.AUTO # type: ignore[misc] + + +def test_json_schema_is_recursive_and_rejects_non_json() -> None: + schema = {"type": "object", "required": ["name"]} + value = JsonSchema(schema) + schema["type"] = "array" + assert value.schema["type"] == "object" + assert value.schema["required"] == ("name",) + with pytest.raises(TypeError): + value.schema["type"] = "array" # type: ignore[index] + required = value.schema["required"] + assert isinstance(required, tuple) + with pytest.raises(TypeError): + required[0] = "changed" # type: ignore[index] + with pytest.raises(TypeError): + JsonSchema({"bad": object()}) + + +class Review(BaseModel): + severity: Literal["low", "high"] + count: int + + +class ReviewList(RootModel[list[Review]]): + pass + + +def test_pydantic_output_adapter_schema_success_and_failure() -> None: + adapter = prepare_output_adapter(Review) + wire = adapter.output_format + assert wire is not None + assert wire.type == "json_schema" + assert wire.schema_["type"] == "object" + + success = adapter.adapt({"severity": "high", "count": 2}) + assert success.output == Review(severity="high", count=2) + assert success.structured_output == {"severity": "high", "count": 2} + assert success.validation_error is None + + failure = adapter.adapt({"severity": "unknown", "count": 2}) + assert failure.output is None + assert failure.structured_output == {"severity": "unknown", "count": 2} + assert isinstance(failure.validation_error, ValidationError) + + missing = adapter.adapt(None) + assert missing.output is None + assert isinstance(missing.validation_error, ValidationError) + + +def test_json_schema_output_adapter_and_bad_output_argument() -> None: + adapter = prepare_output_adapter(JsonSchema({"type": "object"})) + adapted = adapter.adapt({"summary": "ok"}) + assert adapted.output == {"summary": "ok"} + assert adapted.structured_output == {"summary": "ok"} + assert adapted.output is not adapted.structured_output + adapted.output["summary"] = "changed" + assert adapted.structured_output == {"summary": "ok"} + with pytest.raises(TypeError): + adapter.adapt(["not", "an", "object"]) + with pytest.raises(TypeError): + prepare_output_adapter(str) + + +@pytest.mark.parametrize( + "schema", + [ + {"type": "array", "items": {"type": "string"}}, + {"type": "string"}, + {"properties": {"summary": {"type": "string"}}}, + ], +) +def test_output_adapter_rejects_non_object_json_schemas( + schema: dict[str, object], +) -> None: + with pytest.raises(TypeError, match="top-level object"): + prepare_output_adapter(JsonSchema(schema)) + + +def test_output_adapter_rejects_pydantic_root_list_model() -> None: + with pytest.raises(TypeError, match="top-level object"): + prepare_output_adapter(ReviewList) + + +def test_no_output_adapter_returns_empty_adaptation() -> None: + adapted = prepare_output_adapter().adapt({"ignored": True}) + assert adapted.output is None + assert adapted.structured_output is None + assert adapted.validation_error is None + + +def test_tool_result_block_content_matches_protocol_blocks() -> None: + json_content = {"nested": ["value"]} + blocks = [ + TextBlock(text="done"), + ImageBlock( + source=Base64ImageSource( + data=base64.b64encode(PNG).decode(), media_type="image/png" + ) + ), + DocumentBlock(source=TextDocumentSource(data="details")), + json_content, + ["nested", {"ok": True}], + 3, + False, + None, + ] + result = ToolResultBlock(tool_use_id="tool-1", content=blocks) + blocks.clear() + json_content["nested"].append("changed") + assert isinstance(result.content, tuple) + assert [type(item) for item in result.content[:3]] == [ + TextBlock, + ImageBlock, + DocumentBlock, + ] + assert result.content[3:] == ( + {"nested": ("value",)}, + ("nested", {"ok": True}), + 3, + False, + None, + ) + assert isinstance(result.content[3], MappingProxyType) + + text = ToolResultBlock(tool_use_id="tool-2", content="plain") + assert text.content == "plain" + + with pytest.raises(TypeError): + ToolResultBlock(tool_use_id="tool-3", content=[object()]) # type: ignore[list-item] + with pytest.raises(ValueError): + ToolResultBlock(tool_use_id="tool-4", content=[float("nan")]) + + +def test_stream_tool_result_json_content_is_recursively_immutable() -> None: + content = [{"nested": ["value"]}] + result = ToolResult( + tool_use_id="tool-1", + tool_name="Read", + content=content, + is_error=False, + ) + content[0]["nested"].append("changed") + assert result.content == ({"nested": ("value",)},) + assert isinstance(result.content[0], MappingProxyType) + + +def test_mcp_status_changed_uses_concrete_status_models() -> None: + servers = [ + McpServerStatusInfo( + name="local", + status=McpServerStatus.CONNECTED, + source="project", + is_managed=False, + server_type=McpServerType.STDIO, + ) + ] + summary = McpStatusSummary( + total=1, + connected=1, + connecting=0, + failed=0, + config_error=McpConfigError(path="/repo/.factory/mcp.json", message="bad"), + ) + changed = McpStatusChanged(servers=servers, summary=summary) + servers.clear() + assert changed.servers[0].name == "local" + assert changed.summary is summary + with pytest.raises(dataclasses.FrozenInstanceError): + changed.servers[0].name = "changed" # type: ignore[misc] + with pytest.raises(dataclasses.FrozenInstanceError): + changed.summary.config_error.message = "changed" # type: ignore[union-attr,misc] + + +def test_permission_actions_preserve_details_defaults_and_plan() -> None: + tool_use = ToolUseBlock(id="tool-1", name="ApplyPatch", input={}) + patch_file = ApplyPatchFile( + file_path="/repo/a.py", + file_name="a.py", + operation="update", + old_content="old", + new_content="new", + ) + patch = ApplyPatchAction( + tool_use=tool_use, + file_path="/repo/a.py", + file_name="a.py", + patch_content="*** Begin Patch", + old_content="old", + new_content="new", + files=[patch_file], + ) + assert patch.files == (patch_file,) + + ask = AskUserAction( + tool_use=tool_use, + questionnaire="invalid questionnaire", + questions=[], + parse_error=AskUserParseError(message="invalid JSON", line=3), + ) + assert ask.parse_error == AskUserParseError(message="invalid JSON", line=3) + + mcp = McpToolAction( + tool_use=tool_use, + tool_name="search", + impact_level="low", + ) + assert mcp.server_name is None + assert mcp.actual_tool_name is None + + sandbox = SandboxViolationAction( + tool_use=tool_use, + violating_tool_name="Execute", + target="/outside", + operation=SandboxOperation.WRITE, + violation_type=SandboxViolationType.FILESYSTEM_WRITE, + reason="outside sandbox", + is_org_deny=False, + ) + assert sandbox.violation_reason is None + + request = PermissionRequest( + actions=[ + ExitSpecModeAction( + tool_use=tool_use, + plan="Implement the change.", + title="Implementation", + ) + ], + options=[], + ) + assert request.plan is not None + assert request.plan.text == "Implement the change." + assert request.plan.title == "Implementation" + + +def test_every_permission_action_variant_fields_and_defaults() -> None: + tool_use = ToolUseBlock(id="tool-1", name="tool", input={}) + + edit = EditAction(tool_use=tool_use, file_path="/repo/a.py", file_name="a.py") + assert edit.old_content is None + assert edit.new_content is None + assert edit.confirmation_type is ToolConfirmationType.EDIT + + commands = ["git", "status"] + execute = ExecuteAction( + tool_use=tool_use, + full_command="git status", + command="git", + extracted_commands=commands, + ) + commands.clear() + assert execute.extracted_commands == ("git", "status") + assert execute.impact_level is None + assert execute.risk_level_reason is None + + create = CreateFile( + tool_use=tool_use, + file_path="/repo/new.py", + file_name="new.py", + content="pass\n", + ) + assert create.confirmation_type is ToolConfirmationType.CREATE + + ask = AskUserAction(tool_use=tool_use, questionnaire="questionnaire") + assert ask.questions == () + assert ask.parse_error is None + + exit_spec = ExitSpecModeAction(tool_use=tool_use, plan="Implement") + assert exit_spec.title is None + + patch = ApplyPatchAction( + tool_use=tool_use, + file_path="/repo/a.py", + file_name="a.py", + patch_content="patch", + ) + assert patch.old_content is None + assert patch.new_content is None + assert patch.files is None + + mcp = McpToolAction( + tool_use=tool_use, + tool_name="search", + impact_level="low", + ) + assert mcp.server_name is None + assert mcp.actual_tool_name is None + + sandbox = SandboxViolationAction( + tool_use=tool_use, + violating_tool_name="Execute", + target="/outside", + operation=SandboxOperation.WRITE, + violation_type=SandboxViolationType.FILESYSTEM_WRITE, + reason="outside sandbox", + is_org_deny=False, + ) + assert sandbox.violation_reason is None + + shield = DroidShieldViolationAction( + tool_use=tool_use, + command="unsafe", + reason="blocked", + ) + assert shield.confirmation_type is ToolConfirmationType.DROID_SHIELD_VIOLATION + + +def test_tool_info_is_complete_and_immutable() -> None: + tool = ToolInfo( + id="Read", + display_name="Read", + description="Read a file", + category=ToolCategory.READ, + default_allowed=True, + allowed=False, + ) + assert tool.category is ToolCategory.READ + assert tool.default_allowed + assert not tool.allowed + with pytest.raises(dataclasses.FrozenInstanceError): + tool.allowed = True # type: ignore[misc] + with pytest.raises(TypeError): + ToolInfo(id="Read") # type: ignore[call-arg] + + +def test_session_settings_require_model_and_reasoning_effort() -> None: + settings = SessionSettings( + model="claude-sonnet", + reasoning_effort=ReasoningEffort.HIGH, + disabled_tools={"Execute"}, + ) + assert settings.model == "claude-sonnet" + assert settings.reasoning_effort is ReasoningEffort.HIGH + assert settings.disabled_tools == frozenset({"Execute"}) + with pytest.raises(TypeError): + SessionSettings() # type: ignore[call-arg] + + +def test_structured_output_error_details_are_immutable() -> None: + details = {"issues": [{"path": ["summary"]}]} + error = StructuredOutputError( + code="invalid_output", + message="Output did not match schema", + details=details, + ) + details["issues"][0]["path"].append("changed") + assert error.details == {"issues": ({"path": ("summary",)},)} + assert isinstance(error.details, MappingProxyType) + with pytest.raises(TypeError): + StructuredOutputError("invalid_output", "bad", details=object()) # type: ignore[arg-type] + with pytest.raises(ValueError): + StructuredOutputError("invalid_output", "bad", details=float("inf")) + + +def _terminal_kwargs() -> dict[str, object]: + return { + "text": "done", + "messages": [], + "usage": None, + "duration": timedelta(seconds=1), + "turn_count": 1, + "session_id": "session-1", + } + + +def test_terminal_result_invariants() -> None: + success = RunSuccess(**_terminal_kwargs()) # type: ignore[arg-type] + interrupted = RunInterrupted(**_terminal_kwargs()) # type: ignore[arg-type] + assert success.subtype == "success" + assert success.success and not success.interrupted + assert success.error is None + assert success.structured_output_error is None + assert interrupted.subtype == "interrupted" + assert not interrupted.success and interrupted.interrupted + + terminal_error = ErrorEvent(message="failed", error_type=ErrorType.ERROR) + failure = RunFailure( + subtype="error_during_execution", + error=terminal_error, + **_terminal_kwargs(), # type: ignore[arg-type] + ) + assert failure.error is terminal_error + assert not failure.success and not failure.interrupted + + with pytest.raises(TypeError): + RunSuccess( # type: ignore[call-arg] + error=terminal_error, + **_terminal_kwargs(), + ) + with pytest.raises(TypeError): + RunInterrupted( # type: ignore[call-arg] + structured_output_error=StructuredOutputError("invalid", "bad"), + **_terminal_kwargs(), + ) + with pytest.raises(ValueError): + RunFailure( # type: ignore[arg-type] + subtype="success", + **_terminal_kwargs(), + ) + + +def test_run_result_is_a_runtime_generic_base() -> None: + results = ( + RunSuccess(**_terminal_kwargs()), # type: ignore[arg-type] + RunInterrupted(**_terminal_kwargs()), # type: ignore[arg-type] + RunFailure( + subtype="error_during_execution", + **_terminal_kwargs(), # type: ignore[arg-type] + ), + ) + assert all(isinstance(result, RunResult) for result in results) + assert not isinstance(TextBlock(text="not terminal"), RunResult) + with pytest.raises(dataclasses.FrozenInstanceError): + results[0].text = "changed" # type: ignore[misc] + with pytest.raises(TypeError): + RunResult() + + +class CollectingSink: + def __init__(self) -> None: + self.logs: list[LogEvent] = [] + self.metrics: list[MetricEvent] = [] + + def log(self, event: LogEvent) -> None: + self.logs.append(event) + + def record(self, event: MetricEvent) -> None: + self.metrics.append(event) + + def inject(self, carrier: TraceContext) -> None: + carrier.traceparent = "trace" + carrier.tracestate = "state" + + +class BrokenSink: + def log(self, event: LogEvent) -> None: + raise RuntimeError + + def record(self, event: MetricEvent) -> None: + raise RuntimeError + + def inject(self, carrier: TraceContext) -> None: + carrier.traceparent = "partial" + raise RuntimeError + + +def test_observability_shape_isolation_and_protocol_adapter() -> None: + sink = CollectingSink() + observability = Observability(logger=sink, metrics=sink, tracing=sink) + attributes = {"safe": 1, "nested": {"secret": "removed"}} + event = LogEvent( + level="info", + name="droid.sdk.test", + message="safe", + attributes=attributes, + ) + attributes["safe"] = 2 + assert event.attributes == {"safe": 1} + assert emit_log(observability, event) + assert record_metric( + observability, + MetricEvent( + name="count", kind="counter", value=1, unit="1", attributes={"ok": True} + ), + ) + carrier = TraceContext() + assert inject_trace_context(observability, carrier) + assert carrier.traceparent == "trace" + + broken = Observability( + logger=BrokenSink(), metrics=BrokenSink(), tracing=BrokenSink() + ) + assert not emit_log(broken, event) + assert not record_metric( + broken, MetricEvent(name="count", kind="counter", value=1, unit="1") + ) + broken_carrier = TraceContext() + assert not inject_trace_context(broken, broken_carrier) + assert broken_carrier.traceparent is None + + adapter = ObservabilityAdapter(observability) + metadata: dict[str, str] = {"existing": "value"} + adapter.trace_meta_injector(metadata) + adapter.timing_callback(ProtocolTiming("method", 0.5, "success")) + assert metadata == { + "existing": "value", + "traceparent": "trace", + "tracestate": "state", + } + assert sink.metrics[-1].attributes == { + "method": "method", + "outcome": "success", + } + + +def test_runtime_normalization_and_transport_precedence() -> None: + class Transport: + is_connected = True + + async def connect(self) -> None: ... + + async def send(self, message: str) -> None: ... + + def read_messages(self) -> object: + raise NotImplementedError + + async def close(self) -> None: ... + + env = {"KEY": "value"} + runtime = Runtime( + executable="droid", + args=["--flag"], + env=env, + transport=Transport(), # type: ignore[arg-type] + ) + env["KEY"] = "changed" + assert runtime.executable == Path("droid") + assert runtime.args == ("--flag",) + assert runtime.env == {"KEY": "value"} + assert runtime.uses_supplied_transport + + +def test_environment_secrets_are_redacted_from_diagnostics() -> None: + api_key = "sentinel-api-key-do-not-log" + token = "sentinel-token-do-not-log" + header_secret = "sentinel-header-do-not-log" + oauth_secret = "sentinel-oauth-do-not-log" + runtime = Runtime(env={"FACTORY_API_KEY": api_key}) + server = StdioMcpServerConfig( + name="local", + command="server", + env={"ACCESS_TOKEN": token}, + ) + header = HttpHeader(name="Authorization", value=header_secret) + oauth = McpOAuthOptions(client_id="client", client_secret=oauth_secret) + + assert runtime.env["FACTORY_API_KEY"] == api_key + assert server.env["ACCESS_TOKEN"] == token + assert tuple(runtime.env) == ("FACTORY_API_KEY",) + assert tuple(server.env) == ("ACCESS_TOKEN",) + with pytest.raises(TypeError): + runtime.env["FACTORY_API_KEY"] = "changed" # type: ignore[index] + with pytest.raises(TypeError): + server.env["ACCESS_TOKEN"] = "changed" # type: ignore[index] + + diagnostic_values = ( + repr(runtime), + str(runtime), + repr(server), + str(server), + repr(RuntimeError(repr(runtime))), + repr(RuntimeError(repr(server))), + repr(serialize_error(RuntimeError(repr(runtime)))), + repr(header), + repr(oauth), + repr( + LogEvent( + level="error", + name="droid.sdk.test", + message="configuration failed", + attributes={"runtime": repr(runtime), "server": repr(server)}, + ) + ), + ) + assert all(api_key not in value for value in diagnostic_values) + assert all(token not in value for value in diagnostic_values) + assert all(header_secret not in value for value in diagnostic_values) + assert all(oauth_secret not in value for value in diagnostic_values) + assert "" in repr(runtime) + assert "" in repr(server) + + +def test_public_enum_values() -> None: + assert Mode.AUTO.value == "auto" + assert ContextAccuracy.ESTIMATED.value == "estimated" + assert ToolConfirmationOutcome.PROCEED_ALWAYS_EXACT_PATH.value == ( + "proceed_always_file" + ) + + +@pytest.mark.parametrize( + "example", + [ + "attachments.py", + "observability.py", + "structured_output_model.py", + ], +) +def test_offline_examples_execute(example: str) -> None: + root = Path(__file__).parents[1] + completed = subprocess.run( + [sys.executable, str(root / "examples" / example)], + check=False, + capture_output=True, + text=True, + timeout=30, + ) + assert completed.returncode == 0, completed.stderr + assert completed.stdout diff --git a/tests/test_v5_session.py b/tests/test_v5_session.py new file mode 100644 index 0000000..73041b6 --- /dev/null +++ b/tests/test_v5_session.py @@ -0,0 +1,1053 @@ +from __future__ import annotations + +import asyncio +import time +from types import SimpleNamespace +from typing import TYPE_CHECKING, Any, ClassVar, cast + +import pytest + +import droid_sdk._high_level.session as session_module +from droid_sdk import ( + Document, + DroidConnectionError, + ErrorEvent, + ErrorType, + HttpHeader, + HttpMcpServerConfig, + InteractionHandlers, + McpOAuthOptions, + Mode, + ReasoningEffort, + Runtime, + RunTimeoutError, + Session, + SessionBusyError, + SessionClosedError, + SessionConfig, + SessionNotOpenError, + SessionReplacedError, + SessionReplacementError, + TextDocumentSource, +) +from droid_sdk._high_level.interaction_adapter import InteractionDispatcher +from droid_sdk.mcp import create_sdk_mcp_server +from droid_sdk.observability import LogEvent, MetricEvent, Observability +from droid_sdk.schemas.enums import ( + ReasoningEffort as WireReasoningEffort, +) + +if TYPE_CHECKING: + from collections.abc import Callable + + from droid_sdk.types import DroidClientTransport + + +def wire_settings() -> SimpleNamespace: + return SimpleNamespace( + model_id="model", + reasoning_effort=WireReasoningEffort.Medium, + interaction_mode=None, + autonomy_level=None, + spec_mode_model_id="spec-model", + spec_mode_reasoning_effort=WireReasoningEffort.High, + tags=[], + sandbox=None, + additional_tool_ids=None, + enabled_tool_ids=None, + disabled_tool_ids=None, + restrict_tool_ids=None, + ) + + +class FakeTransport: + is_connected = True + + +class FakeClient: + instances: ClassVar[list[FakeClient]] = [] + fail_connect: ClassVar[bool] = False + fail_replacement_load: ClassVar[bool] = False + fail_fork: ClassVar[bool] = False + connect_entered: ClassVar[asyncio.Event | None] = None + connect_gate: ClassVar[asyncio.Event | None] = None + initialize_entered: ClassVar[asyncio.Event | None] = None + initialize_gate: ClassVar[asyncio.Event | None] = None + remote_session_created: ClassVar[asyncio.Event | None] = None + remote_session_gate: ClassVar[asyncio.Event | None] = None + replacement_gate: ClassVar[asyncio.Event | None] = None + replacement_entered: ClassVar[asyncio.Event | None] = None + send_gate: ClassVar[asyncio.Event | None] = None + close_entered: ClassVar[asyncio.Event | None] = None + close_gate: ClassVar[asyncio.Event | None] = None + close_session_error: ClassVar[Exception | None] = None + fail_send: ClassVar[bool] = False + hang_interrupt: ClassVar[bool] = False + + def __init__(self, **kwargs: object) -> None: + self.kwargs = kwargs + self.initialize_calls: list[dict[str, Any]] = [] + self.update_calls: list[dict[str, Any]] = [] + self.load_calls: list[dict[str, Any]] = [] + self.message_calls: list[dict[str, Any]] = [] + self.mcp_calls: list[dict[str, Any]] = [] + self.callbacks: list[Callable[[dict[str, Any]], None]] = [] + self.error_callbacks: list[Callable[[Exception], None]] = [] + self.dispatcher: InteractionDispatcher | None = None + self.interrupt_calls = 0 + self.close_calls = 0 + self.close_session_calls = 0 + type(self).instances.append(self) + + async def connect(self) -> None: + if self.connect_entered is not None: + self.connect_entered.set() + if self.connect_gate is not None: + await self.connect_gate.wait() + if self.fail_connect: + raise FileNotFoundError("missing") + + async def initialize_session(self, **kwargs: Any) -> SimpleNamespace: + self.initialize_calls.append(kwargs) + if self.initialize_entered is not None: + self.initialize_entered.set() + if self.initialize_gate is not None: + await self.initialize_gate.wait() + if self.remote_session_created is not None: + self.remote_session_created.set() + if self.remote_session_gate is not None: + await self.remote_session_gate.wait() + return SimpleNamespace(session_id="session-1", settings=wire_settings()) + + async def update_session_settings(self, **kwargs: Any) -> None: + self.update_calls.append(kwargs) + + def set_interaction_handlers( + self, + handlers: object, + *, + error_sink: object | None = None, + ) -> None: + self.dispatcher = InteractionDispatcher( + cast("InteractionHandlers", handlers), + error_sink=cast("Any", error_sink), + ) + + def on_error( + self, + callback: Callable[[Exception], None], + ) -> Callable[[], None]: + self.error_callbacks.append(callback) + + def unsubscribe() -> None: + self.error_callbacks.remove(callback) + + return unsubscribe + + async def add_user_message(self, **kwargs: Any) -> None: + self.message_calls.append(kwargs) + if self.fail_send: + raise RuntimeError("send failed") + if self.send_gate is not None: + await self.send_gate.wait() + + async def interrupt_session(self) -> None: + self.interrupt_calls += 1 + if self.hang_interrupt: + await asyncio.Event().wait() + + async def rename_session(self, *, title: str) -> None: + assert title + + async def add_mcp_server(self, **kwargs: Any) -> SimpleNamespace: + self.mcp_calls.append(kwargs) + return SimpleNamespace(success=True) + + async def fork_session(self, **kwargs: Any) -> SimpleNamespace: + return await self._replacement_result() + + async def compact_session(self, **kwargs: Any) -> SimpleNamespace: + result = await self._replacement_result() + result.removed_count = 3 + return result + + async def execute_rewind(self, **kwargs: Any) -> SimpleNamespace: + result = await self._replacement_result() + result.restored_count = 1 + result.deleted_count = 2 + result.failed_restore_count = 0 + result.failed_delete_count = 0 + return result + + async def _replacement_result(self) -> SimpleNamespace: + if self.replacement_entered is not None: + self.replacement_entered.set() + if self.replacement_gate is not None: + await self.replacement_gate.wait() + if self.fail_fork: + raise RuntimeError("fork failed") + return SimpleNamespace(new_session_id="session-2") + + async def load_session(self, **kwargs: Any) -> SimpleNamespace: + self.load_calls.append(kwargs) + if self.fail_replacement_load and kwargs["session_id"] == "session-2": + raise RuntimeError("replacement unavailable") + return SimpleNamespace( + settings=wire_settings(), + model_extra={}, + ) + + def on_notification( + self, + callback: Callable[[dict[str, Any]], None], + ) -> Callable[[], None]: + self.callbacks.append(callback) + + def unsubscribe() -> None: + self.callbacks.remove(callback) + + return unsubscribe + + async def close_session(self, *, reason: str) -> None: + assert reason == "other" + self.close_session_calls += 1 + if self.close_session_error is not None: + raise self.close_session_error + + async def close(self) -> None: + self.close_calls += 1 + if self.close_entered is not None: + self.close_entered.set() + if self.close_gate is not None: + await self.close_gate.wait() + + +@pytest.fixture(autouse=True) +def fake_client(monkeypatch: pytest.MonkeyPatch) -> None: + FakeClient.instances.clear() + FakeClient.fail_connect = False + FakeClient.fail_replacement_load = False + FakeClient.fail_fork = False + FakeClient.connect_entered = None + FakeClient.connect_gate = None + FakeClient.initialize_entered = None + FakeClient.initialize_gate = None + FakeClient.remote_session_created = None + FakeClient.remote_session_gate = None + FakeClient.replacement_gate = None + FakeClient.replacement_entered = None + FakeClient.send_gate = None + FakeClient.close_entered = None + FakeClient.close_gate = None + FakeClient.close_session_error = None + FakeClient.fail_send = False + FakeClient.hang_interrupt = False + monkeypatch.setattr(session_module, "DroidClient", FakeClient) + + +def runtime() -> Runtime: + return Runtime(transport=cast("DroidClientTransport", FakeTransport())) + + +class ObservabilitySink: + def __init__(self) -> None: + self.logs: list[LogEvent] = [] + self.metrics: list[MetricEvent] = [] + + def log(self, event: LogEvent) -> None: + self.logs.append(event) + + def record(self, event: MetricEvent) -> None: + self.metrics.append(event) + + +@pytest.mark.asyncio +async def test_session_is_lazy_and_context_manager_owns_cleanup() -> None: + session = Session(runtime=runtime()) + with pytest.raises(SessionNotOpenError): + _ = session.id + + async with session: + assert session.id == "session-1" + assert session.settings.model == "model" + await session.open() + + client = FakeClient.instances[0] + assert len(client.initialize_calls) == 1 + assert client.close_session_calls == 1 + assert client.close_calls == 1 + with pytest.raises(SessionClosedError): + await session.rename("closed") + + +@pytest.mark.asyncio +async def test_session_updates_and_merges_settings_notifications() -> None: + session = Session(runtime=runtime()) + await session.open() + client = FakeClient.instances[0] + + await session.update_settings( + mode=Mode.SPEC, + spec_model=None, + spec_reasoning_effort=None, + ) + + update = client.update_calls[-1] + assert update["explicit_null_fields"] == [ + "specModeModelId", + "specModeReasoningEffort", + ] + assert session.settings.spec_model is None + assert session.settings.spec_reasoning_effort is None + + client.callbacks[0]( + { + "params": { + "notification": { + "type": "settings_updated", + "settings": { + "modelId": "new-model", + "reasoningEffort": "high", + }, + } + } + } + ) + assert session.settings.model == "new-model" + assert session.settings.reasoning_effort is ReasoningEffort.HIGH + await session.close() + + +@pytest.mark.asyncio +async def test_session_maps_missing_executable_and_cleans_up() -> None: + FakeClient.fail_connect = True + session = Session(runtime=runtime()) + + with pytest.raises(DroidConnectionError, match="executable was not found"): + await session.open() + + assert FakeClient.instances[0].close_calls == 1 + + +@pytest.mark.asyncio +async def test_concurrent_open_and_close_share_lifecycle_tasks() -> None: + FakeClient.connect_entered = asyncio.Event() + FakeClient.connect_gate = asyncio.Event() + session = Session(runtime=runtime()) + + first_open = asyncio.create_task(session.open()) + await FakeClient.connect_entered.wait() + second_open = asyncio.create_task(session.open()) + close = asyncio.create_task(session.close()) + first_open.cancel() + with pytest.raises(asyncio.CancelledError): + await first_open + + assert len(FakeClient.instances) == 1 + assert not second_open.done() + assert not close.done() + FakeClient.connect_gate.set() + await second_open + await close + + client = FakeClient.instances[0] + assert len(client.initialize_calls) == 1 + assert client.close_session_calls == 1 + assert client.close_calls == 1 + with pytest.raises(SessionClosedError): + await session.open() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("stage", "expects_close_session"), + [ + ("connect", False), + ("initialize", True), + ("remote-created", True), + ], +) +async def test_final_cancelled_open_cleans_resources_and_is_retryable( + stage: str, + expects_close_session: bool, +) -> None: + entered = asyncio.Event() + gate = asyncio.Event() + if stage == "connect": + FakeClient.connect_entered = entered + FakeClient.connect_gate = gate + elif stage == "initialize": + FakeClient.initialize_entered = entered + FakeClient.initialize_gate = gate + else: + FakeClient.remote_session_created = entered + FakeClient.remote_session_gate = gate + + session = Session(runtime=runtime()) + opening = asyncio.create_task(session.open()) + await entered.wait() + opening.cancel() + with pytest.raises(asyncio.CancelledError): + await opening + + client = FakeClient.instances[0] + assert client.close_calls == 1 + assert client.close_session_calls == int(expects_close_session) + assert session._state is session_module._State.LAZY + + FakeClient.connect_gate = None + FakeClient.initialize_gate = None + FakeClient.remote_session_gate = None + await session.open() + await session.close() + + +@pytest.mark.asyncio +async def test_cancelled_open_before_client_construction_closes_sdk_server( + monkeypatch: pytest.MonkeyPatch, +) -> None: + server = create_sdk_mcp_server("gated", []) + entered = asyncio.Event() + gate = asyncio.Event() + close_calls = 0 + + async def gated_start(_server: object) -> HttpMcpServerConfig: + entered.set() + await gate.wait() + return HttpMcpServerConfig(name="gated", url="http://127.0.0.1:1/mcp") + + async def tracked_close(_server: object) -> None: + nonlocal close_calls + close_calls += 1 + + monkeypatch.setattr(type(server), "start", gated_start) + monkeypatch.setattr(type(server), "close", tracked_close) + session = Session( + runtime=runtime(), + config=SessionConfig(mcp_servers=[server]), + ) + opening = asyncio.create_task(session.open()) + await entered.wait() + opening.cancel() + with pytest.raises(asyncio.CancelledError): + await opening + + assert FakeClient.instances == [] + assert close_calls == 1 + assert session._state is session_module._State.LAZY + gate.set() + await session.open() + await session.close() + assert len(FakeClient.instances) == 1 + + +@pytest.mark.asyncio +async def test_final_cancelled_open_after_assignment_closes_and_resets( + monkeypatch: pytest.MonkeyPatch, +) -> None: + entered = asyncio.Event() + gate = asyncio.Event() + original = Session._open_impl + + async def gated_open(session: Session) -> None: + await original(session) + entered.set() + await gate.wait() + + monkeypatch.setattr(Session, "_open_impl", gated_open) + session = Session(runtime=runtime()) + opening = asyncio.create_task(session.open()) + await entered.wait() + opening.cancel() + with pytest.raises(asyncio.CancelledError): + await opening + + client = FakeClient.instances[0] + assert client.close_session_calls == 1 + assert client.close_calls == 1 + assert session._state is session_module._State.LAZY + + +@pytest.mark.asyncio +async def test_repeated_open_cancellation_cannot_abort_startup_cleanup() -> None: + FakeClient.connect_entered = asyncio.Event() + FakeClient.connect_gate = asyncio.Event() + FakeClient.close_entered = asyncio.Event() + FakeClient.close_gate = asyncio.Event() + session = Session(runtime=runtime()) + opening = asyncio.create_task(session.open()) + await FakeClient.connect_entered.wait() + + opening.cancel() + await FakeClient.close_entered.wait() + cleanup = session._open_cleanup_task + assert cleanup is not None + assert not cleanup.done() + + opening.cancel() + with pytest.raises(asyncio.CancelledError): + await opening + assert not cleanup.done() + assert session._state is not session_module._State.LAZY + + FakeClient.close_gate.set() + await cleanup + client = FakeClient.instances[0] + assert client.close_calls == 1 + assert session._state is session_module._State.LAZY + + FakeClient.connect_gate = None + FakeClient.close_gate = None + await session.open() + await session.close() + + +@pytest.mark.asyncio +async def test_cancelled_open_racing_close_finishes_closed() -> None: + FakeClient.connect_entered = asyncio.Event() + FakeClient.connect_gate = asyncio.Event() + session = Session(runtime=runtime()) + opening = asyncio.create_task(session.open()) + await FakeClient.connect_entered.wait() + closing = asyncio.create_task(session.close()) + opening.cancel() + + with pytest.raises(asyncio.CancelledError): + await opening + await closing + client = FakeClient.instances[0] + assert client.close_calls == 1 + assert session._state is session_module._State.CLOSED + with pytest.raises(SessionClosedError): + await session.open() + + +@pytest.mark.asyncio +async def test_cancelled_and_repeated_close_awaits_one_cleanup() -> None: + session = Session(runtime=runtime()) + await session.open() + FakeClient.close_entered = asyncio.Event() + FakeClient.close_gate = asyncio.Event() + + first_close = asyncio.create_task(session.close()) + await FakeClient.close_entered.wait() + first_close.cancel() + with pytest.raises(asyncio.CancelledError): + await first_close + + second_close = asyncio.create_task(session.close()) + third_close = asyncio.create_task(session.close()) + assert not second_close.done() + assert not third_close.done() + FakeClient.close_gate.set() + await asyncio.gather(second_close, third_close) + + client = FakeClient.instances[0] + assert client.close_session_calls == 1 + assert client.close_calls == 1 + await session.close() + + +@pytest.mark.asyncio +async def test_close_failure_runs_remaining_cleanup_and_is_sticky() -> None: + failure = RuntimeError("close session failed") + FakeClient.close_session_error = failure + session = Session(runtime=runtime()) + await session.open() + + with pytest.raises(RuntimeError, match="close session failed") as first: + await session.close() + with pytest.raises(RuntimeError, match="close session failed") as second: + await session.close() + + client = FakeClient.instances[0] + assert first.value is failure + assert second.value is failure + assert client.close_session_calls == 1 + assert client.close_calls == 1 + + +@pytest.mark.asyncio +async def test_stream_serializes_text_and_pdf_through_wire_models() -> None: + session = Session(runtime=runtime()) + await session.open() + text = Document( + TextDocumentSource( + "notes", + name="notes.txt", + mime="application/x-high-level-only", + ) + ) + pdf = Document.from_bytes(b"%PDF-1.7\n%%EOF\n", name="report.pdf") + + stream = session.stream("review", files=(text, pdf)) + async with stream: + sent = FakeClient.instances[0].message_calls[-1]["files"] + wire = [item.model_dump(by_alias=True, exclude_none=True) for item in sent] + assert wire[0] == { + "type": "text", + "mediaType": "text/plain", + "data": "notes", + "name": "notes.txt", + } + assert wire[1]["mediaType"] == "application/pdf" + assert "mime" not in wire[0] + await session.close() + + +@pytest.mark.asyncio +async def test_active_turn_allows_non_turn_operations() -> None: + session = Session(runtime=runtime()) + await session.open() + stream = session.stream("waiting") + + await session.update_settings(model="other") + await session.rename("renamed") + unsubscribe = session.on_notification(lambda _event: None) + unsubscribe() + with pytest.raises(SessionBusyError): + session.stream("second") + with pytest.raises(SessionBusyError): + await session.fork() + + await stream.aclose() + await session.close() + + +@pytest.mark.asyncio +async def test_early_break_releases_turn_and_emits_safe_terminal_observability() -> ( + None +): + sink = ObservabilitySink() + observed_runtime = Runtime( + transport=cast("DroidClientTransport", FakeTransport()), + observability=Observability(logger=sink, metrics=sink), + ) + session = Session(runtime=observed_runtime) + await session.open() + stream = session.stream("private prompt") + + async with stream: + stream.queue_error_event(ErrorEvent("safe", ErrorType.PROTOCOL_ERROR)) + async for _event in stream: + break + + assert session._active_stream is None + terminal_logs = [ + event for event in sink.logs if event.name == "droid.sdk.run.terminal" + ] + terminal_metrics = [ + event for event in sink.metrics if event.name == "droid.sdk.run.terminal" + ] + assert len(terminal_logs) == 1 + assert terminal_logs[0].attributes == { + "session_id": "session-1", + "status": "interrupted", + } + assert "private prompt" not in repr(sink.logs) + assert len(terminal_metrics) == 1 + await session.close() + + +@pytest.mark.asyncio +async def test_replacement_race_rejects_work_and_close_owns_successor() -> None: + gate = asyncio.Event() + FakeClient.replacement_gate = gate + FakeClient.replacement_entered = asyncio.Event() + session = Session(runtime=runtime()) + await session.open() + + replacement = asyncio.create_task(session.fork()) + await FakeClient.replacement_entered.wait() + with pytest.raises(SessionBusyError): + session.stream("blocked") + with pytest.raises(SessionBusyError): + await session.fork() + with pytest.raises(SessionBusyError): + await session.open() + close = asyncio.create_task(session.close()) + assert not close.done() + + gate.set() + successor = await replacement + await close + with pytest.raises(SessionClosedError): + await successor.rename("closed") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("operation", ["fork", "compact", "rewind"]) +async def test_close_on_already_retired_source_does_not_close_successor( + operation: str, +) -> None: + session = Session(runtime=runtime()) + await session.open() + if operation == "fork": + successor = await session.fork() + elif operation == "compact": + successor = (await session.compact()).session + else: + successor = (await session.rewind("message", title="rewound")).session + client = FakeClient.instances[0] + + await session.close() + assert client.close_session_calls == 0 + assert client.close_calls == 0 + await successor.rename("still open") + + await successor.close() + assert client.close_session_calls == 1 + assert client.close_calls == 1 + + +@pytest.mark.asyncio +async def test_close_intent_survives_lock_race_with_replacement_completion() -> None: + FakeClient.replacement_gate = asyncio.Event() + FakeClient.replacement_entered = asyncio.Event() + session = Session(runtime=runtime()) + await session.open() + replacement = asyncio.create_task(session.fork()) + await FakeClient.replacement_entered.wait() + + await session._lifecycle_lock.acquire() + try: + closing = asyncio.create_task(session.close()) + while not session._replacement_close_requested: + await asyncio.sleep(0) + FakeClient.replacement_gate.set() + successor = await replacement + finally: + session._lifecycle_lock.release() + + await closing + with pytest.raises(SessionClosedError): + await successor.rename("closed") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("operation", ["fork", "compact", "rewind"]) +async def test_cancelled_replacement_rpc_restores_open_source(operation: str) -> None: + FakeClient.replacement_entered = asyncio.Event() + FakeClient.replacement_gate = asyncio.Event() + session = Session(runtime=runtime()) + await session.open() + + if operation == "fork": + replacement = asyncio.create_task(session.fork()) + elif operation == "compact": + replacement = asyncio.create_task(session.compact()) + else: + replacement = asyncio.create_task(session.rewind("message", title="rewound")) + await FakeClient.replacement_entered.wait() + replacement.cancel() + with pytest.raises(asyncio.CancelledError): + await replacement + + client = FakeClient.instances[0] + assert client.load_calls == [] + await session.rename("still open") + await session.close() + assert client.close_session_calls == 1 + assert client.close_calls == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("operation", ["fork", "compact", "rewind"]) +async def test_cancelled_replacement_after_successor_creation_restores_source( + operation: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config = SessionConfig( + additional_tools={"Custom"}, + enabled_tools={"Read"}, + disabled_tools={"Execute"}, + restrict_tools={"Read"}, + auto_reject_permission_requests=True, + disable_builtin_skills=True, + ) + session = Session(config=config, runtime=runtime()) + await session.open() + entered = asyncio.Event() + gate = asyncio.Event() + + async def gated_handoff() -> None: + entered.set() + await gate.wait() + + monkeypatch.setattr( + session_module, + "_replacement_handoff_checkpoint", + gated_handoff, + ) + if operation == "fork": + replacement = asyncio.create_task(session.fork()) + elif operation == "compact": + replacement = asyncio.create_task(session.compact()) + else: + replacement = asyncio.create_task(session.rewind("message", title="rewound")) + await entered.wait() + replacement.cancel() + with pytest.raises(asyncio.CancelledError): + await replacement + + client = FakeClient.instances[0] + assert [call["session_id"] for call in client.load_calls] == [ + "session-2", + "session-1", + ] + restored = client.load_calls[-1] + assert restored["additional_tool_ids"] == ["Custom"] + assert restored["enabled_tool_ids"] == ["Read"] + assert restored["disabled_tool_ids"] == ["Execute"] + assert restored["auto_reject_permission_requests"] is True + assert restored["disable_builtin_skills"] is True + assert client.update_calls[-1]["restrict_tool_ids"] == ["Read"] + await session.rename("restored") + await session.close() + assert client.close_session_calls == 1 + assert client.close_calls == 1 + + +@pytest.mark.asyncio +async def test_cancelled_replacement_racing_close_cleans_successor() -> None: + session = Session(runtime=runtime()) + await session.open() + entered = asyncio.Event() + gate = asyncio.Event() + original = session_module._replacement_handoff_checkpoint + + async def gated_handoff() -> None: + entered.set() + await gate.wait() + await original() + + session_module._replacement_handoff_checkpoint = gated_handoff + try: + replacement = asyncio.create_task(session.fork()) + await entered.wait() + closing = asyncio.create_task(session.close()) + while not session._replacement_close_requested: + await asyncio.sleep(0) + replacement.cancel() + with pytest.raises(asyncio.CancelledError): + await replacement + await closing + finally: + session_module._replacement_handoff_checkpoint = original + + client = FakeClient.instances[0] + assert client.close_session_calls == 1 + assert client.close_calls == 1 + assert session._state is session_module._State.CLOSED + + +@pytest.mark.asyncio +async def test_replacement_reattaches_policies_and_rolls_back() -> None: + config = SessionConfig( + additional_tools={"Custom"}, + enabled_tools={"Read"}, + disabled_tools={"Execute"}, + restrict_tools={"Read"}, + auto_reject_permission_requests=True, + disable_builtin_skills=True, + ) + session = Session(config=config, runtime=runtime()) + await session.open() + FakeClient.fail_replacement_load = True + + with pytest.raises(SessionReplacementError): + await session.fork() + + client = FakeClient.instances[0] + assert [call["session_id"] for call in client.load_calls] == [ + "session-2", + "session-1", + ] + for call in client.load_calls: + assert call["additional_tool_ids"] == ["Custom"] + assert call["enabled_tool_ids"] == ["Read"] + assert call["disabled_tool_ids"] == ["Execute"] + assert call["auto_reject_permission_requests"] is True + assert call["disable_builtin_skills"] is True + assert client.update_calls[-1]["restrict_tool_ids"] == ["Read"] + await session.rename("restored") + await session.close() + + +@pytest.mark.asyncio +async def test_replacement_success_reattaches_policies() -> None: + config = SessionConfig( + additional_tools={"Custom"}, + enabled_tools={"Read"}, + disabled_tools={"Execute"}, + restrict_tools={"Read"}, + auto_reject_permission_requests=True, + disable_builtin_skills=True, + ) + session = Session(config=config, runtime=runtime()) + await session.open() + + successor = await session.fork() + client = FakeClient.instances[0] + load = client.load_calls[-1] + assert load["additional_tool_ids"] == ["Custom"] + assert load["enabled_tool_ids"] == ["Read"] + assert load["disabled_tool_ids"] == ["Execute"] + assert load["auto_reject_permission_requests"] is True + assert load["disable_builtin_skills"] is True + assert client.update_calls[-1]["restrict_tool_ids"] == ["Read"] + with pytest.raises(SessionReplacedError): + await session.rename("retired") + await successor.close() + + +@pytest.mark.asyncio +async def test_replacement_rpc_failure_restores_open_state() -> None: + session = Session(runtime=runtime()) + await session.open() + FakeClient.fail_fork = True + + with pytest.raises(RuntimeError, match="fork failed"): + await session.fork() + await session.rename("still open") + await session.close() + + +@pytest.mark.asyncio +async def test_timeout_and_cancellation_ignore_hanging_interrupt() -> None: + FakeClient.send_gate = asyncio.Event() + FakeClient.hang_interrupt = True + session = Session(runtime=runtime()) + await session.open() + stream = session.stream("slow start", timeout=0.01) + + started = time.monotonic() + with pytest.raises(RunTimeoutError): + async with stream: + pass + assert time.monotonic() - started < 0.25 + assert session._active_stream is None + + FakeClient.send_gate = None + waiting = session.stream("wait forever") + await waiting.__aenter__() + next_event = asyncio.create_task(anext(waiting.__aiter__())) + await asyncio.sleep(0) + next_event.cancel() + started = time.monotonic() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(next_event, timeout=0.25) + assert time.monotonic() - started < 0.25 + assert session._active_stream is None + await session.close() + + +@pytest.mark.asyncio +async def test_stream_start_failure_releases_subscriptions_and_turn() -> None: + FakeClient.fail_send = True + session = Session(runtime=runtime()) + await session.open() + stream = session.stream("fails") + + with pytest.raises(RuntimeError, match="send failed"): + async with stream: + pass + + client = FakeClient.instances[0] + assert session._active_stream is None + assert client.error_callbacks == [] + await session.close() + + +def permission_params() -> dict[str, object]: + return { + "toolUses": [ + { + "toolUse": { + "type": "tool_use", + "id": "tool-1", + "name": "Create", + "input": {}, + }, + "confirmationType": "create", + "details": { + "type": "create", + "filePath": "/repo/a.py", + "fileName": "a.py", + "content": "private", + }, + } + ], + "options": [{"label": "Proceed", "value": "proceed_once"}], + "associatedSessionIds": [], + } + + +@pytest.mark.asyncio +async def test_interaction_failures_are_sanitized_stream_events() -> None: + def throwing(_request: object) -> object: + raise RuntimeError("private handler details") + + session = Session( + interactions=InteractionHandlers(on_permission=cast("Any", throwing)), + runtime=runtime(), + ) + await session.open() + stream = session.stream("interact") + await stream.__aenter__() + dispatcher = FakeClient.instances[0].dispatcher + assert dispatcher is not None + assert await dispatcher.handle_permission(permission_params()) == { + "selectedOption": "cancel" + } + + event = await anext(stream.__aiter__()) + assert isinstance(event, ErrorEvent) + assert event.message == "Permission interaction handler failed" + assert "private" not in event.message + await stream.aclose() + await session.close() + + +@pytest.mark.asyncio +async def test_mcp_configs_are_canonically_validated_and_serialized() -> None: + secret = "do-not-expose" + invalid = Session( + config=SessionConfig( + mcp_servers=( + HttpMcpServerConfig( + name="bad", + url="relative", + oauth=McpOAuthOptions(client_secret=secret), + ), + ) + ), + runtime=runtime(), + ) + with pytest.raises(ValueError) as raised: + await invalid.open() + assert secret not in str(raised.value) + assert secret not in repr(raised.value) + + config = HttpMcpServerConfig( + name="valid", + url="https://example.com/mcp", + headers=(HttpHeader("Authorization", "Bearer private"),), + oauth=McpOAuthOptions( + scopes=("read",), + authorization_server_issuer="https://auth.example.com", + client_id="client", + client_secret="secret", + ), + ) + session = Session( + config=SessionConfig(mcp_servers=(config,)), + runtime=runtime(), + ) + await session.open() + sent = FakeClient.instances[-1].initialize_calls[0]["mcp_servers"][0] + assert sent["type"] == "http" + assert sent["oauth"]["authorizationServerIssuer"] == ("https://auth.example.com") + await session.add_mcp_server(config) + assert FakeClient.instances[-1].mcp_calls[-1]["url"] == ("https://example.com/mcp") + await session.close() diff --git a/tests/test_v5_streaming_core.py b/tests/test_v5_streaming_core.py new file mode 100644 index 0000000..e1cac8e --- /dev/null +++ b/tests/test_v5_streaming_core.py @@ -0,0 +1,1327 @@ +from __future__ import annotations + +import asyncio +from collections.abc import Mapping +from datetime import datetime, timedelta, timezone +from typing import Any, cast + +import pytest +from pydantic import BaseModel + +from droid_sdk import ( + AssistantMessage, + Autonomy, + ErrorEvent, + HookExecution, + InteractionHandlers, + JsonSchema, + McpAuthCompleted, + McpAuthRequired, + McpStatusChanged, + Mode, + PermissionRequest, + PermissionResolved, + QuestionRequest, + ReasoningEffort, + RunFailure, + RunInterrupted, + RunStream, + RunSuccess, + RunTimeoutError, + SessionSettingsUpdate, + SessionTitleUpdated, + SessionWorkingDirectoryChanged, + SettingsUpdated, + StreamIncompleteError, + TextComplete, + TextDelta, + ThinkingComplete, + ThinkingDelta, + TokenUsageUpdate, + ToolCall, + ToolCallDelta, + ToolConfirmationOutcome, + ToolProgress, + ToolResult, + UserMessage, + WorkingStateChanged, +) +from droid_sdk._high_level.interaction_adapter import InteractionDispatcher +from droid_sdk._high_level.output import prepare_output_adapter +from droid_sdk._high_level.streaming import _javascript_number_string +from droid_sdk.errors import DroidProtocolError +from droid_sdk.low_level import DroidClient + +USAGE = { + "inputTokens": 1, + "outputTokens": 2, + "cacheCreationTokens": 3, + "cacheReadTokens": 4, + "thinkingTokens": 5, + "factoryCredits": 0.25, +} + + +def _message( + role: str = "assistant", + *, + content: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: + return { + "id": f"{role}-message", + "role": role, + "content": content or [{"type": "text", "id": "text-1", "text": "done"}], + "parentId": "parent", + "createdAt": 1_700_000_000, + "updatedAt": 1_700_000_001, + } + + +def _complete( + reason: str = "completed", + turn_id: str | None = "turn", +) -> dict[str, Any]: + value: dict[str, Any] = { + "type": "agent_turn_completed", + "reason": reason, + "tokenUsage": USAGE, + "durationMs": 125, + } + if turn_id is not None: + value["turnId"] = turn_id + return value + + +async def _collect(stream: RunStream[Any]) -> list[object]: + return [item async for item in stream] + + +@pytest.mark.asyncio +async def test_deadline_checked_before_each_queued_event_and_terminal() -> None: + current = 100.0 + releases: list[bool] = [] + stream = RunStream[None]( + expected_turn_id="turn", + session_id="session", + timeout=10, + monotonic=lambda: current, + finish=releases.append, + ) + await stream.__aenter__() + stream.feed_notification({"type": "create_message", "message": _message("user")}) + stream.feed_notification(_complete()) + iterator = stream.__aiter__() + + current = 109.999 + assert isinstance(await anext(iterator), UserMessage) + + current = 110.0 + with pytest.raises(RunTimeoutError): + await anext(iterator) + + assert releases == [True] + assert stream.completed is False + with pytest.raises(StreamIncompleteError): + _ = stream.result + + +@pytest.mark.asyncio +async def test_queued_terminal_after_deadline_cannot_become_success() -> None: + current = 5.0 + releases: list[bool] = [] + stream = RunStream[None]( + expected_turn_id="turn", + session_id="session", + timeout=1, + monotonic=lambda: current, + finish=releases.append, + ) + await stream.__aenter__() + stream.feed_notification(_complete()) + current = 6.001 + + with pytest.raises(RunTimeoutError): + await anext(stream.__aiter__()) + + assert releases == [True] + assert stream.completed is False + + +@pytest.mark.asyncio +async def test_terminal_arriving_after_deadline_is_never_recorded_as_success() -> None: + current = 1.0 + stream = RunStream[None]( + expected_turn_id="turn", + session_id="session", + timeout=2, + monotonic=lambda: current, + ) + await stream.__aenter__() + current = 3.0 + stream.feed_notification(_complete()) + + assert stream.completed is False + with pytest.raises(RunTimeoutError): + await anext(stream.__aiter__()) + + +@pytest.mark.asyncio +async def test_stream_all_documented_partial_events_in_delivery_order() -> None: + stream = RunStream[None]( + expected_turn_id="turn", + session_id="session", + include_partial_messages=True, + ) + notifications: list[dict[str, Any]] = [ + { + "type": "assistant_text_delta", + "messageId": "assistant-message", + "blockIndex": 0, + "textDelta": "fallback", + }, + { + "type": "assistant_text_complete", + "messageId": "assistant-message", + "blockIndex": 0, + }, + { + "type": "thinking_text_delta", + "messageId": "assistant-message", + "blockIndex": 1, + "textDelta": "thought", + }, + { + "type": "thinking_text_complete", + "messageId": "assistant-message", + "blockIndex": 1, + "durationMs": 50, + }, + { + "type": "tool_call", + "toolUse": { + "type": "tool_use", + "id": "tool-1", + "name": "Read", + "input": {"path": "/repo/a.py"}, + }, + }, + { + "type": "tool_progress_update", + "toolUseId": "tool-1", + "toolName": "Read", + "update": { + "type": "status", + "status": "running", + "timestamp": 1_700_000_002, + "parameters": {"path": "/repo/a.py"}, + "terminalId": "terminal", + "fullOutput": "output", + "subagentSessionId": "child", + }, + }, + { + "type": "session_token_usage_changed", + "sessionId": "session", + "tokenUsage": USAGE, + }, + {"type": "droid_working_state_changed", "newState": "idle"}, + { + "type": "permission_resolved", + "requestId": "permission", + "toolUseIds": ["tool-1"], + "selectedOption": "proceed_always_file", + }, + { + "type": "settings_updated", + "settings": { + "modelId": "model", + "reasoningEffort": "high", + "interactionMode": "auto", + "autonomyLevel": "low", + }, + }, + {"type": "session_title_updated", "title": "New title"}, + {"type": "session_working_directory_changed", "cwd": "/repo"}, + { + "type": "mcp_status_changed", + "servers": [ + { + "name": "local", + "status": "connected", + "source": "project", + "isManaged": False, + "serverType": "stdio", + } + ], + "summary": { + "total": 1, + "connected": 1, + "connecting": 0, + "failed": 0, + }, + }, + { + "type": "mcp_auth_required", + "serverName": "remote", + "authUrl": "https://example.test/auth", + "message": "Authenticate", + "state": "state", + }, + { + "type": "mcp_auth_completed", + "serverName": "remote", + "outcome": "success", + "message": "Done", + }, + {"type": "unknown_future_notification", "private": "ignored"}, + _complete(), + ] + for notification in notifications: + stream.feed_notification(notification) + + events = await _collect(stream) + assert [type(event) for event in events] == [ + TextDelta, + TextComplete, + ThinkingDelta, + ThinkingComplete, + ToolCallDelta, + ToolProgress, + TokenUsageUpdate, + WorkingStateChanged, + PermissionResolved, + SettingsUpdated, + SessionTitleUpdated, + SessionWorkingDirectoryChanged, + McpStatusChanged, + McpAuthRequired, + McpAuthCompleted, + RunSuccess, + ] + assert cast("TextDelta", events[0]).message_id == "assistant-message" + assert cast("ThinkingComplete", events[3]).duration == timedelta(milliseconds=50) + assert cast("ToolProgress", events[5]).update.terminal_id == "terminal" + assert cast("PermissionResolved", events[8]).selected_option is ( + ToolConfirmationOutcome.PROCEED_ALWAYS_EXACT_PATH + ) + assert stream.result.text == "fallback" + + +@pytest.mark.asyncio +async def test_protocol_epoch_milliseconds_are_aware_datetimes() -> None: + timestamp_ms = 1_700_000_000_123 + expected = datetime.fromtimestamp(timestamp_ms / 1000, tz=timezone.utc) + stream = RunStream[None]( + expected_turn_id="turn", + session_id="session", + include_partial_messages=True, + ) + message = _message() + message["createdAt"] = timestamp_ms + message["updatedAt"] = timestamp_ms + 1 + stream.feed_notification({"type": "create_message", "message": message}) + stream.feed_notification( + { + "type": "tool_progress_update", + "toolUseId": "tool", + "toolName": "Read", + "update": { + "type": "status", + "text": "working", + "timestamp": timestamp_ms, + }, + } + ) + stream.feed_notification(_complete()) + + events = await _collect(stream) + assistant = cast("AssistantMessage", events[0]) + progress = cast("ToolProgress", events[1]) + assert assistant.created_at == expected + assert assistant.updated_at == datetime.fromtimestamp( + (timestamp_ms + 1) / 1000, + tz=timezone.utc, + ) + assert progress.update.timestamp == expected + + +@pytest.mark.asyncio +async def test_tool_progress_preserves_explicit_empty_text() -> None: + stream = RunStream[None]( + expected_turn_id="turn", + session_id="session", + include_partial_messages=True, + ) + stream.feed_notification( + { + "type": "tool_progress_update", + "toolUseId": "tool", + "toolName": "Read", + "update": { + "type": "status", + "text": "", + "status": "running", + "details": "fallback", + }, + } + ) + stream.feed_notification(_complete()) + + progress = cast("ToolProgress", (await _collect(stream))[0]) + assert progress.content == "" + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (0, "0"), + (-0.0, "0"), + (1, "1"), + (-42, "-42"), + (1.5, "1.5"), + (1e-7, "1e-7"), + (-2.5e-7, "-2.5e-7"), + (1e-6, "0.000001"), + (1e20, "100000000000000000000"), + (1e21, "1e+21"), + (1.2345678901234567, "1.2345678901234567"), + (9_007_199_254_740_993, "9007199254740992"), + ], +) +def test_javascript_number_stringification( + value: int | float, + expected: str, +) -> None: + assert _javascript_number_string(value) == expected + + +@pytest.mark.asyncio +async def test_numeric_tool_result_uses_javascript_stringification() -> None: + stream = RunStream[None](expected_turn_id="turn", session_id="session") + stream.feed_notification( + { + "type": "tool_result", + "messageId": "message", + "toolUseId": "tool", + "content": 1e-7, + } + ) + stream.feed_notification(_complete()) + + result = cast("ToolResult", (await _collect(stream))[0]) + assert result.content == "1e-7" + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("wire_settings", "expected"), + [ + ({}, SessionSettingsUpdate()), + ({"modelId": "model"}, SessionSettingsUpdate(model="model")), + ( + {"reasoningEffort": "high"}, + SessionSettingsUpdate(reasoning_effort=ReasoningEffort.HIGH), + ), + ( + { + "interactionMode": "spec", + "autonomyLevel": "low", + "enabledToolIds": [], + "tags": [], + "compactionThresholdCheckEnabled": False, + }, + SessionSettingsUpdate( + mode=Mode.SPEC, + autonomy=Autonomy.LOW, + enabled_tools=frozenset(), + tags=(), + compaction_threshold_check_enabled=False, + ), + ), + ( + { + "specModeModelId": "spec-model", + "specModeReasoningEffort": "medium", + "additionalToolIds": ["one"], + "disabledToolIds": ["two"], + "restrictToolIds": ["three"], + }, + SessionSettingsUpdate( + spec_model="spec-model", + spec_reasoning_effort=ReasoningEffort.MEDIUM, + additional_tools={"one"}, + disabled_tools={"two"}, + restrict_tools={"three"}, + ), + ), + ( + {"autonomyMode": "auto-medium"}, + SessionSettingsUpdate( + mode=Mode.AUTO, + autonomy=Autonomy.MEDIUM, + ), + ), + ], +) +async def test_partial_settings_updates_are_always_emitted( + wire_settings: dict[str, object], + expected: SessionSettingsUpdate, +) -> None: + stream = RunStream[None]( + expected_turn_id="turn", + session_id="session", + include_partial_messages=True, + ) + stream.feed_notification({"type": "settings_updated", "settings": wire_settings}) + stream.feed_notification(_complete()) + + event = cast("SettingsUpdated", (await _collect(stream))[0]) + assert event.settings == expected + + +@pytest.mark.asyncio +async def test_complete_messages_blocks_tools_hooks_errors_and_default_filter() -> None: + stream = RunStream[None](expected_turn_id="turn", session_id="session") + stream.feed_notification( + { + "type": "assistant_text_delta", + "messageId": "assistant-message", + "blockIndex": 0, + "textDelta": "not persisted", + } + ) + stream.feed_notification( + { + "type": "create_message", + "message": _message( + content=[ + {"type": "text", "id": "text", "text": "one"}, + { + "type": "thinking", + "id": "thinking", + "thinking": "private", + "signature": "signature", + "durationMs": 5, + }, + { + "type": "redacted_thinking", + "id": "redacted", + "data": "opaque", + }, + { + "type": "tool_use", + "id": "tool-1", + "name": "Read", + "input": {"path": "/repo/a.py"}, + }, + { + "type": "tool_result", + "id": "result", + "toolUseId": "tool-0", + "content": [{"type": "text", "text": "nested"}], + "isError": False, + }, + { + "type": "document", + "id": "document", + "source": { + "type": "text", + "mediaType": "text/plain", + "data": "source", + "name": "a.py", + }, + }, + {"type": "text", "id": "text-2", "text": "two"}, + ] + ), + } + ) + stream.feed_notification( + { + "type": "tool_result", + "messageId": "tool-message", + "toolUseId": "tool-1", + "content": [{"type": "text", "text": "ok"}], + "isError": False, + } + ) + stream.feed_notification( + { + "type": "hook_execution_started", + "hookId": "hook", + "hookEventName": "PreToolUse", + "hookCommands": [{"command": "check", "timeout": 2}], + } + ) + stream.feed_notification( + { + "type": "hook_execution_completed", + "hookId": "hook", + "hookStatus": "completed", + "hookResults": [ + { + "command": "check", + "timeout": 2, + "exitCode": 0, + "stdout": "ok", + "stderr": "", + "suppressOutput": True, + } + ], + } + ) + stream.feed_notification( + { + "type": "error", + "message": "recoverable", + "errorType": "Error", + "timestamp": "2025-01-01T00:00:00Z", + } + ) + stream.feed_notification(_complete()) + + events = await _collect(stream) + assert [type(event) for event in events] == [ + ToolCall, + AssistantMessage, + ToolResult, + HookExecution, + HookExecution, + ErrorEvent, + RunSuccess, + ] + tool_result = cast("ToolResult", events[2]) + assert tool_result.tool_name == "Read" + assistant = cast("AssistantMessage", events[1]) + assert assistant.text == "onetwo" + assert assistant.created_at.tzinfo is not None + assert cast("HookExecution", events[3]).timeout == timedelta(seconds=2) + assert cast("HookExecution", events[4]).suppress_output is True + assert cast("ErrorEvent", events[5]).timestamp == datetime( + 2025, + 1, + 1, + tzinfo=timezone.utc, + ) + assert stream.result.messages == tuple(events[:-1]) + assert stream.result.text == "onetwo" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", ["completed", "error"]) +@pytest.mark.parametrize("hook_results", [None, []]) +async def test_hook_completion_without_results_emits_no_phantom_event( + status: str, + hook_results: object, +) -> None: + stream = RunStream[None](expected_turn_id="turn", session_id="session") + stream.feed_notification( + { + "type": "hook_execution_started", + "hookId": "hook", + "hookEventName": "PreToolUse", + "hookMatcher": "Read", + "hookToolCallId": "tool", + "hookCommands": [{"command": "check"}], + } + ) + stream.feed_notification( + { + "type": "hook_execution_completed", + "hookId": "hook", + "hookEventName": "PreToolUse", + "hookMatcher": "Read", + "hookToolCallId": "tool", + "hookStatus": status, + "hookResults": hook_results, + } + ) + stream.feed_notification(_complete()) + + events = await _collect(stream) + hooks = [event for event in events if isinstance(event, HookExecution)] + assert [hook.status for hook in hooks] == ["started"] + + +@pytest.mark.asyncio +async def test_user_message_and_foreign_idle_and_missing_turn_ids() -> None: + stream = RunStream[None]( + expected_turn_id="turn", + session_id="session", + include_partial_messages=True, + ) + stream.feed_notification({"type": "create_message", "message": _message("user")}) + stream.feed_notification( + {"type": "droid_working_state_changed", "newState": "idle"} + ) + stream.feed_notification(_complete(turn_id="foreign")) + with pytest.raises(StreamIncompleteError): + _ = stream.result + stream.feed_notification(_complete()) + events = await _collect(stream) + assert isinstance(events[0], UserMessage) + assert isinstance(events[1], WorkingStateChanged) + assert isinstance(events[-1], RunSuccess) + + malformed = RunStream[None](expected_turn_id="turn", session_id="session") + malformed.feed_notification(_complete(turn_id=None)) + with pytest.raises(DroidProtocolError, match="expected turn ID"): + await _collect(malformed) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "notification", + [ + {"type": "agent_turn_completed", "reason": "completed", "turnId": "turn"}, + { + "type": "assistant_text_delta", + "messageId": "message", + "blockIndex": 0, + }, + { + "type": "tool_progress_update", + "toolUseId": "tool", + "toolName": "Read", + "update": {"status": "running"}, + }, + {"type": "create_message"}, + ], +) +async def test_malformed_known_notifications_terminate_stream( + notification: dict[str, object], +) -> None: + stream = RunStream[None](expected_turn_id="turn", session_id="session") + stream.feed_notification(notification) + + with pytest.raises(DroidProtocolError, match=r"Invalid .* notification payload"): + await _collect(stream) + + +@pytest.mark.asyncio +async def test_malformed_known_wrapped_notification_terminates_stream() -> None: + stream = RunStream[None](expected_turn_id="turn", session_id="session") + stream.feed_notification( + { + "jsonrpc": "2.0", + "method": "droid.session_notification", + "params": { + "notification": { + "type": "assistant_text_complete", + "messageId": "message", + } + }, + } + ) + + with pytest.raises(DroidProtocolError, match="assistant_text_complete"): + await _collect(stream) + + +@pytest.mark.asyncio +async def test_unknown_notification_type_remains_ignored() -> None: + stream = RunStream[None](expected_turn_id="turn", session_id="session") + stream.feed_notification({"type": "future_notification", "value": "ignored"}) + stream.feed_notification(_complete()) + + events = await _collect(stream) + assert events == [stream.result] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("reason", "result_type", "subtype"), + [ + ("completed", RunSuccess, "success"), + ("spec_handoff", RunSuccess, "success"), + ("cancelled", RunInterrupted, "interrupted"), + ("permission_rejected", RunInterrupted, "interrupted"), + ("error", RunFailure, "error_during_execution"), + ("structured_output_missing", RunFailure, "error_structured_output"), + ("structured_output_invalid", RunFailure, "error_structured_output"), + ("structured_output_schema_invalid", RunFailure, "error_structured_output"), + ], +) +async def test_every_terminal_result_family( + reason: str, + result_type: type[object], + subtype: str, +) -> None: + stream = RunStream[None](expected_turn_id="turn", session_id="session") + stream.feed_notification( + { + "type": "assistant_text_delta", + "messageId": "assistant-message", + "blockIndex": 0, + "textDelta": "partial", + } + ) + stream.feed_notification(_complete(reason)) + await _collect(stream) + assert isinstance(stream.result, result_type) + assert stream.result.subtype == subtype + assert stream.result.text == "partial" + assert stream.result.usage is not None + assert stream.result.usage.factory_credits == 0.25 + assert stream.result.duration == timedelta(milliseconds=125) + if isinstance(stream.result, RunFailure): + assert stream.result.error is not None + assert (stream.result.structured_output_error is not None) is ( + subtype == "error_structured_output" + ) + + +class Review(BaseModel): + summary: str + count: int + + +class NumericOutput(BaseModel): + value: float + + +@pytest.mark.asyncio +async def test_structured_output_raw_adapted_fallback_and_validation_error() -> None: + valid = RunStream[Review]( + expected_turn_id="turn", + session_id="session", + output_adapter=prepare_output_adapter(Review), + ) + valid.feed_notification( + { + "type": "structured_output", + "messageId": "assistant", + "structuredOutput": {"summary": "ok", "count": 2}, + } + ) + valid.feed_notification(_complete()) + await _collect(valid) + assert valid.result.output == Review(summary="ok", count=2) + assert valid.result.structured_output == {"summary": "ok", "count": 2} + + invalid = RunStream[Review]( + expected_turn_id="turn", + session_id="session", + output_adapter=prepare_output_adapter(Review), + ) + invalid.feed_notification( + { + "type": "structured_output", + "messageId": "assistant", + "structuredOutput": {"summary": "partial", "count": "bad"}, + } + ) + invalid.feed_notification(_complete()) + await _collect(invalid) + assert invalid.result.output is None + assert invalid.result.output_validation_error is not None + assert invalid.result.structured_output == { + "summary": "partial", + "count": "bad", + } + + raw = RunStream[Mapping[str, object]]( + expected_turn_id="turn", + session_id="session", + output_adapter=cast( + "Any", + prepare_output_adapter(JsonSchema({"type": "object"})), + ), + ) + raw.feed_notification( + { + "type": "assistant_text_delta", + "messageId": "assistant", + "blockIndex": 0, + "textDelta": '{"summary":"fallback"}', + } + ) + raw.feed_notification(_complete()) + await _collect(raw) + assert raw.result.output == {"summary": "fallback"} + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "raw_json", + [ + '{"summary":"invalid","count":NaN}', + '{"summary":"invalid","count":Infinity}', + '{"summary":"invalid","count":-Infinity}', + '{"summary":"invalid","count":1e10000}', + '{"summary":"invalid","count":-1e10000}', + ('{"summary":"valid","count":1,"nested":{"items":[{"value":1e10000}]}}'), + ('{"summary":"valid","count":1,"nested":{"items":[{"value":-1e10000}]}}'), + ], +) +async def test_non_finite_structured_output_fallback_always_terminalizes( + raw_json: str, +) -> None: + stream = RunStream[Review]( + expected_turn_id="turn", + session_id="session", + output_adapter=prepare_output_adapter(Review), + ) + stream.feed_notification( + { + "type": "assistant_text_delta", + "messageId": "assistant", + "blockIndex": 0, + "textDelta": raw_json, + } + ) + stream.feed_notification(_complete()) + + events = await _collect(stream) + assert events[-1] is stream.result + assert isinstance(stream.result, RunSuccess) + assert stream.result.output is None + assert stream.result.structured_output is None + assert stream.result.output_validation_error is not None + + +@pytest.mark.asyncio +async def test_large_finite_structured_output_is_retained_and_adapted() -> None: + stream = RunStream[NumericOutput]( + expected_turn_id="turn", + session_id="session", + output_adapter=prepare_output_adapter(NumericOutput), + ) + stream.feed_notification( + { + "type": "assistant_text_delta", + "messageId": "assistant", + "blockIndex": 0, + "textDelta": '{"value":1e300}', + } + ) + stream.feed_notification(_complete()) + + await _collect(stream) + assert stream.result.output == NumericOutput(value=1e300) + assert stream.result.structured_output == {"value": 1e300} + assert stream.result.output_validation_error is None + + +@pytest.mark.asyncio +async def test_non_finite_structured_output_notification_is_not_retained() -> None: + stream = RunStream[Review]( + expected_turn_id="turn", + session_id="session", + output_adapter=prepare_output_adapter(Review), + ) + stream.feed_notification( + { + "type": "structured_output", + "messageId": "assistant", + "structuredOutput": {"summary": "invalid", "count": float("nan")}, + } + ) + stream.feed_notification(_complete()) + + await _collect(stream) + assert stream.result.output is None + assert stream.result.structured_output is None + assert stream.result.output_validation_error is not None + + +@pytest.mark.asyncio +async def test_result_cache_error_propagation_and_single_consumer() -> None: + stream = RunStream[None](expected_turn_id="turn", session_id="session") + with pytest.raises(StreamIncompleteError): + _ = stream.result + stream.feed_notification(_complete()) + first = await _collect(stream) + assert first[-1] is stream.result + assert stream.result is stream.result + with pytest.raises(RuntimeError, match="one consumer"): + await _collect(stream) + + failed = RunStream[None](expected_turn_id="turn", session_id="session") + failed.feed_error(DroidProtocolError("transport failed")) + with pytest.raises(DroidProtocolError, match="transport failed"): + await _collect(failed) + + +def _permission_params( + *, + detail: dict[str, Any] | None = None, + option: str = "proceed_once", +) -> dict[str, object]: + return { + "toolUses": [ + { + "toolUse": { + "type": "tool_use", + "id": "tool-1", + "name": "Create", + "input": {"secret": "prompt payload"}, + }, + "confirmationType": (detail or {}).get("type", "create"), + "details": detail + or { + "type": "create", + "filePath": "/repo/a.py", + "fileName": "a.py", + "content": "credential payload", + }, + } + ], + "options": [{"label": "Proceed", "value": option}], + "associatedSessionIds": ["child"], + } + + +def _question_params() -> dict[str, object]: + return { + "toolCallId": "tool-1", + "questions": [ + { + "index": 1, + "topic": "Choice", + "question": "Pick one", + "options": ["a", "b"], + "multiSelect": True, + } + ], + } + + +@pytest.mark.asyncio +async def test_interaction_sync_async_helpers_wire_fields_and_outcomes() -> None: + errors: list[ErrorEvent] = [] + + def permission(request: PermissionRequest) -> object: + assert request.associated_session_ids == ("child",) + return request.respond( + ToolConfirmationOutcome.PROCEED_ONCE, + comment="approved", + ) + + async def question(request: QuestionRequest) -> object: + question_value = request.questions[0] + return request.submit([question_value.answer_multiple(["a", "b"])]) + + dispatcher = InteractionDispatcher( + cast( + "Any", + InteractionHandlers( + on_permission=permission, + on_question=question, + ), + ), + error_sink=errors.append, + ) + assert await dispatcher.handle_permission(_permission_params()) == { + "selectedOption": "proceed_once", + "comment": "approved", + } + assert await dispatcher.handle_question(_question_params()) == { + "cancelled": False, + "answers": [{"index": 1, "question": "Pick one", "answer": "a, b"}], + } + assert errors == [] + + +@pytest.mark.parametrize( + ("detail", "expected_type"), + [ + ( + { + "type": "edit", + "filePath": "/repo/a.py", + "fileName": "a.py", + "oldContent": "old", + "newContent": "new", + }, + "EditAction", + ), + ( + { + "type": "exec", + "fullCommand": "git status", + "command": "git", + "extractedCommands": ["git", "status"], + "impactLevel": "low", + "riskLevelReason": "read-only", + }, + "ExecuteAction", + ), + ( + { + "type": "create", + "filePath": "/repo/a.py", + "fileName": "a.py", + "content": "content", + }, + "CreateFile", + ), + ( + { + "type": "ask_user", + "questionnaire": "questions", + "parsed": {"questions": _question_params()["questions"]}, + }, + "AskUserAction", + ), + ( + {"type": "exit_spec_mode", "plan": "plan", "title": "title"}, + "ExitSpecModeAction", + ), + ( + { + "type": "apply_patch", + "filePath": "/repo/a.py", + "fileName": "a.py", + "patchContent": "patch", + "files": [ + { + "filePath": "/repo/a.py", + "fileName": "a.py", + "operation": "update", + "moveTo": "/repo/b.py", + } + ], + }, + "ApplyPatchAction", + ), + ( + { + "type": "mcp_tool", + "toolName": "search", + "impactLevel": "medium", + "serverName": "server", + "actualToolName": "actual", + }, + "McpToolAction", + ), + ( + { + "type": "sandbox_violation", + "violatingToolName": "Execute", + "target": "/outside", + "operationType": "write", + "violationType": "filesystem-write", + "reason": "outside sandbox", + "violationReason": "not-allowed", + "isOrgDeny": True, + }, + "SandboxViolationAction", + ), + ( + { + "type": "droid_shield_violation", + "command": "unsafe", + "reason": "blocked", + }, + "DroidShieldViolationAction", + ), + ], +) +def test_every_permission_action_is_converted( + detail: dict[str, Any], + expected_type: str, +) -> None: + captured: list[PermissionRequest] = [] + + def handler(request: PermissionRequest) -> object: + captured.append(request) + return request.respond(ToolConfirmationOutcome.PROCEED_ONCE) + + dispatcher = InteractionDispatcher( + InteractionHandlers(on_permission=cast("Any", handler)) + ) + result = asyncio.run( + dispatcher.handle_permission(_permission_params(detail=detail)) + ) + assert result == {"selectedOption": "proceed_once"} + assert type(captured[0].actions[0]).__name__ == expected_type + + +@pytest.mark.asyncio +async def test_every_permission_outcome_and_edited_content_are_preserved() -> None: + for outcome in ToolConfirmationOutcome: + edited = ( + "edited plan" if outcome is ToolConfirmationOutcome.PROCEED_EDIT else None + ) + + def handler( + request: PermissionRequest, + selected: ToolConfirmationOutcome = outcome, + content: str | None = edited, + ) -> object: + return request.respond( + selected, + comment="comment", + edited_spec_content=content, + ) + + dispatcher = InteractionDispatcher( + InteractionHandlers(on_permission=cast("Any", handler)) + ) + result = await dispatcher.handle_permission( + _permission_params(option=outcome.value) + ) + assert result["selectedOption"] == outcome.value + assert result["comment"] == "comment" + if edited is not None: + assert result["editedSpecContent"] == edited + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "handler", + [ + None, + lambda request: object(), + lambda request: request.respond(ToolConfirmationOutcome.CANCEL), + lambda request: (_ for _ in ()).throw( + RuntimeError("prompt payload credential payload /repo/a.py") + ), + ], +) +async def test_permission_failures_cancel_and_are_sanitized(handler: object) -> None: + errors: list[ErrorEvent] = [] + dispatcher = InteractionDispatcher( + InteractionHandlers(on_permission=cast("Any", handler)), + error_sink=errors.append, + ) + result = await dispatcher.handle_permission(_permission_params()) + assert result == {"selectedOption": "cancel"} + assert len(errors) == 1 + diagnostic = repr(errors[0]) + for secret in ("prompt payload", "credential payload", "/repo/a.py"): + assert secret not in diagnostic + + +@pytest.mark.asyncio +async def test_interaction_cancellation_is_never_wrapped() -> None: + async def cancelled(request: PermissionRequest) -> object: + raise asyncio.CancelledError + + dispatcher = InteractionDispatcher( + InteractionHandlers(on_permission=cast("Any", cancelled)) + ) + with pytest.raises(asyncio.CancelledError): + await dispatcher.handle_permission(_permission_params()) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "handler", + [ + None, + lambda request: object(), + lambda request: (_ for _ in ()).throw(RuntimeError("Pick one prompt payload")), + ], +) +async def test_question_failures_cancel_and_are_sanitized(handler: object) -> None: + errors: list[ErrorEvent] = [] + dispatcher = InteractionDispatcher( + InteractionHandlers(on_question=cast("Any", handler)), + error_sink=errors.append, + ) + assert await dispatcher.handle_question(_question_params()) == { + "cancelled": True, + "answers": [], + } + assert len(errors) == 1 + assert "Pick one" not in repr(errors[0]) + assert "prompt payload" not in repr(errors[0]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure_kind", ["sync", "async", "invalid"]) +async def test_throwing_error_sink_cannot_block_permission_cancellation( + failure_kind: str, +) -> None: + def sync_failure(request: PermissionRequest) -> object: + raise RuntimeError("permission failed") + + async def async_failure(request: PermissionRequest) -> object: + raise RuntimeError("permission failed") + + def invalid_response(request: PermissionRequest) -> object: + return object() + + handlers = { + "sync": sync_failure, + "async": async_failure, + "invalid": invalid_response, + } + + def throwing_sink(event: ErrorEvent) -> None: + raise RuntimeError("sink failed") + + dispatcher = InteractionDispatcher( + InteractionHandlers(on_permission=cast("Any", handlers[failure_kind])), + error_sink=throwing_sink, + ) + assert await dispatcher.handle_permission(_permission_params()) == { + "selectedOption": "cancel" + } + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure_kind", ["sync", "async", "invalid"]) +async def test_throwing_error_sink_cannot_block_question_cancellation( + failure_kind: str, +) -> None: + def sync_failure(request: QuestionRequest) -> object: + raise RuntimeError("question failed") + + async def async_failure(request: QuestionRequest) -> object: + raise RuntimeError("question failed") + + def invalid_response(request: QuestionRequest) -> object: + return object() + + handlers = { + "sync": sync_failure, + "async": async_failure, + "invalid": invalid_response, + } + + def throwing_sink(event: ErrorEvent) -> None: + raise RuntimeError("sink failed") + + dispatcher = InteractionDispatcher( + InteractionHandlers(on_question=cast("Any", handlers[failure_kind])), + error_sink=throwing_sink, + ) + assert await dispatcher.handle_question(_question_params()) == { + "cancelled": True, + "answers": [], + } + + +@pytest.mark.asyncio +async def test_clearing_high_level_handlers_cannot_reactivate_legacy_approval() -> None: + client = DroidClient(exec_path="/not-used") + legacy_calls = 0 + + def approve_legacy(params: dict[str, object]) -> str: + nonlocal legacy_calls + legacy_calls += 1 + return "proceed_once" + + client.set_permission_handler(approve_legacy) + client.set_ask_user_handler( + lambda params: {"cancelled": False, "answers": ["legacy"]} + ) + client.set_interaction_handlers( + InteractionHandlers( + on_permission=lambda request: request.respond( + ToolConfirmationOutcome.PROCEED_ONCE + ), + on_question=lambda request: request.cancel(), + ) + ) + client.clear_interaction_handlers() + + assert client._dispatch_permission_request({}) == "cancel" + assert client._dispatch_ask_user_request({}) == { + "cancelled": True, + "answers": [], + } + assert legacy_calls == 0 diff --git a/tests/test_v5_typing_fixtures.py b/tests/test_v5_typing_fixtures.py new file mode 100644 index 0000000..66deed3 --- /dev/null +++ b/tests/test_v5_typing_fixtures.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).parents[1] +NEGATIVE_FIXTURE = ROOT / "tests" / "typing" / "negative.py" +NEGATIVE_PYRIGHT_CONFIG = ROOT / "tests" / "typing" / "pyright-negative.json" + + +def test_negative_mypy_fixture_is_rejected() -> None: + completed = subprocess.run( + [ + sys.executable, + "-m", + "mypy", + "--strict", + str(NEGATIVE_FIXTURE), + ], + cwd=ROOT, + check=False, + capture_output=True, + text=True, + timeout=30, + ) + assert completed.returncode == 1 + assert "Missing positional arguments" in completed.stdout + assert 'cannot be "str"' in completed.stdout + assert "Incompatible types in assignment" in completed.stdout + assert completed.stdout.count("Unsupported target for indexed assignment") == 2 + + +def test_negative_pyright_fixture_is_rejected() -> None: + pyright = shutil.which("pyright") + if pyright is None: + pytest.fail("pyright executable is required for typing fixture tests") + completed = subprocess.run( + [pyright, "--project", str(NEGATIVE_PYRIGHT_CONFIG)], + cwd=ROOT, + check=False, + capture_output=True, + text=True, + timeout=30, + ) + assert completed.returncode == 1 + assert '"model", "reasoning_effort"' in completed.stdout + assert "No overloads for" in completed.stdout + assert 'Type "BadLogger" is not assignable to declared type "Logger"' in ( + completed.stdout + ) + assert '"__setitem__" method not defined on type "FrozenJsonObject"' in ( + completed.stdout + ) + assert '"__setitem__" method not defined on type "tuple' in completed.stdout diff --git a/tests/typing/negative.py b/tests/typing/negative.py new file mode 100644 index 0000000..6c63b56 --- /dev/null +++ b/tests/typing/negative.py @@ -0,0 +1,65 @@ +# ruff: noqa: TC001 + +from __future__ import annotations + +from droid_sdk import ( + FrozenJsonObject, + FrozenJsonValue, + PermissionHandler, + PermissionRequest, + QuestionHandler, + QuestionRequest, + RunResult, + Session, + SessionSettings, + ToolInfo, + ToolResultBlock, +) +from droid_sdk._high_level.output import prepare_output_adapter +from droid_sdk.observability import Logger + + +class BadLogger: + def log(self, event: str) -> None: + pass + + +SessionSettings() +SessionSettings(model=None, reasoning_effort=None) +ToolInfo(id="Read") +ToolResultBlock(tool_use_id="tool-1", content=[object()]) +prepare_output_adapter(str) +logger: Logger = BadLogger() + + +def bad_permission_handler(request: PermissionRequest) -> str: + return "proceed_once" + + +def bad_question_handler(request: QuestionRequest) -> dict[str, object]: + return {"cancelled": True, "answers": []} + + +permission_handler: PermissionHandler = bad_permission_handler +question_handler: QuestionHandler = bad_question_handler + + +def consume_text(value: str) -> None: + pass + + +def misuse_result_output(result: RunResult[int]) -> None: + consume_text(result.output) + + +def mutate_frozen_json( + value: FrozenJsonObject, + sequence: tuple[FrozenJsonValue, ...], +) -> None: + value["changed"] = True + sequence[0] = "changed" + + +async def misuse_high_level_generics(session: Session) -> None: + await session.stream("prompt", output=str) + await session.remove_mcp_server("name", scope="project") diff --git a/tests/typing/positive.py b/tests/typing/positive.py new file mode 100644 index 0000000..9f56aa5 --- /dev/null +++ b/tests/typing/positive.py @@ -0,0 +1,286 @@ +# ruff: noqa: TC001 + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Literal + +from pydantic import BaseModel +from typing_extensions import assert_type + +from droid_sdk import ( + ApplyPatchAction, + ApplyPatchFile, + AssistantMessage, + CompactOutcome, + DocumentBlock, + FrozenJsonObject, + FrozenJsonValue, + ImageBlock, + JsonObject, + JsonSchema, + McpServerStatusInfo, + McpStatusChanged, + PermissionAction, + PermissionHandler, + PermissionRequest, + PermissionResponse, + QuestionHandler, + QuestionRequest, + QuestionResponse, + ReasoningEffort, + RewindOutcome, + RunFailure, + RunInterrupted, + RunResult, + RunStream, + RunSuccess, + Session, + SessionSettings, + SessionSettingsUpdate, + StreamEvent, + StreamMessage, + TextBlock, + TextDelta, + ToolCategory, + ToolInfo, + ToolResultBlock, + ToolUseBlock, + run, +) +from droid_sdk._high_level.output import OutputAdapter, prepare_output_adapter +from droid_sdk.observability import ( + LogEvent, + Logger, + MetricEvent, + MetricSink, + TraceContext, + TraceContextProvider, +) + + +class Review(BaseModel): + summary: str + + +assert_type(prepare_output_adapter(), OutputAdapter[None]) +assert_type(prepare_output_adapter(Review), OutputAdapter[Review]) + +raw_adapter = prepare_output_adapter(JsonSchema({"type": "object"})) +assert_type(raw_adapter, OutputAdapter[JsonObject]) + +schema_input: JsonObject = { + "type": "object", + "required": ["summary"], +} +frozen_schema = JsonSchema(schema_input).schema +assert_type(frozen_schema, FrozenJsonObject) +assert_type(frozen_schema["type"], FrozenJsonValue) +assert_type(frozen_schema.get("required"), FrozenJsonValue | None) + +settings = SessionSettings( + model="claude-sonnet", + reasoning_effort=ReasoningEffort.HIGH, +) +assert_type(settings.model, str) +assert_type(settings.reasoning_effort, ReasoningEffort) + +settings_update = SessionSettingsUpdate(model="claude-sonnet") +assert_type(settings_update.model, str | None) +assert_type(settings_update.reasoning_effort, ReasoningEffort | None) + +tool = ToolInfo( + id="Read", + display_name="Read", + description="Read a file", + category=ToolCategory.READ, + default_allowed=True, + allowed=True, +) +assert_type(tool.category, ToolCategory) + +block = ToolResultBlock( + tool_use_id="tool-1", + content=[TextBlock(text="done")], +) +if block.content is not None and not isinstance(block.content, str): + assert_type( + block.content[0], + TextBlock | ImageBlock | DocumentBlock | FrozenJsonValue, + ) + +json_block = ToolResultBlock( + tool_use_id="tool-2", + content=[{"nested": ["value"]}], +) +if json_block.content is not None and not isinstance(json_block.content, str): + assert_type( + json_block.content[0], + TextBlock | ImageBlock | DocumentBlock | FrozenJsonValue, + ) + +tool_use = ToolUseBlock(id="tool-1", name="ApplyPatch", input={}) +action: PermissionAction = ApplyPatchAction( + tool_use=tool_use, + file_path="/repo/a.py", + file_name="a.py", + patch_content="patch", + files=[ + ApplyPatchFile( + file_path="/repo/a.py", + file_name="a.py", + operation="update", + ) + ], +) + + +def handle_action(value: PermissionAction) -> None: + if isinstance(value, ApplyPatchAction): + assert_type(value.files, Sequence[ApplyPatchFile] | None) + + +handle_action(action) + + +def handle_result(result: RunResult[Review]) -> None: + assert_type(result.output, Review | None) + if isinstance(result, RunSuccess): + assert_type(result.subtype, Literal["success"]) + assert_type(result.success, Literal[True]) + assert_type(result.interrupted, Literal[False]) + elif isinstance(result, RunInterrupted): + assert_type(result.subtype, Literal["interrupted"]) + assert_type(result.success, Literal[False]) + assert_type(result.interrupted, Literal[True]) + elif isinstance(result, RunFailure): + assert_type( + result.subtype, + Literal["error_during_execution", "error_structured_output"], + ) + assert_type(result.success, Literal[False]) + assert_type(result.interrupted, Literal[False]) + + +def handle_success(result: RunSuccess[Review]) -> None: + assert_type(result.output, Review | None) + + +def handle_interrupted(result: RunInterrupted[Review]) -> None: + assert_type(result.output, Review | None) + + +def handle_failure(result: RunFailure[Review]) -> None: + assert_type(result.output, Review | None) + + +def handle_stream_event(event: StreamEvent[Review]) -> None: + if isinstance(event, RunResult): + assert_type( + event, + RunSuccess[Review] | RunInterrupted[Review] | RunFailure[Review], + ) + assert_type(event.output, Review | None) + if isinstance(event, RunSuccess): + assert_type(event, RunSuccess[Review]) + assert_type(event.output, Review | None) + + +def handle_stream_message(message: StreamMessage[Review]) -> None: + if isinstance(message, AssistantMessage): + assert_type(message, AssistantMessage) + elif isinstance(message, RunResult): + assert_type( + message, + RunSuccess[Review] | RunInterrupted[Review] | RunFailure[Review], + ) + + +def handle_partial_event(event: StreamEvent[Review]) -> None: + if isinstance(event, TextDelta): + assert_type(event, TextDelta) + assert_type(event.block_index, int) + + +def approve(request: PermissionRequest) -> PermissionResponse: + return request.respond(request.options[0].value) + + +async def answer(request: QuestionRequest) -> QuestionResponse: + return request.cancel() + + +permission_handler: PermissionHandler = approve +question_handler: QuestionHandler = answer + + +def handle_mcp(event: McpStatusChanged) -> None: + assert_type(event.servers[0], McpServerStatusInfo) + + +class Sink: + def log(self, event: LogEvent) -> None: + pass + + def record(self, event: MetricEvent) -> None: + pass + + def inject(self, carrier: TraceContext) -> None: + pass + + +logger: Logger = Sink() +metrics: MetricSink = Sink() +tracing: TraceContextProvider = Sink() + + +async def public_generic_calls(session: Session) -> None: + assert_type(await run("hello"), RunResult[None]) + assert_type(await run("hello", output=Review), RunResult[Review]) + assert_type( + await run("hello", output=JsonSchema({"type": "object"})), + RunResult[JsonObject], + ) + + assert_type( + session.stream("hello"), + RunStream[None, StreamMessage[None]], + ) + assert_type( + session.stream("hello", output=Review), + RunStream[Review, StreamMessage[Review]], + ) + assert_type( + session.stream("hello", output=JsonSchema({"type": "object"})), + RunStream[JsonObject, StreamMessage[JsonObject]], + ) + assert_type( + session.stream("hello", include_partial_messages=True), + RunStream[None, StreamEvent[None]], + ) + assert_type( + session.stream( + "hello", + output=Review, + include_partial_messages=True, + ), + RunStream[Review, StreamEvent[Review]], + ) + assert_type( + session.stream( + "hello", + output=JsonSchema({"type": "object"}), + include_partial_messages=True, + ), + RunStream[JsonObject, StreamEvent[JsonObject]], + ) + + +async def lifecycle_outcomes( + compact: CompactOutcome, + rewind: RewindOutcome, +) -> None: + assert_type(compact.session, Session) + assert_type(rewind.session, Session) + async with compact.session as successor: + assert_type(successor, Session) diff --git a/tests/typing/pyright-negative.json b/tests/typing/pyright-negative.json new file mode 100644 index 0000000..6969be2 --- /dev/null +++ b/tests/typing/pyright-negative.json @@ -0,0 +1,6 @@ +{ + "include": ["negative.py"], + "extraPaths": ["../../src"], + "pythonVersion": "3.10", + "typeCheckingMode": "strict" +} diff --git a/uv.lock b/uv.lock index 2bf360f..dd8d620 100644 --- a/uv.lock +++ b/uv.lock @@ -1,6 +1,14 @@ version = 1 revision = 3 requires-python = ">=3.10" +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform == 'win32'", + "python_full_version < '3.11' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'win32'", + "python_full_version < '3.11' and sys_platform != 'win32'", +] [[package]] name = "annotated-types" @@ -11,6 +19,29 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643, upload-time = "2024-05-20T21:33:24.1Z" }, ] +[[package]] +name = "anyio" +version = "4.14.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, + { name = "idna" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/cc/a381afa6efea9f496eff839d4a6a1aed3bfafc7b3ab4b0d1b243a12573dd/anyio-4.14.2.tar.gz", hash = "sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f", size = 260176, upload-time = "2026-07-12T20:29:07.082Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" }, +] + +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + [[package]] name = "backports-asyncio-runner" version = "1.2.0" @@ -20,6 +51,137 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a0/59/76ab57e3fe74484f48a53f8e337171b4a2349e506eabe136d7e01d059086/backports_asyncio_runner-1.2.0-py3-none-any.whl", hash = "sha256:0da0a936a8aeb554eccb426dc55af3ba63bcdc69fa1a600b5bb305413a4477b5", size = 12313, upload-time = "2025-07-02T02:27:14.263Z" }, ] +[[package]] +name = "certifi" +version = "2026.7.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, +] + +[[package]] +name = "cffi" +version = "2.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser", marker = "implementation_name != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b6/d2/2cde336b375f55c76ca670f0be3978cc048e31e24f3b4d7ce8473150a388/cffi-2.1.1-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be", size = 183779, upload-time = "2026-08-03T21:19:15.602Z" }, + { url = "https://files.pythonhosted.org/packages/94/1a/4b2f7c92293ba05cbd4a9a1b28faaf0326272d9488e6354657571c48a7aa/cffi-2.1.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b", size = 184178, upload-time = "2026-08-03T21:19:16.67Z" }, + { url = "https://files.pythonhosted.org/packages/17/0b/ba385d8ccedf926c3cd06e8e2f327027da5afe5f0eb30f1f7bc43ac55125/cffi-2.1.1-cp310-cp310-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004", size = 211037, upload-time = "2026-08-03T21:19:17.705Z" }, + { url = "https://files.pythonhosted.org/packages/a3/b9/0f2e58b2cefa33255bff36935d42b13180fe559bba82596540eb404bde7d/cffi-2.1.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9", size = 218652, upload-time = "2026-08-03T21:19:18.735Z" }, + { url = "https://files.pythonhosted.org/packages/37/15/180e0dab27b9312c7479003d14c9e547634b7dcb934e2cc4650e1b131a7a/cffi-2.1.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98", size = 205422, upload-time = "2026-08-03T21:19:19.96Z" }, + { url = "https://files.pythonhosted.org/packages/18/d4/03026f0c850cbbaa9030750490225b4a7f4d524ea4df72c3cc740a90f4ef/cffi-2.1.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9", size = 205444, upload-time = "2026-08-03T21:19:21.246Z" }, + { url = "https://files.pythonhosted.org/packages/75/77/60bebf6f818bec84210ac5b6979ce4eeadce6fbbaabc9c7ab23e506d1ce5/cffi-2.1.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6", size = 218742, upload-time = "2026-08-03T21:19:22.523Z" }, + { url = "https://files.pythonhosted.org/packages/b0/ae/679bf47e73fd77b352171727f07de559a003f14de5d02b904a6ec1fa73ca/cffi-2.1.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf", size = 221054, upload-time = "2026-08-03T21:19:23.694Z" }, + { url = "https://files.pythonhosted.org/packages/09/b8/eefc0e06913b70aa153bf74c946094a18f58fd4aff11b7f372bfdfdca050/cffi-2.1.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659", size = 213489, upload-time = "2026-08-03T21:19:24.922Z" }, + { url = "https://files.pythonhosted.org/packages/6f/13/4e56852824a03cdf68523a35686f1c28eacd4bd30a7b0a78e682e6e6e1d3/cffi-2.1.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9", size = 220241, upload-time = "2026-08-03T21:19:26.214Z" }, + { url = "https://files.pythonhosted.org/packages/99/7f/040f9e163e4acac3ee3d85b02d00b2576e7ca980d8785f0a3a5f1a9bf7f5/cffi-2.1.1-cp310-cp310-win32.whl", hash = "sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41", size = 174578, upload-time = "2026-08-03T21:19:27.338Z" }, + { url = "https://files.pythonhosted.org/packages/ba/0b/644a2ec1a4eaba49c2939410bb1eb1d25b09d6d0582f5d2f95c537043725/cffi-2.1.1-cp310-cp310-win_amd64.whl", hash = "sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1", size = 185082, upload-time = "2026-08-03T21:19:28.409Z" }, + { url = "https://files.pythonhosted.org/packages/70/d2/16d99a0c4948febc0ebd133a13b2f688ff7f8cb04da971e1128872ce0c03/cffi-2.1.1-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12", size = 183838, upload-time = "2026-08-03T21:19:29.637Z" }, + { url = "https://files.pythonhosted.org/packages/cd/95/31b535a9f0220ae9f357de4a08d57ce89cb417653c2fd9f075f50822a388/cffi-2.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1", size = 184168, upload-time = "2026-08-03T21:19:30.764Z" }, + { url = "https://files.pythonhosted.org/packages/ad/5a/4707a0dc1f203f5dde5a907b0d4e3c25d71120241048bd5bc6f1bb9d4e71/cffi-2.1.1-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0", size = 211805, upload-time = "2026-08-03T21:19:31.867Z" }, + { url = "https://files.pythonhosted.org/packages/ad/66/c19feabb28485b6e0bbaaafa90837a1ef5d302e90f2178bd33f17a49879b/cffi-2.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813", size = 218716, upload-time = "2026-08-03T21:19:32.896Z" }, + { url = "https://files.pythonhosted.org/packages/a7/92/500760486c8baab49a7a8a58ba7fc3355ec3974b454b8a09e528efde9e1d/cffi-2.1.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990", size = 205569, upload-time = "2026-08-03T21:19:34.142Z" }, + { url = "https://files.pythonhosted.org/packages/a5/a7/a67c733254d6e7373f7822f8082d8d6beade791e0cf12a7611f376fa61c7/cffi-2.1.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af", size = 204907, upload-time = "2026-08-03T21:19:35.174Z" }, + { url = "https://files.pythonhosted.org/packages/f7/a4/4399daaf8f7dfee9d7c3327fdb0426ee041cc63edc358b93911ceb2bfc7a/cffi-2.1.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632", size = 217807, upload-time = "2026-08-03T21:19:36.286Z" }, + { url = "https://files.pythonhosted.org/packages/28/f7/dabe6da2466ecbd82dc62e7342dc6b1065dad990c06f00f0ede9ebf2a0ed/cffi-2.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd", size = 221252, upload-time = "2026-08-03T21:19:37.416Z" }, + { url = "https://files.pythonhosted.org/packages/ce/87/616202d8e51342c07d2534c510111c4cc37201775ce8f60802c9335d1edd/cffi-2.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a", size = 214214, upload-time = "2026-08-03T21:19:38.507Z" }, + { url = "https://files.pythonhosted.org/packages/b4/c6/ab025d75d2c26c19b087c0124e75ee31cb65032f4fe345d356d8c507ab97/cffi-2.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa", size = 219408, upload-time = "2026-08-03T21:19:39.809Z" }, + { url = "https://files.pythonhosted.org/packages/db/e2/7e8109f65445bdc673a7b54f02c677de462db75674220fd1335efc8eb598/cffi-2.1.1-cp311-cp311-win32.whl", hash = "sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3", size = 174470, upload-time = "2026-08-03T21:19:41.246Z" }, + { url = "https://files.pythonhosted.org/packages/73/c0/77ba02423c2f7d7091143c45cd49e0e6575c4c1967394bb542bd923a9b74/cffi-2.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0", size = 185096, upload-time = "2026-08-03T21:19:42.615Z" }, + { url = "https://files.pythonhosted.org/packages/7c/47/9f1f85f9672ceda4984dc6c4f8824e8558992a2972c3d3c81fb8eb28d4ba/cffi-2.1.1-cp311-cp311-win_arm64.whl", hash = "sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455", size = 179941, upload-time = "2026-08-03T21:19:43.747Z" }, + { url = "https://files.pythonhosted.org/packages/10/69/43965eccfdead3b9220015fd1320e117be8c6ed01a62ffab76eeb752f5d5/cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0", size = 184821, upload-time = "2026-08-03T21:19:44.887Z" }, + { url = "https://files.pythonhosted.org/packages/54/7d/16e5a096677b5e313ca80cd5e5170efa3ea44624a82bb111925522da64b1/cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf", size = 184719, upload-time = "2026-08-03T21:19:46.129Z" }, + { url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" }, + { url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" }, + { url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" }, + { url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" }, + { url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" }, + { url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" }, + { url = "https://files.pythonhosted.org/packages/80/fb/0bb75b7039588c074b37ae99f40d9bfddf990ecb2fbc346ebccd2e56b9be/cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e", size = 175292, upload-time = "2026-08-03T21:19:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/d9/79/615cc094e2fb508cade7de88d3b4f6c4ec2bab695c97bce9153dc65aadf5/cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a", size = 185919, upload-time = "2026-08-03T21:19:56.89Z" }, + { url = "https://files.pythonhosted.org/packages/70/c6/d0ea84713fe46b243a436a18fcd47d639732747e21635c8a27191b06dc30/cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80", size = 180093, upload-time = "2026-08-03T21:19:58.155Z" }, + { url = "https://files.pythonhosted.org/packages/9d/f4/035513d4117049066b4779dc3b7c0c0fdad175fa13731c9f4003f1cd1478/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e", size = 194248, upload-time = "2026-08-03T21:19:59.399Z" }, + { url = "https://files.pythonhosted.org/packages/76/af/2aeb4dbb5fc41a04161ae9ff1518de7cec08e164f44a8ce6a4cf7fd2cd1d/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c", size = 196908, upload-time = "2026-08-03T21:20:00.746Z" }, + { url = "https://files.pythonhosted.org/packages/a7/46/2e5fdde8555706dd98139a910ca11be02809f3f605ce956f655d0214e100/cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6", size = 184805, upload-time = "2026-08-03T21:20:02.02Z" }, + { url = "https://files.pythonhosted.org/packages/55/41/4c7042f317b9217502988f0873af87e16ad606dc20f84e546e3e6ce9764c/cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971", size = 184764, upload-time = "2026-08-03T21:20:03.141Z" }, + { url = "https://files.pythonhosted.org/packages/43/1f/1c3d90d91811c8f86ced9ed637956c54bfe5b79ca98fe976d7f8c8979f6b/cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c", size = 214722, upload-time = "2026-08-03T21:20:04.377Z" }, + { url = "https://files.pythonhosted.org/packages/37/6f/3b5ce4c3b2192d250f04908f2bfd91ef34552ec8f7716a5d4abdb8d67bb2/cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125", size = 222369, upload-time = "2026-08-03T21:20:05.544Z" }, + { url = "https://files.pythonhosted.org/packages/02/10/4b3c75dde3d9663c9e02ba05c2668b954f671d4bbe346413ca8c696b295a/cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264", size = 210175, upload-time = "2026-08-03T21:20:06.75Z" }, + { url = "https://files.pythonhosted.org/packages/df/62/14f74b9543e605d17701dc797b815958b8bb70b7624ce1b832ddad48ed6c/cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3", size = 208670, upload-time = "2026-08-03T21:20:08.04Z" }, + { url = "https://files.pythonhosted.org/packages/95/95/86342356ff5953b3fb06f7ef7c5bee212d45e770abc7218d451b9148313c/cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2", size = 221824, upload-time = "2026-08-03T21:20:09.274Z" }, + { url = "https://files.pythonhosted.org/packages/eb/ff/7b3429ff53aafe931ed8a5fc69f481bbef7ba6de87ddcbb63d08f483f613/cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b", size = 225148, upload-time = "2026-08-03T21:20:10.7Z" }, + { url = "https://files.pythonhosted.org/packages/34/34/a95870b9221e09cf4f2ce3178b1a210abdfe63a1bd357da940418d7b8d15/cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7", size = 223564, upload-time = "2026-08-03T21:20:12.165Z" }, + { url = "https://files.pythonhosted.org/packages/70/ea/839b50531021a647fb5e929f72cf97bc1ff702b5472166164b5b6e76b851/cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac", size = 175263, upload-time = "2026-08-03T21:20:13.559Z" }, + { url = "https://files.pythonhosted.org/packages/60/a6/8b149b2c3f2e11aaa1618ef64500b45f50f22c57a977a4dff1aff1f91042/cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d", size = 185688, upload-time = "2026-08-03T21:20:14.69Z" }, + { url = "https://files.pythonhosted.org/packages/01/9a/11f687cb39d6a3504060d5242f04f48c735afb4d3d533958a20594890cb2/cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973", size = 180078, upload-time = "2026-08-03T21:20:15.917Z" }, + { url = "https://files.pythonhosted.org/packages/d3/7b/d6bbf82b8b96e7391438898c42f5bd96dd02030fd5b64937d248220003e2/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c", size = 194064, upload-time = "2026-08-03T21:20:17.148Z" }, + { url = "https://files.pythonhosted.org/packages/94/e6/bcc91b283be94735e268487a054004f0aa19947b6348fa367db53230abc8/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb", size = 196720, upload-time = "2026-08-03T21:20:18.268Z" }, + { url = "https://files.pythonhosted.org/packages/d9/99/c4b0c17cacdc9c3b8f280026286a9826d6a208c0f047591a3c3ce99b91fd/cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54", size = 184964, upload-time = "2026-08-03T21:20:19.708Z" }, + { url = "https://files.pythonhosted.org/packages/b3/a9/9db617d05d7367c1ad0ab00b3aa6e6f9281edd689b4ee9ea0e5a84e89c97/cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72", size = 184962, upload-time = "2026-08-03T21:20:20.833Z" }, + { url = "https://files.pythonhosted.org/packages/67/b8/b42132ca113dc567d37684437b46ca1dafc885902b02a110a02d5b511857/cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1", size = 222328, upload-time = "2026-08-03T21:20:22.118Z" }, + { url = "https://files.pythonhosted.org/packages/80/10/c5c0cbf0a657aecf59ef511409734230bf556f05a0d6c9eed7aa5c0a0166/cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062", size = 209985, upload-time = "2026-08-03T21:20:23.401Z" }, + { url = "https://files.pythonhosted.org/packages/d5/6c/bfa0b87b03b9238148beca990292843c9396ba069b54496596594173de7b/cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03", size = 208530, upload-time = "2026-08-03T21:20:24.628Z" }, + { url = "https://files.pythonhosted.org/packages/e9/02/4e7d553a7ac4b4238b38b3c1b80d486e9d4436f8d2acbf87a0997fe3f402/cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96", size = 221525, upload-time = "2026-08-03T21:20:25.758Z" }, + { url = "https://files.pythonhosted.org/packages/82/1d/a4aaf9babd75acb4d5f223bff71533bee748dd770a382619a798960ee9ba/cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527", size = 225053, upload-time = "2026-08-03T21:20:26.985Z" }, + { url = "https://files.pythonhosted.org/packages/81/10/5dc0e7bdd18e22107054288283380fc97a06ae3f1656a106908d666a3c88/cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13", size = 223213, upload-time = "2026-08-03T21:20:28.277Z" }, + { url = "https://files.pythonhosted.org/packages/0b/e9/d0061c364cde06ee43168a0d076ac1da512cbc380d44767b844ba34fe2b6/cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c", size = 177682, upload-time = "2026-08-03T21:20:44.288Z" }, + { url = "https://files.pythonhosted.org/packages/a7/06/1c3e01e3ba14c39f6d10bfbac52753b7e22259e38088e5cfe1d704918690/cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48", size = 187949, upload-time = "2026-08-03T21:20:45.623Z" }, + { url = "https://files.pythonhosted.org/packages/87/5b/da4e39efe18eeb89cf580ea9cfc66b6a7c3eadb808fc0cc1d3a295cb5a5d/cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836", size = 182947, upload-time = "2026-08-03T21:20:46.955Z" }, + { url = "https://files.pythonhosted.org/packages/23/59/40338bf421c5accea1d45158170c87006ef1cd371b05c077e76476949728/cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3", size = 188504, upload-time = "2026-08-03T21:20:29.495Z" }, + { url = "https://files.pythonhosted.org/packages/7d/47/5ecf1023850036e674c77ec4de86182d309ae344e39e7cba984b7df5d647/cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2", size = 188259, upload-time = "2026-08-03T21:20:31.291Z" }, + { url = "https://files.pythonhosted.org/packages/2a/9c/92934c3bea9f785b23eba304538c0b4d37a2a96d2431eb3a1bc87a11aa19/cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94", size = 223864, upload-time = "2026-08-03T21:20:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/4d/45/ba4c93527bc38616a8bd36488acb69a2212d60486794f0c1f318949bbb76/cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc", size = 211538, upload-time = "2026-08-03T21:20:33.808Z" }, + { url = "https://files.pythonhosted.org/packages/80/e9/b6ef565e452acb932fb0cb5443f44a78efbd1233e566f02b5a83855e9115/cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29", size = 210688, upload-time = "2026-08-03T21:20:34.974Z" }, + { url = "https://files.pythonhosted.org/packages/9a/95/eff5f0cee78d2eabc7eebffec40d3fc1876b5f3c95582e018bb4b99601f2/cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676", size = 223803, upload-time = "2026-08-03T21:20:36.564Z" }, + { url = "https://files.pythonhosted.org/packages/fa/01/579d39fb8bef00a335a23d83757b44feb24cd6345a2c451b64cb67b9c362/cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e", size = 226763, upload-time = "2026-08-03T21:20:37.816Z" }, + { url = "https://files.pythonhosted.org/packages/8d/b0/0b44f47c60b01b57b6e2bbd92343f13a85a1d93bc46ccf6e47e244acd99c/cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f", size = 225688, upload-time = "2026-08-03T21:20:38.959Z" }, + { url = "https://files.pythonhosted.org/packages/eb/d2/3b7176cb570a1d3e27faf67b72f591af508036e0d8b2be2ef9af9e8c84bb/cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4", size = 182868, upload-time = "2026-08-03T21:20:40.388Z" }, + { url = "https://files.pythonhosted.org/packages/56/78/31f00c1bcd97c9bbf55f1bfdf5bc809a5de8887473e90bb9960dca825e80/cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e", size = 194104, upload-time = "2026-08-03T21:20:41.725Z" }, + { url = "https://files.pythonhosted.org/packages/7b/1b/58496f2ed0a35de575250c02a43ab3cc2c04d494a88fed31c1cabc0fd176/cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5", size = 186402, upload-time = "2026-08-03T21:20:43.042Z" }, + { url = "https://files.pythonhosted.org/packages/c1/8f/9ebe220eab48a093d1a5a5e339ab0dc7316eef3bb04d63c42f0251b61f50/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d", size = 194043, upload-time = "2026-08-03T21:20:48.179Z" }, + { url = "https://files.pythonhosted.org/packages/ff/69/844bad3ece306c4782c2ecb93597035b6690d48704b803914c199da1e8b3/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b", size = 196737, upload-time = "2026-08-03T21:20:49.457Z" }, + { url = "https://files.pythonhosted.org/packages/1b/8a/af668013284634733f02d683458a0728739c7d6ddb5e14cb0c20832266fe/cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4", size = 184933, upload-time = "2026-08-03T21:20:50.639Z" }, + { url = "https://files.pythonhosted.org/packages/0c/75/2f5207ff6d1a613133b23a5203cc0c2a628313b5eb3974d7956ae3c57950/cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8", size = 185002, upload-time = "2026-08-03T21:20:52.173Z" }, + { url = "https://files.pythonhosted.org/packages/e2/31/9e1313b0a6e30e91b3b3d3fff51ae99c857c07738e3afcce1f7334e1b7ab/cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6", size = 222271, upload-time = "2026-08-03T21:20:53.462Z" }, + { url = "https://files.pythonhosted.org/packages/50/e3/f6234a833e6e08c7007003074723c406559eecf9b48dfc97471e5a8eb7a0/cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80", size = 209919, upload-time = "2026-08-03T21:20:54.783Z" }, + { url = "https://files.pythonhosted.org/packages/0d/fc/5f74e293fced6edb51af3a46c4ccf6c23c9943774ecb375ddbd522c76add/cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779", size = 208529, upload-time = "2026-08-03T21:20:56.066Z" }, + { url = "https://files.pythonhosted.org/packages/44/16/29e6d01b388bef055ecd6ca8244b3f4d336bd09e92d5d892187b9601084e/cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399", size = 221630, upload-time = "2026-08-03T21:20:57.336Z" }, + { url = "https://files.pythonhosted.org/packages/a4/18/fa7f1f6857d5eb88a4ca99ffcbfb7c387a287ccc154c64a73e86314745d7/cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688", size = 225134, upload-time = "2026-08-03T21:20:58.675Z" }, + { url = "https://files.pythonhosted.org/packages/e0/9f/e8e3dfa04a1b4c241f8c91faacad872b4d4efd051d49764ad4e2fd4b9fea/cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7", size = 223197, upload-time = "2026-08-03T21:20:59.968Z" }, + { url = "https://files.pythonhosted.org/packages/f8/7e/8debeb04f1ab9fe2a6963964cd6f1aaf7192627b83926586a6a4e089c9fa/cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac", size = 177683, upload-time = "2026-08-03T21:21:14.901Z" }, + { url = "https://files.pythonhosted.org/packages/e0/31/5158704cc474ab65c1647932e88be78dc0873f47130e253be38bcaf13d01/cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960", size = 187897, upload-time = "2026-08-03T21:21:16.108Z" }, + { url = "https://files.pythonhosted.org/packages/cc/4b/b3a2da8570c704ffc0f9762cdc3ec0f02c8573798e0b5cf7f11c82bbb70f/cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1", size = 182935, upload-time = "2026-08-03T21:21:17.271Z" }, + { url = "https://files.pythonhosted.org/packages/d0/ef/5443574510a1207e6f6bc38ba6e1f1de36cb48fef07b2728bb896a21f430/cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc", size = 188464, upload-time = "2026-08-03T21:21:01.163Z" }, + { url = "https://files.pythonhosted.org/packages/7e/ae/a56fa8c4686ad50e148fcbc8d3ae0d03915ff5c30d795058988c24118cef/cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab", size = 188262, upload-time = "2026-08-03T21:21:02.382Z" }, + { url = "https://files.pythonhosted.org/packages/53/b2/6187f46f2912276a3ae284076109cc5c8680482f11f766ccf26db4a86427/cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e", size = 223779, upload-time = "2026-08-03T21:21:03.553Z" }, + { url = "https://files.pythonhosted.org/packages/8a/f6/c3ad28bd19f77047a03084424fbd4cbe997303267c14423737324be0385d/cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358", size = 211520, upload-time = "2026-08-03T21:21:04.863Z" }, + { url = "https://files.pythonhosted.org/packages/a0/cd/ccac9013a5bd9fd764de118674ab9c805b5ca10c19270d90ee273f8b2240/cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231", size = 210673, upload-time = "2026-08-03T21:21:06.223Z" }, + { url = "https://files.pythonhosted.org/packages/52/86/2976131c639aead931c5bee5aba67e4b09fbeb8018b6f282f70803f923a7/cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6", size = 223835, upload-time = "2026-08-03T21:21:07.539Z" }, + { url = "https://files.pythonhosted.org/packages/ac/0c/33a7aeab2f9c76918c52e084beb39c570db3588133412929e8ec06fab90b/cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94", size = 226705, upload-time = "2026-08-03T21:21:08.774Z" }, + { url = "https://files.pythonhosted.org/packages/e3/26/2cde30fdde421130bfc18f70395731a6e6b2053c6a1978a5258ff04e72fa/cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5", size = 225539, upload-time = "2026-08-03T21:21:09.911Z" }, + { url = "https://files.pythonhosted.org/packages/6d/cd/a361394c94b2129d604bb846f624a8e88255a3ee33129c434a00d715e64f/cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66", size = 182707, upload-time = "2026-08-03T21:21:11.226Z" }, + { url = "https://files.pythonhosted.org/packages/9b/b5/ba2b299993c26577d529b6ae29841f9e15b9fcf004d65f423f4fcf94ade9/cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3", size = 193772, upload-time = "2026-08-03T21:21:12.39Z" }, + { url = "https://files.pythonhosted.org/packages/aa/29/35e016098c814cd93de9cd320c66b5bfba14dc6ecedd3cb518fa7c408c69/cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692", size = 186360, upload-time = "2026-08-03T21:21:13.636Z" }, +] + +[[package]] +name = "click" +version = "8.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/d4/81420972a676e8ffea40450d8c8c92943e7218a78fe9b64359836cc9876b/click-8.4.2.tar.gz", hash = "sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6", size = 338000, upload-time = "2026-06-24T17:45:15.148Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/e2/79c688af8b210d232694e31e59da9f6ec747bae31c3f5946e4e9b98860d5/click-8.4.2-py3-none-any.whl", hash = "sha256:e6f9f66136c816745b9d65817da91d61d957fb16e02e4dcd0552553c5a197b76", size = 119243, upload-time = "2026-06-24T17:45:13.73Z" }, +] + [[package]] name = "colorama" version = "0.4.6" @@ -147,17 +309,78 @@ toml = [ { name = "tomli", marker = "python_full_version <= '3.11'" }, ] +[[package]] +name = "cryptography" +version = "50.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/de/41/6cbdcf9142d00fe82836fbb51e503e58088575cf7a0fe1dbff6695bf0840/cryptography-50.0.0.tar.gz", hash = "sha256:eeac2acb5a20ed25e0ad6d1df9891a520b78b404266b6d11778f25d5d691a6c9", size = 880201, upload-time = "2026-07-31T14:25:10.11Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c5/5c/59086b4aac5e879d38ddbcf74e4be7ade89cebc3eb199a55da998c3bb46a/cryptography-50.0.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:031e2d5dd4bb9caa3ca9c82e5a197fd8ae680232cee62603d1a813f3f07e3d03", size = 4001252, upload-time = "2026-07-31T14:23:33.331Z" }, + { url = "https://files.pythonhosted.org/packages/57/ef/8f2df13c7216bcad3e1c74e07f6e193d93e998e114f524a53877c9af27ad/cryptography-50.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fd9192b7b70c573d7f214eb1ae35e00d359f6f5e4b27c7e21e30de1fc6204645", size = 4719554, upload-time = "2026-07-31T14:23:35.611Z" }, + { url = "https://files.pythonhosted.org/packages/d9/41/029086c34d91052fc3b88bcc8056f709a7c915c7a23b235a54eb800b1c97/cryptography-50.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:06a32a980526a6ab9a4b9bf8f7385800791e2bb960903cb6b530e4817509a3b7", size = 4702130, upload-time = "2026-07-31T14:23:37.635Z" }, + { url = "https://files.pythonhosted.org/packages/7d/ff/b6ce0954962e7f7b969f850a883744197bb3910bdfd7b6da162eab7d9f68/cryptography-50.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a1b30560f2acc95aa8b2e06e716a13dbfc97314747b80d9707e307f77b40d6b3", size = 4725244, upload-time = "2026-07-31T14:23:39.471Z" }, + { url = "https://files.pythonhosted.org/packages/06/1e/63a1027cb7fec360a182208e1b7767d5aa1fe57be3d6aa856e69a321edc0/cryptography-50.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:8d89f3976b10b4ce31118de72329025f70d2c6ead14a8217c5514dd2c6d5a78f", size = 5342265, upload-time = "2026-07-31T14:23:41.286Z" }, + { url = "https://files.pythonhosted.org/packages/6b/72/a1116d683a6d7ece94590013882515de087edf9ef0e6292aae615a44df73/cryptography-50.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:b42a28c1844fd9de8f3f7d540e36b66f3a9c83fceac7170ebc7a6a19edd9dcae", size = 4734609, upload-time = "2026-07-31T14:23:43.139Z" }, + { url = "https://files.pythonhosted.org/packages/15/37/36a9c479bbe49acea2636c7fd3360d20f7b7e079c300352011c44850b181/cryptography-50.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:900131fafd8aead39ac7dd3a7e833be754c17a95cfd91221636949fe4eb0aa8a", size = 4356517, upload-time = "2026-07-31T14:23:44.939Z" }, + { url = "https://files.pythonhosted.org/packages/32/98/8a151d64367204cbc63ec65d37502f1d9c53cf4bfc6ec3c532614dbec60d/cryptography-50.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:07949c449a1abcf60d1ee6e88956d89404c7df3c8258f46589e912988e551987", size = 4724529, upload-time = "2026-07-31T14:23:46.93Z" }, + { url = "https://files.pythonhosted.org/packages/22/f6/ec13b470172126464a86bf54d2294a46d29837fc51ba3e45d4047946fb5e/cryptography-50.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f89831ef99dd7dd169ab06d63a831adb9e20a87aac6d380266bbda5823349169", size = 5299852, upload-time = "2026-07-31T14:23:48.851Z" }, + { url = "https://files.pythonhosted.org/packages/da/3a/f05e32c99d440c9bb891ea0e36c9091891e36be5a9a87ab2ee6ea20729f6/cryptography-50.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:82148ec5bddac30b51a5b3c1945075f896fa022cb93f8e4a01e9f6ee95292c5f", size = 4734462, upload-time = "2026-07-31T14:23:50.861Z" }, + { url = "https://files.pythonhosted.org/packages/ca/dc/bd72b26be8953f80625f63151efd38eee71c76ca6cf591c08ff34615a79e/cryptography-50.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1489e263a8048bb8b6a8bac662eb2d402ea5d2b7b4699b72f385f1e2772db105", size = 4852708, upload-time = "2026-07-31T14:23:52.715Z" }, + { url = "https://files.pythonhosted.org/packages/27/20/c930314a2ab476d15dec966ec87e2e9637bb02b06106b12c0396c57bb603/cryptography-50.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7cec5b856506da6defb290f30c9ee687d5f5e8cb0bd3f6459dde43b0b4fa40ef", size = 5004179, upload-time = "2026-07-31T14:23:54.887Z" }, + { url = "https://files.pythonhosted.org/packages/32/2e/c9db68a0c4bfa28e310707527c0ee3a2bd254104d2e02e68f368e197aa4c/cryptography-50.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:bd1c592e4d5974f0d08d4888e432157adba757c66da0246918e43677fafa2d30", size = 3840395, upload-time = "2026-07-31T14:23:56.677Z" }, + { url = "https://files.pythonhosted.org/packages/c3/fb/951032a3bf22a5697c83183fb6294a4843772947a70e616c57b3ff5f522e/cryptography-50.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:49e7d93abdbd2990caced757e5fade25302f719c3c8fb6e6fff2dde98999fc41", size = 3989258, upload-time = "2026-07-31T14:23:58.881Z" }, + { url = "https://files.pythonhosted.org/packages/d4/67/91eb047e69c5e845f2f14b8a2e4a1aab0f283cb885531e9e22c8adb176bc/cryptography-50.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:19736989797678c6af1e55cd49055cdbcb55d8f6b5583ac5335f933aba9101dc", size = 4700648, upload-time = "2026-07-31T14:24:00.702Z" }, + { url = "https://files.pythonhosted.org/packages/30/82/85f0f7425c856b9f96459411eb12e74ef72df9caf6f8f15bf23a33ff131f/cryptography-50.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:80b63928fa35083b33966ce1efb70e5b9607181e49dcd1c22c8c005e319f667f", size = 4682442, upload-time = "2026-07-31T14:24:02.538Z" }, + { url = "https://files.pythonhosted.org/packages/1a/28/b555a365adff1cca2fbe7b9e487d68a40de6bc67ff2cb587473eb43de0e7/cryptography-50.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:d58c3db7cd6eed54e6c06744db55456b65ebd7492ddeae9c1e93cfca7aa857d3", size = 4707596, upload-time = "2026-07-31T14:24:04.394Z" }, + { url = "https://files.pythonhosted.org/packages/72/d8/f52538140cc719df62a01cf87d1c7142318d235817109d6f4054d7c352d6/cryptography-50.0.0-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:df2a58a472f332225671c35b0a830208b86d004f82baa8530fa3782c85646533", size = 5314552, upload-time = "2026-07-31T14:24:06.31Z" }, + { url = "https://files.pythonhosted.org/packages/38/14/6120e5bd7c5aa022ad15424ba4d5c5269d0d9448ed4d55e492ea91e3c1c4/cryptography-50.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:11b74db56cdbe3cdee6e3f6982ecb70334fa10dce99ed58bf7894aaaa3b2a037", size = 4717113, upload-time = "2026-07-31T14:24:08.349Z" }, + { url = "https://files.pythonhosted.org/packages/fa/71/190bf38c3ee2e0f8efc9860ae100c9df4169742eef274b91e7aa1cb133b9/cryptography-50.0.0-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:f59e38625469987d7ef6d495323c55e7db6c212eaf6112267e0d3b565a2e9c9f", size = 4338580, upload-time = "2026-07-31T14:24:10.227Z" }, + { url = "https://files.pythonhosted.org/packages/3a/63/504ccfbbe61fd8aa983f7f146399cdf034c72c2fc55f5b2dfdcdcdb20c99/cryptography-50.0.0-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:ecfed7367f965a0328cfbdd70da860f15441f002f613185668c6e6ebf5a0ac11", size = 4707038, upload-time = "2026-07-31T14:24:12.169Z" }, + { url = "https://files.pythonhosted.org/packages/01/77/2cf79bbfc4d12ca106437a6e170d6aaa01a373e93093118aaaef0e801bd4/cryptography-50.0.0-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:9aa87839c383bdbab6ef865787a1fb877af8dd03464c4400322726feaaadfc6d", size = 5273110, upload-time = "2026-07-31T14:24:14.38Z" }, + { url = "https://files.pythonhosted.org/packages/e5/45/8aae2972c520145377ea3559a605a899bebe227bf070b33cdb445929a9b9/cryptography-50.0.0-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:6ba6a53445bd3cfa809ef3ef5f1589aa6ba08784a1d962bf47d0940e871dab1c", size = 4716439, upload-time = "2026-07-31T14:24:16.415Z" }, + { url = "https://files.pythonhosted.org/packages/7b/20/4fe50b619a48c2525cc46e2dbc1ac490708d704be5d467bdaac6dc955682/cryptography-50.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:3f5735ffe4996d28b809371756219f5354864902a3b9e7c0b9ee87041209fc9c", size = 4837383, upload-time = "2026-07-31T14:24:18.553Z" }, + { url = "https://files.pythonhosted.org/packages/92/91/3a31366e183343d3703f8995c095f5734676bd6938118047e50fcf279eb4/cryptography-50.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:1b4a266766514614f8aa60416e71f2fc6e575d36e7bdc90f644fadb2f4b75b95", size = 4985772, upload-time = "2026-07-31T14:24:20.385Z" }, + { url = "https://files.pythonhosted.org/packages/74/9a/02ffe35b2853d121689871eb5dce862092562b3a1ed5cc98f1aaed441506/cryptography-50.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:12b9c6996425c76ea6c457ace4f3073e715b8c545add07cd1a8f3a4f90691269", size = 3816291, upload-time = "2026-07-31T14:24:22.125Z" }, + { url = "https://files.pythonhosted.org/packages/03/37/73d005be173aff344af30e9fd2a576575cb2391a7101d9cd3842e1fa8cce/cryptography-50.0.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:ccdc4a71a4dabae05de219404f9f4abc38e3b58422177ff93d0da05967dafa07", size = 4036009, upload-time = "2026-07-31T14:24:24.122Z" }, + { url = "https://files.pythonhosted.org/packages/ff/c6/7a6202a534e32103a285b7834a120869557fe198d51d7cfe59754c8bda9c/cryptography-50.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:910e1d2668e7de9648f2bcee30e180db2a6b15c30f887d7c4c93ddf96e3992e3", size = 4745252, upload-time = "2026-07-31T14:24:26.118Z" }, + { url = "https://files.pythonhosted.org/packages/85/4f/0fa8c2f4428198f15d9ff8d63400e27afbf94ce833f6108da1eb3753f945/cryptography-50.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a91296cb61e8df6f86d0c19cc4068228da256bf59bf86049fbd821084565327f", size = 4728939, upload-time = "2026-07-31T14:24:27.994Z" }, + { url = "https://files.pythonhosted.org/packages/d1/63/54dd723490ba2dc09b299682c10b38db38f159728bcaae8c591b8af2f22d/cryptography-50.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:e722f16708d854fe924790e051061f6704a472c3bac347b6fd88033ea8dd0dc5", size = 4748483, upload-time = "2026-07-31T14:24:30.254Z" }, + { url = "https://files.pythonhosted.org/packages/1d/dd/7c77d26285cc7f6991efce64a0f5b4f9383bfa5dd8c5033003eaf7db4cdb/cryptography-50.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:d764dcf130c428ef66786f866dd750f53182bc608813489915e9fc106bb0c82f", size = 5367599, upload-time = "2026-07-31T14:24:32.457Z" }, + { url = "https://files.pythonhosted.org/packages/46/c9/f60aed34c013f317f92817b6c171c2d22a78270fa41109bd4b08af26b194/cryptography-50.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:105110f43a471dbd0060b9c9516cb8a6a79233631a04cc2ba16f28323ac6e025", size = 4762647, upload-time = "2026-07-31T14:24:34.599Z" }, + { url = "https://files.pythonhosted.org/packages/be/f3/f9a0173b139372c3a48ed98154b45cc6b9de17c789d5ab552e621c293609/cryptography-50.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:828743d939e9629bc267b8e2d08d8bb67cd4319c771a33d4b18b22dd8fb7440a", size = 4385197, upload-time = "2026-07-31T14:24:36.647Z" }, + { url = "https://files.pythonhosted.org/packages/d8/36/83bb81f6e569bc38e1e4a7bc80f29b46bb9601920bc455fc8e888f5d5742/cryptography-50.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:2a8183b489dc1f7f80f135780fadc1108f14b31b8a40411c7a5b17425f65f28b", size = 4748095, upload-time = "2026-07-31T14:24:39.493Z" }, + { url = "https://files.pythonhosted.org/packages/6b/16/d3008eff98c764979865834c3d386d4fd041b5f52e7f34fc29ac1a5eb515/cryptography-50.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:6e7d61120573a7f2cd94cc095f9e81f6967c61ccdf194285aa143ecec8e0b708", size = 5325948, upload-time = "2026-07-31T14:24:41.556Z" }, + { url = "https://files.pythonhosted.org/packages/9c/f8/d97f9603efda3888187bfdb893f26c41be4735c10631d05d284ee6b047c4/cryptography-50.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:37fdb0d0111f1e2ff07139dfb79f1b49531f8e213c46f1163dd7642979b58c47", size = 4762400, upload-time = "2026-07-31T14:24:43.636Z" }, + { url = "https://files.pythonhosted.org/packages/64/a2/4615c8f7d81a00b1d6e6afe19f694e1543582349fb5f4076f6cb5dc36485/cryptography-50.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c87f62a3d3b9888ed0fdde100ec06aa61ca9cd44bad9057d1dff9a516b5f5bb9", size = 4878208, upload-time = "2026-07-31T14:24:45.522Z" }, + { url = "https://files.pythonhosted.org/packages/d2/1a/efcfb02f91407149a0dacffffab791f7e19bf6385f63b3666dc8b5e5c9c8/cryptography-50.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:65c2c3add92b45fd0709db8594536aea39c2a67af0e27ffcf049c498501140b7", size = 5037050, upload-time = "2026-07-31T14:24:47.697Z" }, + { url = "https://files.pythonhosted.org/packages/57/30/4a22984d4f1bdfb8c054f07a92bc176b97a3134cc1d6c4b3bffb1f3688b4/cryptography-50.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:d24fead1d4d076e1bfb006dcec392074a3cd8d7b4fc8a595aa64073b2b7a96ba", size = 3874135, upload-time = "2026-07-31T14:24:50.085Z" }, + { url = "https://files.pythonhosted.org/packages/9d/3e/e54cde8c01631a5a8226ccd617eab9e57fd5cfdad90f1a9e6bb570794631/cryptography-50.0.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:5e34edd123674534acd70147f0ca331eaa2c74e6325fb2028c886aa26ba0b68c", size = 3963170, upload-time = "2026-07-31T14:24:51.968Z" }, + { url = "https://files.pythonhosted.org/packages/01/b6/0b9e125e90f3d2dcf599a218a899cda7326a3158cfa258723f0b398b08f6/cryptography-50.0.0-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:8eb5e1172eb569ea8a872796576e6a67c276351728b6455d5beb01242b027c6a", size = 4692441, upload-time = "2026-07-31T14:24:53.743Z" }, + { url = "https://files.pythonhosted.org/packages/53/c9/a5151588710785a96d7bc4de27d4cd62f263bbbcb203cfe29df537eb6505/cryptography-50.0.0-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:910d11e1a385c654bf738bf3e6b8e6ed5de0f5610fcae2be9e5b398d8081d20e", size = 4699810, upload-time = "2026-07-31T14:24:55.746Z" }, + { url = "https://files.pythonhosted.org/packages/c7/1a/15b92b25eb6ce3089cd49377ae990a0f3ad485a510f968aed1f19dbdcdf2/cryptography-50.0.0-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:62598a8a57f815db4c6259a4e97d857dab56697e7de8e8ab02352ab74da1995d", size = 4691924, upload-time = "2026-07-31T14:24:58.082Z" }, + { url = "https://files.pythonhosted.org/packages/62/15/219075012ab13e8905f3cd572204f4acb4b111df787104346b9bc0cea789/cryptography-50.0.0-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:07479a1cb08219ab719147e742e76090c9c773321959bb94946fffdd397a6437", size = 4699593, upload-time = "2026-07-31T14:24:59.951Z" }, + { url = "https://files.pythonhosted.org/packages/8e/b5/c2c5fce26f0ee40d21bafe7f191d29a34b35a65ac4fe8a1191d1983612e9/cryptography-50.0.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:c99c003e088647b8a5b7c145d6f78c335f6348332b62e142d411c4b63d1460b9", size = 3813796, upload-time = "2026-07-31T14:25:02.298Z" }, +] + [[package]] name = "droid-sdk" version = "0.1.3" source = { editable = "." } dependencies = [ + { name = "mcp" }, { name = "pydantic" }, + { name = "starlette" }, + { name = "uvicorn" }, ] [package.dev-dependencies] dev = [ { name = "mypy" }, + { name = "pyright" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-cov" }, @@ -165,11 +388,17 @@ dev = [ ] [package.metadata] -requires-dist = [{ name = "pydantic", specifier = ">=2.0" }] +requires-dist = [ + { name = "mcp", specifier = ">=1.27,<2" }, + { name = "pydantic", specifier = ">=2.0" }, + { name = "starlette", specifier = ">=0.40" }, + { name = "uvicorn", specifier = ">=0.31,<1" }, +] [package.metadata.requires-dev] dev = [ { name = "mypy" }, + { name = "pyright" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-cov" }, @@ -181,13 +410,68 @@ name = "exceptiongroup" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" }, ] +[[package]] +name = "h11" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, +] + +[[package]] +name = "httpcore" +version = "1.0.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, +] + +[[package]] +name = "httpx" +version = "0.28.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "certifi" }, + { name = "httpcore" }, + { name = "idna" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, +] + +[[package]] +name = "httpx-sse" +version = "0.4.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0f/4c/751061ffa58615a32c31b2d82e8482be8dd4a89154f003147acee90f2be9/httpx_sse-0.4.3.tar.gz", hash = "sha256:9b1ed0127459a66014aec3c56bebd93da3c1bc8bb6618c8082039a44889a755d", size = 15943, upload-time = "2025-10-10T21:48:22.271Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d2/fd/6668e5aec43ab844de6fc74927e155a3b37bf40d7c3790e49fc0406b6578/httpx_sse-0.4.3-py3-none-any.whl", hash = "sha256:0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc", size = 8960, upload-time = "2025-10-10T21:48:21.158Z" }, +] + +[[package]] +name = "idna" +version = "3.18" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/63/9496c57188a2ee585e0f1db071d75089a11e98aa86eb99d9d7618fc1edce/idna-3.18.tar.gz", hash = "sha256:ffb385a7e039654cef1ab9ef32c6fafe283c0c0467bba1d9029738ce4a14a848", size = 196711, upload-time = "2026-06-02T14:34:07.794Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/5e/d4e9f1a599fb8e573b7b87160658329fbf28d19eac2718f51fc3def3aa5a/idna-3.18-py3-none-any.whl", hash = "sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2", size = 65455, upload-time = "2026-06-02T14:34:06.319Z" }, +] + [[package]] name = "iniconfig" version = "2.3.0" @@ -197,6 +481,34 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] +[[package]] +name = "jsonschema" +version = "4.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "jsonschema-specifications" }, + { name = "referencing" }, + { name = "rpds-py", version = "0.30.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "rpds-py", version = "2026.6.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b3/fc/e067678238fa451312d4c62bf6e6cf5ec56375422aee02f9cb5f909b3047/jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326", size = 366583, upload-time = "2026-01-07T13:41:07.246Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce", size = 90630, upload-time = "2026-01-07T13:41:05.306Z" }, +] + +[[package]] +name = "jsonschema-specifications" +version = "2025.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "referencing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/74/a633ee74eb36c44aa6d1095e7cc5569bebf04342ee146178e2d36600708b/jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d", size = 32855, upload-time = "2025-09-08T01:34:59.186Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" }, +] + [[package]] name = "librt" version = "0.8.1" @@ -282,6 +594,31 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b2/c8/d148e041732d631fc76036f8b30fae4e77b027a1e95b7a84bb522481a940/librt-0.8.1-cp314-cp314t-win_arm64.whl", hash = "sha256:bf512a71a23504ed08103a13c941f763db13fb11177beb3d9244c98c29fb4a61", size = 48755, upload-time = "2026-02-17T16:12:47.943Z" }, ] +[[package]] +name = "mcp" +version = "1.29.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "httpx" }, + { name = "httpx-sse" }, + { name = "jsonschema" }, + { name = "pydantic" }, + { name = "pydantic-settings" }, + { name = "pyjwt", extra = ["crypto"] }, + { name = "python-multipart" }, + { name = "pywin32", marker = "sys_platform == 'win32'" }, + { name = "sse-starlette" }, + { name = "starlette" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, + { name = "uvicorn", marker = "sys_platform != 'emscripten'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/30/d3/f9acc21dfc886e4f78e2add1a47db46ce16884346afde53f8a064c02c891/mcp-1.29.0.tar.gz", hash = "sha256:52d01f334de1868cc3bb2d6604931126a67631f99a6c5d3b82ba47290315ec36", size = 643148, upload-time = "2026-07-28T13:41:41.939Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/01/c8/248b201f6d753d69fd5d6506011abbb35a946d9142b2ae311a948fd0be3d/mcp-1.29.0-py3-none-any.whl", hash = "sha256:f5a075bb611f23d6f4d080c6a1699fa62772eebc562ba9e66b306ddde1c755f7", size = 223436, upload-time = "2026-07-28T13:41:40.337Z" }, +] + [[package]] name = "mypy" version = "1.19.1" @@ -337,6 +674,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" }, ] +[[package]] +name = "nodeenv" +version = "1.10.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/24/bf/d1bda4f6168e0b2e9e5958945e01910052158313224ada5ce1fb2e1113b8/nodeenv-1.10.0.tar.gz", hash = "sha256:996c191ad80897d076bdfba80a41994c2b47c68e224c542b48feba42ba00f8bb", size = 55611, upload-time = "2025-12-20T14:08:54.006Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/b2/d0896bdcdc8d28a7fc5717c305f1a861c26e18c05047949fb371034d98bd/nodeenv-1.10.0-py2.py3-none-any.whl", hash = "sha256:5bb13e3eed2923615535339b3c620e76779af4cb4c6a90deccc9e36b274d3827", size = 23438, upload-time = "2025-12-20T14:08:52.782Z" }, +] + [[package]] name = "packaging" version = "26.0" @@ -364,6 +710,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] +[[package]] +name = "pycparser" +version = "3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" }, +] + [[package]] name = "pydantic" version = "2.12.5" @@ -497,6 +852,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/36/c7/cfc8e811f061c841d7990b0201912c3556bfeb99cdcb7ed24adc8d6f8704/pydantic_core-2.41.5-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:56121965f7a4dc965bff783d70b907ddf3d57f6eba29b6d2e5dabfaf07799c51", size = 2145302, upload-time = "2025-11-04T13:43:46.64Z" }, ] +[[package]] +name = "pydantic-settings" +version = "2.15.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, + { name = "python-dotenv" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/68/ca/31c57507b13119d7d3cfa1576dad2911a4861e3be07b579395f4e9d393f9/pydantic_settings-2.15.0.tar.gz", hash = "sha256:694b793e84f766ba76a90ebdefc01d0a9a045dab0382bee70393da93712ad117", size = 261253, upload-time = "2026-08-07T09:24:57.419Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/30/a4/2bffa9f8e804325a09867f0e9d30795c80ea9f8d62560bd1b6ad6220eb2f/pydantic_settings-2.15.0-py3-none-any.whl", hash = "sha256:0ba092c291c94baceb5eff768aa0d56400a457585bc0175925a5a5510303da42", size = 69413, upload-time = "2026-08-07T09:24:55.839Z" }, +] + [[package]] name = "pygments" version = "2.19.2" @@ -506,6 +875,36 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c7/21/705964c7812476f378728bdf590ca4b771ec72385c533964653c68e86bdc/pygments-2.19.2-py3-none-any.whl", hash = "sha256:86540386c03d588bb81d44bc3928634ff26449851e99741617ecb9037ee5ec0b", size = 1225217, upload-time = "2025-06-21T13:39:07.939Z" }, ] +[[package]] +name = "pyjwt" +version = "2.13.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3b/81/58d0ac84e1ef3a3843791d6954d94c0b33d526c75eeb1efbce9d0a4c4077/pyjwt-2.13.0.tar.gz", hash = "sha256:41571c89ca91598c79e8ef18a2d07367d4810fbbd6f637794879baf1b7703423", size = 107515, upload-time = "2026-05-21T19:54:36.618Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a3/5e/ecf12fdb62546d64385c158514e9b2b671f7832108ef2ecd2020ce0af2d1/pyjwt-2.13.0-py3-none-any.whl", hash = "sha256:66adcc2aff09b3f1bbd95fc1e1577df8ac8723c978552fd43304c8a290ac5728", size = 31274, upload-time = "2026-05-21T19:54:35.362Z" }, +] + +[package.optional-dependencies] +crypto = [ + { name = "cryptography" }, +] + +[[package]] +name = "pyright" +version = "1.1.411" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nodeenv" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7e/ab/265f7dc69d28113ebba19092e57b075f41543b2ed048429c5f56e2b88eac/pyright-1.1.411.tar.gz", hash = "sha256:d885a0551f2e763b089a02702174e7f4ba77548cddabc972ab86d1f7f1b0f998", size = 4112861, upload-time = "2026-06-25T02:14:06.37Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/49/385be530a6a5b78d1cbcd5c2e38debc8959a2fc6bdb716f4e581002979fc/pyright-1.1.411-py3-none-any.whl", hash = "sha256:dc7c72a8e2700c55baa127554040e067041ea53ccfd50bf96308cc4291c7d5d9", size = 6181526, upload-time = "2026-06-25T02:14:04.691Z" }, +] + [[package]] name = "pytest" version = "9.0.2" @@ -552,6 +951,319 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" }, ] +[[package]] +name = "python-dotenv" +version = "1.2.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/82/ed/0301aeeac3e5353ef3d94b6ec08bbcabd04a72018415dcb29e588514bba8/python_dotenv-1.2.2.tar.gz", hash = "sha256:2c371a91fbd7ba082c2c1dc1f8bf89ca22564a087c2c287cd9b662adde799cf3", size = 50135, upload-time = "2026-03-01T16:00:26.196Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/d7/1959b9648791274998a9c3526f6d0ec8fd2233e4d4acce81bbae76b44b2a/python_dotenv-1.2.2-py3-none-any.whl", hash = "sha256:1d8214789a24de455a8b8bd8ae6fe3c6b69a5e3d64aa8a8e5d68e694bbcb285a", size = 22101, upload-time = "2026-03-01T16:00:25.09Z" }, +] + +[[package]] +name = "python-multipart" +version = "0.0.32" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5b/42/55c32bb9b12693c092ad250a0e82edb5b31ddeda6eb772de5f308b3804ad/python_multipart-0.0.32.tar.gz", hash = "sha256:be54b7f3fa167bb83e4fcd936b887b708f4e57fe75911c02aebf53efaf8d938e", size = 46881, upload-time = "2026-06-04T16:18:58.647Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e1/04/e8135ebd1ad02c56ec633277529b2602ff99ff634be76cdba5744cf554fd/python_multipart-0.0.32-py3-none-any.whl", hash = "sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23", size = 30042, upload-time = "2026-06-04T16:18:57.319Z" }, +] + +[[package]] +name = "pywin32" +version = "312" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fe/1b/9cfdeac80ee45bebbbcb31f1b7b99a0d81a1c72de48d837be984e0e88b1d/pywin32-312-cp310-cp310-win32.whl", hash = "sha256:772235332b5d1024c696f11cea1ae4be7930f0a8b894bb43db14e3f435f1ff7e", size = 6361387, upload-time = "2026-06-04T07:49:14.329Z" }, + { url = "https://files.pythonhosted.org/packages/33/b1/7afc96d041d982c27bc2df6f853d43f01fd273e3d39d04be3647ddeb533d/pywin32-312-cp310-cp310-win_amd64.whl", hash = "sha256:5dbc35d2b5320dc07f25fa31269cfb767471002b17de5eb067d03da68c7cb2db", size = 6926780, upload-time = "2026-06-04T07:49:16.881Z" }, + { url = "https://files.pythonhosted.org/packages/ce/3a/4140da9ad54108e517f4a16b2d83da3033e08662144623e1239587cb7db6/pywin32-312-cp310-cp310-win_arm64.whl", hash = "sha256:3020656e34f1cf7faeb7bccd2b84653a607c6ff0c55ada85e6487d61716deabd", size = 4307203, upload-time = "2026-06-04T07:49:18.993Z" }, + { url = "https://files.pythonhosted.org/packages/1f/f5/10a6e845a00fc5e7afd0a988b744f403d4d57162a28d160a093c4d9322f0/pywin32-312-cp311-cp311-win32.whl", hash = "sha256:17948aeadbdb091f0ced6ef0841620794e68327b94ee415571c1203594b7215c", size = 6362659, upload-time = "2026-06-04T07:49:21.349Z" }, + { url = "https://files.pythonhosted.org/packages/35/c4/dcd2d62b5944b6d5db53413a5899016ccd57ffcb7278f3f81655d25d2027/pywin32-312-cp311-cp311-win_amd64.whl", hash = "sha256:d11417d84412f859b722fad0841b3614459ed0047f7542d8362e77884f6b6e8a", size = 6928825, upload-time = "2026-06-04T07:49:23.934Z" }, + { url = "https://files.pythonhosted.org/packages/b7/56/3cbb433fe4501cdba2eb9040f56a4e1a8243faa4186b25295564d1a7a79d/pywin32-312-cp311-cp311-win_arm64.whl", hash = "sha256:b2200a054ca6d6625c4842fc56a4976a4b47f96b73dbe5538c3f813a80359f47", size = 6721875, upload-time = "2026-06-04T07:49:26.416Z" }, + { url = "https://files.pythonhosted.org/packages/83/ff/32aa7d2ed0ab12b323aaa64f9b75e6ad4f8fd09f9ccfc28c79414d46838d/pywin32-312-cp312-cp312-win32.whl", hash = "sha256:dab4f65ac9c4e48400a2a0530c46c3c579cd5905ecd11b80692373915269208b", size = 6371877, upload-time = "2026-06-04T07:49:28.836Z" }, + { url = "https://files.pythonhosted.org/packages/03/d9/77040d3b43df3f3be32ea289433d660d2727f5ba327bc73be835127d9d60/pywin32-312-cp312-cp312-win_amd64.whl", hash = "sha256:b457f6d628a47e8a7346ce22acb7e1a46a4a78b52e1d17e1af56871bd19a93bc", size = 6914841, upload-time = "2026-06-04T07:49:31.85Z" }, + { url = "https://files.pythonhosted.org/packages/e3/cc/7b1ec671775756020a0ee7f4feeaf3c568f0ab86bd3900088cf986937a92/pywin32-312-cp312-cp312-win_arm64.whl", hash = "sha256:6017c58e12f6809fbb0555b75df144c2922a9ffd18e4b9b5afa863b6c1a9d950", size = 6727901, upload-time = "2026-06-04T07:49:34.244Z" }, + { url = "https://files.pythonhosted.org/packages/2d/41/12fbfd7f36ed2146d8bc9de96c2741296bf0d490b98508496cff322e274c/pywin32-312-cp313-cp313-win32.whl", hash = "sha256:7a27df850933d16a8eabfbaeb73d52b273e2da667f80d70b01a89d1f6828d02c", size = 6370184, upload-time = "2026-06-04T07:49:36.253Z" }, + { url = "https://files.pythonhosted.org/packages/ba/db/36a78e3403099d31d9746d13fdcde5accc43c1155f375a34d15983a479a7/pywin32-312-cp313-cp313-win_amd64.whl", hash = "sha256:c53e878d15a1c44788082bfe712a905433473aa38f86375b7cf8b45e3acbaaf9", size = 6914298, upload-time = "2026-06-04T07:49:38.876Z" }, + { url = "https://files.pythonhosted.org/packages/84/37/c1697194092b76de9ed47ca124323f02c57ffc8a45c06f88a3d5acaf01eb/pywin32-312-cp313-cp313-win_arm64.whl", hash = "sha256:59aba5d5940842075343a5ddc6b11f1cdf0d1567fe745290359dfbcc7c2eb831", size = 6727640, upload-time = "2026-06-04T07:49:41.083Z" }, + { url = "https://files.pythonhosted.org/packages/fc/2b/1f3cded5822fd49c02f40544cbb5f58c7cfd6b1694869fd476cb6170ee97/pywin32-312-cp314-cp314-win32.whl", hash = "sha256:a77a90fbb6881238d2ca9c6fd797b25817f3768fe78d214a90137ff055a75f5b", size = 6468928, upload-time = "2026-06-04T07:49:43.188Z" }, + { url = "https://files.pythonhosted.org/packages/21/82/3bf86d2e2808902013132e1ce905a7da0da53790f3836c64bf44d55e24f3/pywin32-312-cp314-cp314-win_amd64.whl", hash = "sha256:a4dd3a848290ef724347b19f301045831d8e802fa4464f491b98b1e0a081432e", size = 7024157, upload-time = "2026-06-04T07:49:45.34Z" }, + { url = "https://files.pythonhosted.org/packages/a4/0e/73f6d6800b4f27655abd9e9f6aaeaefcddb2b946e4674efa2bab184a7f7b/pywin32-312-cp314-cp314-win_arm64.whl", hash = "sha256:9fce94568364e0155e6dfb781ac5d95903be8baf28670632beab1b523f300daa", size = 6839598, upload-time = "2026-06-04T07:49:47.613Z" }, + { url = "https://files.pythonhosted.org/packages/eb/61/caa39686032d2ebdd04ff0ab5cbe163126c0066d98e00c9018646e42393b/pywin32-312-cp315-cp315-win32.whl", hash = "sha256:5c1fbe4a937a73ae9297384a3da38518cbc694c68ad8a809b2e19acd350f03ed", size = 6471159, upload-time = "2026-06-04T07:49:50.035Z" }, + { url = "https://files.pythonhosted.org/packages/0f/cd/7e1de64a4a6f69c04214169657ccab0d93a670ea50e35eb8f489d7378249/pywin32-312-cp315-cp315-win_amd64.whl", hash = "sha256:c2f03a0f73f804a13c2735b99392b0cd426bb4f2c4d0178e5ac966a0f21618d5", size = 7025293, upload-time = "2026-06-04T07:49:54.857Z" }, + { url = "https://files.pythonhosted.org/packages/23/ed/4532e9388e65fa16b46776ef47ad631a64eda1631884488af707666350ed/pywin32-312-cp315-cp315-win_arm64.whl", hash = "sha256:a8597d28f267b39074aef51fa593530082b39cbe5a074226096857b1fed2dfb9", size = 6840337, upload-time = "2026-06-04T07:49:57.531Z" }, +] + +[[package]] +name = "referencing" +version = "0.37.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "rpds-py", version = "0.30.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "rpds-py", version = "2026.6.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, +] + +[[package]] +name = "rpds-py" +version = "0.30.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11' and sys_platform == 'win32'", + "python_full_version < '3.11' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/20/af/3f2f423103f1113b36230496629986e0ef7e199d2aa8392452b484b38ced/rpds_py-0.30.0.tar.gz", hash = "sha256:dd8ff7cf90014af0c0f787eea34794ebf6415242ee1d6fa91eaba725cc441e84", size = 69469, upload-time = "2025-11-30T20:24:38.837Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/06/0c/0c411a0ec64ccb6d104dcabe0e713e05e153a9a2c3c2bd2b32ce412166fe/rpds_py-0.30.0-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:679ae98e00c0e8d68a7fda324e16b90fd5260945b45d3b824c892cec9eea3288", size = 370490, upload-time = "2025-11-30T20:21:33.256Z" }, + { url = "https://files.pythonhosted.org/packages/19/6a/4ba3d0fb7297ebae71171822554abe48d7cab29c28b8f9f2c04b79988c05/rpds_py-0.30.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:4cc2206b76b4f576934f0ed374b10d7ca5f457858b157ca52064bdfc26b9fc00", size = 359751, upload-time = "2025-11-30T20:21:34.591Z" }, + { url = "https://files.pythonhosted.org/packages/cd/7c/e4933565ef7f7a0818985d87c15d9d273f1a649afa6a52ea35ad011195ea/rpds_py-0.30.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:389a2d49eded1896c3d48b0136ead37c48e221b391c052fba3f4055c367f60a6", size = 389696, upload-time = "2025-11-30T20:21:36.122Z" }, + { url = "https://files.pythonhosted.org/packages/5e/01/6271a2511ad0815f00f7ed4390cf2567bec1d4b1da39e2c27a41e6e3b4de/rpds_py-0.30.0-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:32c8528634e1bf7121f3de08fa85b138f4e0dc47657866630611b03967f041d7", size = 403136, upload-time = "2025-11-30T20:21:37.728Z" }, + { url = "https://files.pythonhosted.org/packages/55/64/c857eb7cd7541e9b4eee9d49c196e833128a55b89a9850a9c9ac33ccf897/rpds_py-0.30.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f207f69853edd6f6700b86efb84999651baf3789e78a466431df1331608e5324", size = 524699, upload-time = "2025-11-30T20:21:38.92Z" }, + { url = "https://files.pythonhosted.org/packages/9c/ed/94816543404078af9ab26159c44f9e98e20fe47e2126d5d32c9d9948d10a/rpds_py-0.30.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:67b02ec25ba7a9e8fa74c63b6ca44cf5707f2fbfadae3ee8e7494297d56aa9df", size = 412022, upload-time = "2025-11-30T20:21:40.407Z" }, + { url = "https://files.pythonhosted.org/packages/61/b5/707f6cf0066a6412aacc11d17920ea2e19e5b2f04081c64526eb35b5c6e7/rpds_py-0.30.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0c0e95f6819a19965ff420f65578bacb0b00f251fefe2c8b23347c37174271f3", size = 390522, upload-time = "2025-11-30T20:21:42.17Z" }, + { url = "https://files.pythonhosted.org/packages/13/4e/57a85fda37a229ff4226f8cbcf09f2a455d1ed20e802ce5b2b4a7f5ed053/rpds_py-0.30.0-cp310-cp310-manylinux_2_31_riscv64.whl", hash = "sha256:a452763cc5198f2f98898eb98f7569649fe5da666c2dc6b5ddb10fde5a574221", size = 404579, upload-time = "2025-11-30T20:21:43.769Z" }, + { url = "https://files.pythonhosted.org/packages/f9/da/c9339293513ec680a721e0e16bf2bac3db6e5d7e922488de471308349bba/rpds_py-0.30.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e0b65193a413ccc930671c55153a03ee57cecb49e6227204b04fae512eb657a7", size = 421305, upload-time = "2025-11-30T20:21:44.994Z" }, + { url = "https://files.pythonhosted.org/packages/f9/be/522cb84751114f4ad9d822ff5a1aa3c98006341895d5f084779b99596e5c/rpds_py-0.30.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:858738e9c32147f78b3ac24dc0edb6610000e56dc0f700fd5f651d0a0f0eb9ff", size = 572503, upload-time = "2025-11-30T20:21:46.91Z" }, + { url = "https://files.pythonhosted.org/packages/a2/9b/de879f7e7ceddc973ea6e4629e9b380213a6938a249e94b0cdbcc325bb66/rpds_py-0.30.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:da279aa314f00acbb803da1e76fa18666778e8a8f83484fba94526da5de2cba7", size = 598322, upload-time = "2025-11-30T20:21:48.709Z" }, + { url = "https://files.pythonhosted.org/packages/48/ac/f01fc22efec3f37d8a914fc1b2fb9bcafd56a299edbe96406f3053edea5a/rpds_py-0.30.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:7c64d38fb49b6cdeda16ab49e35fe0da2e1e9b34bc38bd78386530f218b37139", size = 560792, upload-time = "2025-11-30T20:21:50.024Z" }, + { url = "https://files.pythonhosted.org/packages/e2/da/4e2b19d0f131f35b6146425f846563d0ce036763e38913d917187307a671/rpds_py-0.30.0-cp310-cp310-win32.whl", hash = "sha256:6de2a32a1665b93233cde140ff8b3467bdb9e2af2b91079f0333a0974d12d464", size = 221901, upload-time = "2025-11-30T20:21:51.32Z" }, + { url = "https://files.pythonhosted.org/packages/96/cb/156d7a5cf4f78a7cc571465d8aec7a3c447c94f6749c5123f08438bcf7bc/rpds_py-0.30.0-cp310-cp310-win_amd64.whl", hash = "sha256:1726859cd0de969f88dc8673bdd954185b9104e05806be64bcd87badbe313169", size = 235823, upload-time = "2025-11-30T20:21:52.505Z" }, + { url = "https://files.pythonhosted.org/packages/4d/6e/f964e88b3d2abee2a82c1ac8366da848fce1c6d834dc2132c3fda3970290/rpds_py-0.30.0-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:a2bffea6a4ca9f01b3f8e548302470306689684e61602aa3d141e34da06cf425", size = 370157, upload-time = "2025-11-30T20:21:53.789Z" }, + { url = "https://files.pythonhosted.org/packages/94/ba/24e5ebb7c1c82e74c4e4f33b2112a5573ddc703915b13a073737b59b86e0/rpds_py-0.30.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:dc4f992dfe1e2bc3ebc7444f6c7051b4bc13cd8e33e43511e8ffd13bf407010d", size = 359676, upload-time = "2025-11-30T20:21:55.475Z" }, + { url = "https://files.pythonhosted.org/packages/84/86/04dbba1b087227747d64d80c3b74df946b986c57af0a9f0c98726d4d7a3b/rpds_py-0.30.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:422c3cb9856d80b09d30d2eb255d0754b23e090034e1deb4083f8004bd0761e4", size = 389938, upload-time = "2025-11-30T20:21:57.079Z" }, + { url = "https://files.pythonhosted.org/packages/42/bb/1463f0b1722b7f45431bdd468301991d1328b16cffe0b1c2918eba2c4eee/rpds_py-0.30.0-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:07ae8a593e1c3c6b82ca3292efbe73c30b61332fd612e05abee07c79359f292f", size = 402932, upload-time = "2025-11-30T20:21:58.47Z" }, + { url = "https://files.pythonhosted.org/packages/99/ee/2520700a5c1f2d76631f948b0736cdf9b0acb25abd0ca8e889b5c62ac2e3/rpds_py-0.30.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:12f90dd7557b6bd57f40abe7747e81e0c0b119bef015ea7726e69fe550e394a4", size = 525830, upload-time = "2025-11-30T20:21:59.699Z" }, + { url = "https://files.pythonhosted.org/packages/e0/ad/bd0331f740f5705cc555a5e17fdf334671262160270962e69a2bdef3bf76/rpds_py-0.30.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:99b47d6ad9a6da00bec6aabe5a6279ecd3c06a329d4aa4771034a21e335c3a97", size = 412033, upload-time = "2025-11-30T20:22:00.991Z" }, + { url = "https://files.pythonhosted.org/packages/f8/1e/372195d326549bb51f0ba0f2ecb9874579906b97e08880e7a65c3bef1a99/rpds_py-0.30.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:33f559f3104504506a44bb666b93a33f5d33133765b0c216a5bf2f1e1503af89", size = 390828, upload-time = "2025-11-30T20:22:02.723Z" }, + { url = "https://files.pythonhosted.org/packages/ab/2b/d88bb33294e3e0c76bc8f351a3721212713629ffca1700fa94979cb3eae8/rpds_py-0.30.0-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:946fe926af6e44f3697abbc305ea168c2c31d3e3ef1058cf68f379bf0335a78d", size = 404683, upload-time = "2025-11-30T20:22:04.367Z" }, + { url = "https://files.pythonhosted.org/packages/50/32/c759a8d42bcb5289c1fac697cd92f6fe01a018dd937e62ae77e0e7f15702/rpds_py-0.30.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:495aeca4b93d465efde585977365187149e75383ad2684f81519f504f5c13038", size = 421583, upload-time = "2025-11-30T20:22:05.814Z" }, + { url = "https://files.pythonhosted.org/packages/2b/81/e729761dbd55ddf5d84ec4ff1f47857f4374b0f19bdabfcf929164da3e24/rpds_py-0.30.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d9a0ca5da0386dee0655b4ccdf46119df60e0f10da268d04fe7cc87886872ba7", size = 572496, upload-time = "2025-11-30T20:22:07.713Z" }, + { url = "https://files.pythonhosted.org/packages/14/f6/69066a924c3557c9c30baa6ec3a0aa07526305684c6f86c696b08860726c/rpds_py-0.30.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:8d6d1cc13664ec13c1b84241204ff3b12f9bb82464b8ad6e7a5d3486975c2eed", size = 598669, upload-time = "2025-11-30T20:22:09.312Z" }, + { url = "https://files.pythonhosted.org/packages/5f/48/905896b1eb8a05630d20333d1d8ffd162394127b74ce0b0784ae04498d32/rpds_py-0.30.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:3896fa1be39912cf0757753826bc8bdc8ca331a28a7c4ae46b7a21280b06bb85", size = 561011, upload-time = "2025-11-30T20:22:11.309Z" }, + { url = "https://files.pythonhosted.org/packages/22/16/cd3027c7e279d22e5eb431dd3c0fbc677bed58797fe7581e148f3f68818b/rpds_py-0.30.0-cp311-cp311-win32.whl", hash = "sha256:55f66022632205940f1827effeff17c4fa7ae1953d2b74a8581baaefb7d16f8c", size = 221406, upload-time = "2025-11-30T20:22:13.101Z" }, + { url = "https://files.pythonhosted.org/packages/fa/5b/e7b7aa136f28462b344e652ee010d4de26ee9fd16f1bfd5811f5153ccf89/rpds_py-0.30.0-cp311-cp311-win_amd64.whl", hash = "sha256:a51033ff701fca756439d641c0ad09a41d9242fa69121c7d8769604a0a629825", size = 236024, upload-time = "2025-11-30T20:22:14.853Z" }, + { url = "https://files.pythonhosted.org/packages/14/a6/364bba985e4c13658edb156640608f2c9e1d3ea3c81b27aa9d889fff0e31/rpds_py-0.30.0-cp311-cp311-win_arm64.whl", hash = "sha256:47b0ef6231c58f506ef0b74d44e330405caa8428e770fec25329ed2cb971a229", size = 229069, upload-time = "2025-11-30T20:22:16.577Z" }, + { url = "https://files.pythonhosted.org/packages/03/e7/98a2f4ac921d82f33e03f3835f5bf3a4a40aa1bfdc57975e74a97b2b4bdd/rpds_py-0.30.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a161f20d9a43006833cd7068375a94d035714d73a172b681d8881820600abfad", size = 375086, upload-time = "2025-11-30T20:22:17.93Z" }, + { url = "https://files.pythonhosted.org/packages/4d/a1/bca7fd3d452b272e13335db8d6b0b3ecde0f90ad6f16f3328c6fb150c889/rpds_py-0.30.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6abc8880d9d036ecaafe709079969f56e876fcf107f7a8e9920ba6d5a3878d05", size = 359053, upload-time = "2025-11-30T20:22:19.297Z" }, + { url = "https://files.pythonhosted.org/packages/65/1c/ae157e83a6357eceff62ba7e52113e3ec4834a84cfe07fa4b0757a7d105f/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ca28829ae5f5d569bb62a79512c842a03a12576375d5ece7d2cadf8abe96ec28", size = 390763, upload-time = "2025-11-30T20:22:21.661Z" }, + { url = "https://files.pythonhosted.org/packages/d4/36/eb2eb8515e2ad24c0bd43c3ee9cd74c33f7ca6430755ccdb240fd3144c44/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a1010ed9524c73b94d15919ca4d41d8780980e1765babf85f9a2f90d247153dd", size = 408951, upload-time = "2025-11-30T20:22:23.408Z" }, + { url = "https://files.pythonhosted.org/packages/d6/65/ad8dc1784a331fabbd740ef6f71ce2198c7ed0890dab595adb9ea2d775a1/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f8d1736cfb49381ba528cd5baa46f82fdc65c06e843dab24dd70b63d09121b3f", size = 514622, upload-time = "2025-11-30T20:22:25.16Z" }, + { url = "https://files.pythonhosted.org/packages/63/8e/0cfa7ae158e15e143fe03993b5bcd743a59f541f5952e1546b1ac1b5fd45/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d948b135c4693daff7bc2dcfc4ec57237a29bd37e60c2fabf5aff2bbacf3e2f1", size = 414492, upload-time = "2025-11-30T20:22:26.505Z" }, + { url = "https://files.pythonhosted.org/packages/60/1b/6f8f29f3f995c7ffdde46a626ddccd7c63aefc0efae881dc13b6e5d5bb16/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47f236970bccb2233267d89173d3ad2703cd36a0e2a6e92d0560d333871a3d23", size = 394080, upload-time = "2025-11-30T20:22:27.934Z" }, + { url = "https://files.pythonhosted.org/packages/6d/d5/a266341051a7a3ca2f4b750a3aa4abc986378431fc2da508c5034d081b70/rpds_py-0.30.0-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:2e6ecb5a5bcacf59c3f912155044479af1d0b6681280048b338b28e364aca1f6", size = 408680, upload-time = "2025-11-30T20:22:29.341Z" }, + { url = "https://files.pythonhosted.org/packages/10/3b/71b725851df9ab7a7a4e33cf36d241933da66040d195a84781f49c50490c/rpds_py-0.30.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a8fa71a2e078c527c3e9dc9fc5a98c9db40bcc8a92b4e8858e36d329f8684b51", size = 423589, upload-time = "2025-11-30T20:22:31.469Z" }, + { url = "https://files.pythonhosted.org/packages/00/2b/e59e58c544dc9bd8bd8384ecdb8ea91f6727f0e37a7131baeff8d6f51661/rpds_py-0.30.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:73c67f2db7bc334e518d097c6d1e6fed021bbc9b7d678d6cc433478365d1d5f5", size = 573289, upload-time = "2025-11-30T20:22:32.997Z" }, + { url = "https://files.pythonhosted.org/packages/da/3e/a18e6f5b460893172a7d6a680e86d3b6bc87a54c1f0b03446a3c8c7b588f/rpds_py-0.30.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:5ba103fb455be00f3b1c2076c9d4264bfcb037c976167a6047ed82f23153f02e", size = 599737, upload-time = "2025-11-30T20:22:34.419Z" }, + { url = "https://files.pythonhosted.org/packages/5c/e2/714694e4b87b85a18e2c243614974413c60aa107fd815b8cbc42b873d1d7/rpds_py-0.30.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7cee9c752c0364588353e627da8a7e808a66873672bcb5f52890c33fd965b394", size = 563120, upload-time = "2025-11-30T20:22:35.903Z" }, + { url = "https://files.pythonhosted.org/packages/6f/ab/d5d5e3bcedb0a77f4f613706b750e50a5a3ba1c15ccd3665ecc636c968fd/rpds_py-0.30.0-cp312-cp312-win32.whl", hash = "sha256:1ab5b83dbcf55acc8b08fc62b796ef672c457b17dbd7820a11d6c52c06839bdf", size = 223782, upload-time = "2025-11-30T20:22:37.271Z" }, + { url = "https://files.pythonhosted.org/packages/39/3b/f786af9957306fdc38a74cef405b7b93180f481fb48453a114bb6465744a/rpds_py-0.30.0-cp312-cp312-win_amd64.whl", hash = "sha256:a090322ca841abd453d43456ac34db46e8b05fd9b3b4ac0c78bcde8b089f959b", size = 240463, upload-time = "2025-11-30T20:22:39.021Z" }, + { url = "https://files.pythonhosted.org/packages/f3/d2/b91dc748126c1559042cfe41990deb92c4ee3e2b415f6b5234969ffaf0cc/rpds_py-0.30.0-cp312-cp312-win_arm64.whl", hash = "sha256:669b1805bd639dd2989b281be2cfd951c6121b65e729d9b843e9639ef1fd555e", size = 230868, upload-time = "2025-11-30T20:22:40.493Z" }, + { url = "https://files.pythonhosted.org/packages/ed/dc/d61221eb88ff410de3c49143407f6f3147acf2538c86f2ab7ce65ae7d5f9/rpds_py-0.30.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:f83424d738204d9770830d35290ff3273fbb02b41f919870479fab14b9d303b2", size = 374887, upload-time = "2025-11-30T20:22:41.812Z" }, + { url = "https://files.pythonhosted.org/packages/fd/32/55fb50ae104061dbc564ef15cc43c013dc4a9f4527a1f4d99baddf56fe5f/rpds_py-0.30.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e7536cd91353c5273434b4e003cbda89034d67e7710eab8761fd918ec6c69cf8", size = 358904, upload-time = "2025-11-30T20:22:43.479Z" }, + { url = "https://files.pythonhosted.org/packages/58/70/faed8186300e3b9bdd138d0273109784eea2396c68458ed580f885dfe7ad/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2771c6c15973347f50fece41fc447c054b7ac2ae0502388ce3b6738cd366e3d4", size = 389945, upload-time = "2025-11-30T20:22:44.819Z" }, + { url = "https://files.pythonhosted.org/packages/bd/a8/073cac3ed2c6387df38f71296d002ab43496a96b92c823e76f46b8af0543/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:0a59119fc6e3f460315fe9d08149f8102aa322299deaa5cab5b40092345c2136", size = 407783, upload-time = "2025-11-30T20:22:46.103Z" }, + { url = "https://files.pythonhosted.org/packages/77/57/5999eb8c58671f1c11eba084115e77a8899d6e694d2a18f69f0ba471ec8b/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:76fec018282b4ead0364022e3c54b60bf368b9d926877957a8624b58419169b7", size = 515021, upload-time = "2025-11-30T20:22:47.458Z" }, + { url = "https://files.pythonhosted.org/packages/e0/af/5ab4833eadc36c0a8ed2bc5c0de0493c04f6c06de223170bd0798ff98ced/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:692bef75a5525db97318e8cd061542b5a79812d711ea03dbc1f6f8dbb0c5f0d2", size = 414589, upload-time = "2025-11-30T20:22:48.872Z" }, + { url = "https://files.pythonhosted.org/packages/b7/de/f7192e12b21b9e9a68a6d0f249b4af3fdcdff8418be0767a627564afa1f1/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9027da1ce107104c50c81383cae773ef5c24d296dd11c99e2629dbd7967a20c6", size = 394025, upload-time = "2025-11-30T20:22:50.196Z" }, + { url = "https://files.pythonhosted.org/packages/91/c4/fc70cd0249496493500e7cc2de87504f5aa6509de1e88623431fec76d4b6/rpds_py-0.30.0-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:9cf69cdda1f5968a30a359aba2f7f9aa648a9ce4b580d6826437f2b291cfc86e", size = 408895, upload-time = "2025-11-30T20:22:51.87Z" }, + { url = "https://files.pythonhosted.org/packages/58/95/d9275b05ab96556fefff73a385813eb66032e4c99f411d0795372d9abcea/rpds_py-0.30.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a4796a717bf12b9da9d3ad002519a86063dcac8988b030e405704ef7d74d2d9d", size = 422799, upload-time = "2025-11-30T20:22:53.341Z" }, + { url = "https://files.pythonhosted.org/packages/06/c1/3088fc04b6624eb12a57eb814f0d4997a44b0d208d6cace713033ff1a6ba/rpds_py-0.30.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5d4c2aa7c50ad4728a094ebd5eb46c452e9cb7edbfdb18f9e1221f597a73e1e7", size = 572731, upload-time = "2025-11-30T20:22:54.778Z" }, + { url = "https://files.pythonhosted.org/packages/d8/42/c612a833183b39774e8ac8fecae81263a68b9583ee343db33ab571a7ce55/rpds_py-0.30.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ba81a9203d07805435eb06f536d95a266c21e5b2dfbf6517748ca40c98d19e31", size = 599027, upload-time = "2025-11-30T20:22:56.212Z" }, + { url = "https://files.pythonhosted.org/packages/5f/60/525a50f45b01d70005403ae0e25f43c0384369ad24ffe46e8d9068b50086/rpds_py-0.30.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:945dccface01af02675628334f7cf49c2af4c1c904748efc5cf7bbdf0b579f95", size = 563020, upload-time = "2025-11-30T20:22:58.2Z" }, + { url = "https://files.pythonhosted.org/packages/0b/5d/47c4655e9bcd5ca907148535c10e7d489044243cc9941c16ed7cd53be91d/rpds_py-0.30.0-cp313-cp313-win32.whl", hash = "sha256:b40fb160a2db369a194cb27943582b38f79fc4887291417685f3ad693c5a1d5d", size = 223139, upload-time = "2025-11-30T20:23:00.209Z" }, + { url = "https://files.pythonhosted.org/packages/f2/e1/485132437d20aa4d3e1d8b3fb5a5e65aa8139f1e097080c2a8443201742c/rpds_py-0.30.0-cp313-cp313-win_amd64.whl", hash = "sha256:806f36b1b605e2d6a72716f321f20036b9489d29c51c91f4dd29a3e3afb73b15", size = 240224, upload-time = "2025-11-30T20:23:02.008Z" }, + { url = "https://files.pythonhosted.org/packages/24/95/ffd128ed1146a153d928617b0ef673960130be0009c77d8fbf0abe306713/rpds_py-0.30.0-cp313-cp313-win_arm64.whl", hash = "sha256:d96c2086587c7c30d44f31f42eae4eac89b60dabbac18c7669be3700f13c3ce1", size = 230645, upload-time = "2025-11-30T20:23:03.43Z" }, + { url = "https://files.pythonhosted.org/packages/ff/1b/b10de890a0def2a319a2626334a7f0ae388215eb60914dbac8a3bae54435/rpds_py-0.30.0-cp313-cp313t-macosx_10_12_x86_64.whl", hash = "sha256:eb0b93f2e5c2189ee831ee43f156ed34e2a89a78a66b98cadad955972548be5a", size = 364443, upload-time = "2025-11-30T20:23:04.878Z" }, + { url = "https://files.pythonhosted.org/packages/0d/bf/27e39f5971dc4f305a4fb9c672ca06f290f7c4e261c568f3dea16a410d47/rpds_py-0.30.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:922e10f31f303c7c920da8981051ff6d8c1a56207dbdf330d9047f6d30b70e5e", size = 353375, upload-time = "2025-11-30T20:23:06.342Z" }, + { url = "https://files.pythonhosted.org/packages/40/58/442ada3bba6e8e6615fc00483135c14a7538d2ffac30e2d933ccf6852232/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cdc62c8286ba9bf7f47befdcea13ea0e26bf294bda99758fd90535cbaf408000", size = 383850, upload-time = "2025-11-30T20:23:07.825Z" }, + { url = "https://files.pythonhosted.org/packages/14/14/f59b0127409a33c6ef6f5c1ebd5ad8e32d7861c9c7adfa9a624fc3889f6c/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:47f9a91efc418b54fb8190a6b4aa7813a23fb79c51f4bb84e418f5476c38b8db", size = 392812, upload-time = "2025-11-30T20:23:09.228Z" }, + { url = "https://files.pythonhosted.org/packages/b3/66/e0be3e162ac299b3a22527e8913767d869e6cc75c46bd844aa43fb81ab62/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1f3587eb9b17f3789ad50824084fa6f81921bbf9a795826570bda82cb3ed91f2", size = 517841, upload-time = "2025-11-30T20:23:11.186Z" }, + { url = "https://files.pythonhosted.org/packages/3d/55/fa3b9cf31d0c963ecf1ba777f7cf4b2a2c976795ac430d24a1f43d25a6ba/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:39c02563fc592411c2c61d26b6c5fe1e51eaa44a75aa2c8735ca88b0d9599daa", size = 408149, upload-time = "2025-11-30T20:23:12.864Z" }, + { url = "https://files.pythonhosted.org/packages/60/ca/780cf3b1a32b18c0f05c441958d3758f02544f1d613abf9488cd78876378/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:51a1234d8febafdfd33a42d97da7a43f5dcb120c1060e352a3fbc0c6d36e2083", size = 383843, upload-time = "2025-11-30T20:23:14.638Z" }, + { url = "https://files.pythonhosted.org/packages/82/86/d5f2e04f2aa6247c613da0c1dd87fcd08fa17107e858193566048a1e2f0a/rpds_py-0.30.0-cp313-cp313t-manylinux_2_31_riscv64.whl", hash = "sha256:eb2c4071ab598733724c08221091e8d80e89064cd472819285a9ab0f24bcedb9", size = 396507, upload-time = "2025-11-30T20:23:16.105Z" }, + { url = "https://files.pythonhosted.org/packages/4b/9a/453255d2f769fe44e07ea9785c8347edaf867f7026872e76c1ad9f7bed92/rpds_py-0.30.0-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:6bdfdb946967d816e6adf9a3d8201bfad269c67efe6cefd7093ef959683c8de0", size = 414949, upload-time = "2025-11-30T20:23:17.539Z" }, + { url = "https://files.pythonhosted.org/packages/a3/31/622a86cdc0c45d6df0e9ccb6becdba5074735e7033c20e401a6d9d0e2ca0/rpds_py-0.30.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c77afbd5f5250bf27bf516c7c4a016813eb2d3e116139aed0096940c5982da94", size = 565790, upload-time = "2025-11-30T20:23:19.029Z" }, + { url = "https://files.pythonhosted.org/packages/1c/5d/15bbf0fb4a3f58a3b1c67855ec1efcc4ceaef4e86644665fff03e1b66d8d/rpds_py-0.30.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:61046904275472a76c8c90c9ccee9013d70a6d0f73eecefd38c1ae7c39045a08", size = 590217, upload-time = "2025-11-30T20:23:20.885Z" }, + { url = "https://files.pythonhosted.org/packages/6d/61/21b8c41f68e60c8cc3b2e25644f0e3681926020f11d06ab0b78e3c6bbff1/rpds_py-0.30.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:4c5f36a861bc4b7da6516dbdf302c55313afa09b81931e8280361a4f6c9a2d27", size = 555806, upload-time = "2025-11-30T20:23:22.488Z" }, + { url = "https://files.pythonhosted.org/packages/f9/39/7e067bb06c31de48de3eb200f9fc7c58982a4d3db44b07e73963e10d3be9/rpds_py-0.30.0-cp313-cp313t-win32.whl", hash = "sha256:3d4a69de7a3e50ffc214ae16d79d8fbb0922972da0356dcf4d0fdca2878559c6", size = 211341, upload-time = "2025-11-30T20:23:24.449Z" }, + { url = "https://files.pythonhosted.org/packages/0a/4d/222ef0b46443cf4cf46764d9c630f3fe4abaa7245be9417e56e9f52b8f65/rpds_py-0.30.0-cp313-cp313t-win_amd64.whl", hash = "sha256:f14fc5df50a716f7ece6a80b6c78bb35ea2ca47c499e422aa4463455dd96d56d", size = 225768, upload-time = "2025-11-30T20:23:25.908Z" }, + { url = "https://files.pythonhosted.org/packages/86/81/dad16382ebbd3d0e0328776d8fd7ca94220e4fa0798d1dc5e7da48cb3201/rpds_py-0.30.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:68f19c879420aa08f61203801423f6cd5ac5f0ac4ac82a2368a9fcd6a9a075e0", size = 362099, upload-time = "2025-11-30T20:23:27.316Z" }, + { url = "https://files.pythonhosted.org/packages/2b/60/19f7884db5d5603edf3c6bce35408f45ad3e97e10007df0e17dd57af18f8/rpds_py-0.30.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:ec7c4490c672c1a0389d319b3a9cfcd098dcdc4783991553c332a15acf7249be", size = 353192, upload-time = "2025-11-30T20:23:29.151Z" }, + { url = "https://files.pythonhosted.org/packages/bf/c4/76eb0e1e72d1a9c4703c69607cec123c29028bff28ce41588792417098ac/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f251c812357a3fed308d684a5079ddfb9d933860fc6de89f2b7ab00da481e65f", size = 384080, upload-time = "2025-11-30T20:23:30.785Z" }, + { url = "https://files.pythonhosted.org/packages/72/87/87ea665e92f3298d1b26d78814721dc39ed8d2c74b86e83348d6b48a6f31/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ac98b175585ecf4c0348fd7b29c3864bda53b805c773cbf7bfdaffc8070c976f", size = 394841, upload-time = "2025-11-30T20:23:32.209Z" }, + { url = "https://files.pythonhosted.org/packages/77/ad/7783a89ca0587c15dcbf139b4a8364a872a25f861bdb88ed99f9b0dec985/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3e62880792319dbeb7eb866547f2e35973289e7d5696c6e295476448f5b63c87", size = 516670, upload-time = "2025-11-30T20:23:33.742Z" }, + { url = "https://files.pythonhosted.org/packages/5b/3c/2882bdac942bd2172f3da574eab16f309ae10a3925644e969536553cb4ee/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4e7fc54e0900ab35d041b0601431b0a0eb495f0851a0639b6ef90f7741b39a18", size = 408005, upload-time = "2025-11-30T20:23:35.253Z" }, + { url = "https://files.pythonhosted.org/packages/ce/81/9a91c0111ce1758c92516a3e44776920b579d9a7c09b2b06b642d4de3f0f/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47e77dc9822d3ad616c3d5759ea5631a75e5809d5a28707744ef79d7a1bcfcad", size = 382112, upload-time = "2025-11-30T20:23:36.842Z" }, + { url = "https://files.pythonhosted.org/packages/cf/8e/1da49d4a107027e5fbc64daeab96a0706361a2918da10cb41769244b805d/rpds_py-0.30.0-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:b4dc1a6ff022ff85ecafef7979a2c6eb423430e05f1165d6688234e62ba99a07", size = 399049, upload-time = "2025-11-30T20:23:38.343Z" }, + { url = "https://files.pythonhosted.org/packages/df/5a/7ee239b1aa48a127570ec03becbb29c9d5a9eb092febbd1699d567cae859/rpds_py-0.30.0-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:4559c972db3a360808309e06a74628b95eaccbf961c335c8fe0d590cf587456f", size = 415661, upload-time = "2025-11-30T20:23:40.263Z" }, + { url = "https://files.pythonhosted.org/packages/70/ea/caa143cf6b772f823bc7929a45da1fa83569ee49b11d18d0ada7f5ee6fd6/rpds_py-0.30.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:0ed177ed9bded28f8deb6ab40c183cd1192aa0de40c12f38be4d59cd33cb5c65", size = 565606, upload-time = "2025-11-30T20:23:42.186Z" }, + { url = "https://files.pythonhosted.org/packages/64/91/ac20ba2d69303f961ad8cf55bf7dbdb4763f627291ba3d0d7d67333cced9/rpds_py-0.30.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:ad1fa8db769b76ea911cb4e10f049d80bf518c104f15b3edb2371cc65375c46f", size = 591126, upload-time = "2025-11-30T20:23:44.086Z" }, + { url = "https://files.pythonhosted.org/packages/21/20/7ff5f3c8b00c8a95f75985128c26ba44503fb35b8e0259d812766ea966c7/rpds_py-0.30.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:46e83c697b1f1c72b50e5ee5adb4353eef7406fb3f2043d64c33f20ad1c2fc53", size = 553371, upload-time = "2025-11-30T20:23:46.004Z" }, + { url = "https://files.pythonhosted.org/packages/72/c7/81dadd7b27c8ee391c132a6b192111ca58d866577ce2d9b0ca157552cce0/rpds_py-0.30.0-cp314-cp314-win32.whl", hash = "sha256:ee454b2a007d57363c2dfd5b6ca4a5d7e2c518938f8ed3b706e37e5d470801ed", size = 215298, upload-time = "2025-11-30T20:23:47.696Z" }, + { url = "https://files.pythonhosted.org/packages/3e/d2/1aaac33287e8cfb07aab2e6b8ac1deca62f6f65411344f1433c55e6f3eb8/rpds_py-0.30.0-cp314-cp314-win_amd64.whl", hash = "sha256:95f0802447ac2d10bcc69f6dc28fe95fdf17940367b21d34e34c737870758950", size = 228604, upload-time = "2025-11-30T20:23:49.501Z" }, + { url = "https://files.pythonhosted.org/packages/e8/95/ab005315818cc519ad074cb7784dae60d939163108bd2b394e60dc7b5461/rpds_py-0.30.0-cp314-cp314-win_arm64.whl", hash = "sha256:613aa4771c99f03346e54c3f038e4cc574ac09a3ddfb0e8878487335e96dead6", size = 222391, upload-time = "2025-11-30T20:23:50.96Z" }, + { url = "https://files.pythonhosted.org/packages/9e/68/154fe0194d83b973cdedcdcc88947a2752411165930182ae41d983dcefa6/rpds_py-0.30.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:7e6ecfcb62edfd632e56983964e6884851786443739dbfe3582947e87274f7cb", size = 364868, upload-time = "2025-11-30T20:23:52.494Z" }, + { url = "https://files.pythonhosted.org/packages/83/69/8bbc8b07ec854d92a8b75668c24d2abcb1719ebf890f5604c61c9369a16f/rpds_py-0.30.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a1d0bc22a7cdc173fedebb73ef81e07faef93692b8c1ad3733b67e31e1b6e1b8", size = 353747, upload-time = "2025-11-30T20:23:54.036Z" }, + { url = "https://files.pythonhosted.org/packages/ab/00/ba2e50183dbd9abcce9497fa5149c62b4ff3e22d338a30d690f9af970561/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0d08f00679177226c4cb8c5265012eea897c8ca3b93f429e546600c971bcbae7", size = 383795, upload-time = "2025-11-30T20:23:55.556Z" }, + { url = "https://files.pythonhosted.org/packages/05/6f/86f0272b84926bcb0e4c972262f54223e8ecc556b3224d281e6598fc9268/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:5965af57d5848192c13534f90f9dd16464f3c37aaf166cc1da1cae1fd5a34898", size = 393330, upload-time = "2025-11-30T20:23:57.033Z" }, + { url = "https://files.pythonhosted.org/packages/cb/e9/0e02bb2e6dc63d212641da45df2b0bf29699d01715913e0d0f017ee29438/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9a4e86e34e9ab6b667c27f3211ca48f73dba7cd3d90f8d5b11be56e5dbc3fb4e", size = 518194, upload-time = "2025-11-30T20:23:58.637Z" }, + { url = "https://files.pythonhosted.org/packages/ee/ca/be7bca14cf21513bdf9c0606aba17d1f389ea2b6987035eb4f62bd923f25/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e5d3e6b26f2c785d65cc25ef1e5267ccbe1b069c5c21b8cc724efee290554419", size = 408340, upload-time = "2025-11-30T20:24:00.2Z" }, + { url = "https://files.pythonhosted.org/packages/c2/c7/736e00ebf39ed81d75544c0da6ef7b0998f8201b369acf842f9a90dc8fce/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:626a7433c34566535b6e56a1b39a7b17ba961e97ce3b80ec62e6f1312c025551", size = 383765, upload-time = "2025-11-30T20:24:01.759Z" }, + { url = "https://files.pythonhosted.org/packages/4a/3f/da50dfde9956aaf365c4adc9533b100008ed31aea635f2b8d7b627e25b49/rpds_py-0.30.0-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:acd7eb3f4471577b9b5a41baf02a978e8bdeb08b4b355273994f8b87032000a8", size = 396834, upload-time = "2025-11-30T20:24:03.687Z" }, + { url = "https://files.pythonhosted.org/packages/4e/00/34bcc2565b6020eab2623349efbdec810676ad571995911f1abdae62a3a0/rpds_py-0.30.0-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:fe5fa731a1fa8a0a56b0977413f8cacac1768dad38d16b3a296712709476fbd5", size = 415470, upload-time = "2025-11-30T20:24:05.232Z" }, + { url = "https://files.pythonhosted.org/packages/8c/28/882e72b5b3e6f718d5453bd4d0d9cf8df36fddeb4ddbbab17869d5868616/rpds_py-0.30.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:74a3243a411126362712ee1524dfc90c650a503502f135d54d1b352bd01f2404", size = 565630, upload-time = "2025-11-30T20:24:06.878Z" }, + { url = "https://files.pythonhosted.org/packages/3b/97/04a65539c17692de5b85c6e293520fd01317fd878ea1995f0367d4532fb1/rpds_py-0.30.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:3e8eeb0544f2eb0d2581774be4c3410356eba189529a6b3e36bbbf9696175856", size = 591148, upload-time = "2025-11-30T20:24:08.445Z" }, + { url = "https://files.pythonhosted.org/packages/85/70/92482ccffb96f5441aab93e26c4d66489eb599efdcf96fad90c14bbfb976/rpds_py-0.30.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:dbd936cde57abfee19ab3213cf9c26be06d60750e60a8e4dd85d1ab12c8b1f40", size = 556030, upload-time = "2025-11-30T20:24:10.956Z" }, + { url = "https://files.pythonhosted.org/packages/20/53/7c7e784abfa500a2b6b583b147ee4bb5a2b3747a9166bab52fec4b5b5e7d/rpds_py-0.30.0-cp314-cp314t-win32.whl", hash = "sha256:dc824125c72246d924f7f796b4f63c1e9dc810c7d9e2355864b3c3a73d59ade0", size = 211570, upload-time = "2025-11-30T20:24:12.735Z" }, + { url = "https://files.pythonhosted.org/packages/d0/02/fa464cdfbe6b26e0600b62c528b72d8608f5cc49f96b8d6e38c95d60c676/rpds_py-0.30.0-cp314-cp314t-win_amd64.whl", hash = "sha256:27f4b0e92de5bfbc6f86e43959e6edd1425c33b5e69aab0984a72047f2bcf1e3", size = 226532, upload-time = "2025-11-30T20:24:14.634Z" }, + { url = "https://files.pythonhosted.org/packages/69/71/3f34339ee70521864411f8b6992e7ab13ac30d8e4e3309e07c7361767d91/rpds_py-0.30.0-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:c2262bdba0ad4fc6fb5545660673925c2d2a5d9e2e0fb603aad545427be0fc58", size = 372292, upload-time = "2025-11-30T20:24:16.537Z" }, + { url = "https://files.pythonhosted.org/packages/57/09/f183df9b8f2d66720d2ef71075c59f7e1b336bec7ee4c48f0a2b06857653/rpds_py-0.30.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:ee6af14263f25eedc3bb918a3c04245106a42dfd4f5c2285ea6f997b1fc3f89a", size = 362128, upload-time = "2025-11-30T20:24:18.086Z" }, + { url = "https://files.pythonhosted.org/packages/7a/68/5c2594e937253457342e078f0cc1ded3dd7b2ad59afdbf2d354869110a02/rpds_py-0.30.0-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3adbb8179ce342d235c31ab8ec511e66c73faa27a47e076ccc92421add53e2bb", size = 391542, upload-time = "2025-11-30T20:24:20.092Z" }, + { url = "https://files.pythonhosted.org/packages/49/5c/31ef1afd70b4b4fbdb2800249f34c57c64beb687495b10aec0365f53dfc4/rpds_py-0.30.0-pp311-pypy311_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:250fa00e9543ac9b97ac258bd37367ff5256666122c2d0f2bc97577c60a1818c", size = 404004, upload-time = "2025-11-30T20:24:22.231Z" }, + { url = "https://files.pythonhosted.org/packages/e3/63/0cfbea38d05756f3440ce6534d51a491d26176ac045e2707adc99bb6e60a/rpds_py-0.30.0-pp311-pypy311_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9854cf4f488b3d57b9aaeb105f06d78e5529d3145b1e4a41750167e8c213c6d3", size = 527063, upload-time = "2025-11-30T20:24:24.302Z" }, + { url = "https://files.pythonhosted.org/packages/42/e6/01e1f72a2456678b0f618fc9a1a13f882061690893c192fcad9f2926553a/rpds_py-0.30.0-pp311-pypy311_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:993914b8e560023bc0a8bf742c5f303551992dcb85e247b1e5c7f4a7d145bda5", size = 413099, upload-time = "2025-11-30T20:24:25.916Z" }, + { url = "https://files.pythonhosted.org/packages/b8/25/8df56677f209003dcbb180765520c544525e3ef21ea72279c98b9aa7c7fb/rpds_py-0.30.0-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:58edca431fb9b29950807e301826586e5bbf24163677732429770a697ffe6738", size = 392177, upload-time = "2025-11-30T20:24:27.834Z" }, + { url = "https://files.pythonhosted.org/packages/4a/b4/0a771378c5f16f8115f796d1f437950158679bcd2a7c68cf251cfb00ed5b/rpds_py-0.30.0-pp311-pypy311_pp73-manylinux_2_31_riscv64.whl", hash = "sha256:dea5b552272a944763b34394d04577cf0f9bd013207bc32323b5a89a53cf9c2f", size = 406015, upload-time = "2025-11-30T20:24:29.457Z" }, + { url = "https://files.pythonhosted.org/packages/36/d8/456dbba0af75049dc6f63ff295a2f92766b9d521fa00de67a2bd6427d57a/rpds_py-0.30.0-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ba3af48635eb83d03f6c9735dfb21785303e73d22ad03d489e88adae6eab8877", size = 423736, upload-time = "2025-11-30T20:24:31.22Z" }, + { url = "https://files.pythonhosted.org/packages/13/64/b4d76f227d5c45a7e0b796c674fd81b0a6c4fbd48dc29271857d8219571c/rpds_py-0.30.0-pp311-pypy311_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:dff13836529b921e22f15cb099751209a60009731a68519630a24d61f0b1b30a", size = 573981, upload-time = "2025-11-30T20:24:32.934Z" }, + { url = "https://files.pythonhosted.org/packages/20/91/092bacadeda3edf92bf743cc96a7be133e13a39cdbfd7b5082e7ab638406/rpds_py-0.30.0-pp311-pypy311_pp73-musllinux_1_2_i686.whl", hash = "sha256:1b151685b23929ab7beec71080a8889d4d6d9fa9a983d213f07121205d48e2c4", size = 599782, upload-time = "2025-11-30T20:24:35.169Z" }, + { url = "https://files.pythonhosted.org/packages/d1/b7/b95708304cd49b7b6f82fdd039f1748b66ec2b21d6a45180910802f1abf1/rpds_py-0.30.0-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:ac37f9f516c51e5753f27dfdef11a88330f04de2d564be3991384b2f3535d02e", size = 562191, upload-time = "2025-11-30T20:24:36.853Z" }, +] + +[[package]] +name = "rpds-py" +version = "2026.6.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/aa/2a/9618a122aeb2a169a28b03889a2995fe297588964333d4a7d67bdf46e147/rpds_py-2026.6.3.tar.gz", hash = "sha256:1cebd1337c242e4ec2293e541f712b2da849b29f48f0c293684b71c0632625d4", size = 64051, upload-time = "2026-06-30T07:17:53.009Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/94/1f/a2dca5ffdbf1d475ffc4e80e4d5d720ff3a00f691795910116960ee12511/rpds_py-2026.6.3-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:7b689145a1485c335569bd056464f3243a29af7ed3871c7be31ad624ba239bc7", size = 342174, upload-time = "2026-06-30T07:14:54.821Z" }, + { url = "https://files.pythonhosted.org/packages/4d/dc/323d08583c0832911768663d1944f0107fcd4088704858d84b5e06d105a0/rpds_py-2026.6.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:db08f45aecde626498fb3df07bcf6d2ec040af42e859a4f5040d79c200342911", size = 345513, upload-time = "2026-06-30T07:14:56.515Z" }, + { url = "https://files.pythonhosted.org/packages/0b/2a/e31989834d18d2f26ec1d2774c5b1eb3331df4ea8ada525175294c94b48a/rpds_py-2026.6.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:acc992ab27b15f852c76755eb2ab7dce86585ddadba6fa5946e58556088845b4", size = 373783, upload-time = "2026-06-30T07:14:57.736Z" }, + { url = "https://files.pythonhosted.org/packages/87/fe/e80107ee3639585c9941c17d6a42cd65325022f656c023191fce78c324c8/rpds_py-2026.6.3-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7f88d653e7b3b779d71ae7454e20dcc9b6bae903f33c269db9f2be41bda3f261", size = 378316, upload-time = "2026-06-30T07:14:59.077Z" }, + { url = "https://files.pythonhosted.org/packages/22/6f/81e3adf81acfb6fa694de2a6e4e7d8863121e3e0799e0a7725e6cf5679c4/rpds_py-2026.6.3-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e52655eaf81e32593abedaa4bfe33170c8cfedf3365ed9be6e11e07f148f0278", size = 499423, upload-time = "2026-06-30T07:15:00.488Z" }, + { url = "https://files.pythonhosted.org/packages/2d/9a/41263969df0ce3d9af2a96d5005a288200af1989aed3354bfceb5fc0b21f/rpds_py-2026.6.3-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:dfcc8b909769d19db55c7cc9541eb64b9b774b1057ffffb4f1048070475bb9f9", size = 386077, upload-time = "2026-06-30T07:15:01.911Z" }, + { url = "https://files.pythonhosted.org/packages/5e/19/7e98f468bd50346faff5b10e5297374b443bfdddacc8e9fbc65984539597/rpds_py-2026.6.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9c1255b302953c86a486b81d330d5ee1d5bd937691ce271b6be0ef0e299eaab7", size = 371315, upload-time = "2026-06-30T07:15:03.317Z" }, + { url = "https://files.pythonhosted.org/packages/99/3c/2b973b4d371906a134b03decfea7f5d9835a2c6d263454392e15b64b5b18/rpds_py-2026.6.3-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:8d2294a31386bfa251d8c8a39472beee17db67d4f1a6eabea665d35c9a4461c3", size = 383502, upload-time = "2026-06-30T07:15:04.627Z" }, + { url = "https://files.pythonhosted.org/packages/98/2a/12e2799500af0a307bca76b63361c51f9fe479223561489c29eea1f2ee41/rpds_py-2026.6.3-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f8f23ead891a3b762f35ab3b04623da7056545b48aa60d59957e6789914545da", size = 402673, upload-time = "2026-06-30T07:15:05.856Z" }, + { url = "https://files.pythonhosted.org/packages/2d/e3/21e5872d165fe08be4f229e3d5ee9d90019c0bf0e5538de60dbd54009450/rpds_py-2026.6.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:421aba32367055614287a4292b6a17f1939c9452299f7a0209c117e990b646d4", size = 549964, upload-time = "2026-06-30T07:15:07.159Z" }, + { url = "https://files.pythonhosted.org/packages/1a/d0/5ee0fe36844297de8123bee27bc12078c1a7416ad9f1b8a8ca18d6b0c0ac/rpds_py-2026.6.3-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:1e5822dfc2f0d4ab7e745eaa6d85945069329beeccef965af3f3bb26058fcab6", size = 615446, upload-time = "2026-06-30T07:15:08.531Z" }, + { url = "https://files.pythonhosted.org/packages/b1/80/1ea5873cb683f2fbe5f21b23ea1f6d179ead19f3c5b249b7eb5dca568ef2/rpds_py-2026.6.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:83e35b57523816c8613fd0776b40cd8bb9f596b37ddd2692eb4a6bb5ab2f8c93", size = 576975, upload-time = "2026-06-30T07:15:09.97Z" }, + { url = "https://files.pythonhosted.org/packages/c9/e1/90ef639217a5ddb15b7f4f61b1c33911fd044ad03c311bafdd2bcab85582/rpds_py-2026.6.3-cp311-cp311-win32.whl", hash = "sha256:de3eceba0b683bcbb1ab93da016d0270df1f9ae7be716b40214c5dafac6ea45a", size = 204453, upload-time = "2026-06-30T07:15:11.324Z" }, + { url = "https://files.pythonhosted.org/packages/f2/b7/b7a1695d7af36f521fb11e80d6d3adbd744f73b921859bd3c2a2c0dc706f/rpds_py-2026.6.3-cp311-cp311-win_amd64.whl", hash = "sha256:2c54a076ca4d370980ab57bc0e31df57bbe8d41340436a90ef8b1219a3cbb127", size = 223219, upload-time = "2026-06-30T07:15:12.476Z" }, + { url = "https://files.pythonhosted.org/packages/d7/a2/145afacf796e4506062825941176ad9445c2dcf2b3b6a1f13d3030a15e19/rpds_py-2026.6.3-cp311-cp311-win_arm64.whl", hash = "sha256:168c733a7112e071bb7a66460e667edfcff06c017a3c523f7a8a8e08d0140804", size = 219137, upload-time = "2026-06-30T07:15:13.631Z" }, + { url = "https://files.pythonhosted.org/packages/5c/be/2e8974163072e7bab7df1a5acd54c4498e75e35d6d18b864d3a9d5dadc92/rpds_py-2026.6.3-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a0811d33247c3d6128a3001d763f2aa056bb3425204335400ac54f89eec3a0d0", size = 343691, upload-time = "2026-06-30T07:15:14.96Z" }, + { url = "https://files.pythonhosted.org/packages/a4/73/319dfa745dd668efe89309141ded489126461fcecd2b8f3a3cda185129b6/rpds_py-2026.6.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:538949e262e46caa31ac01bdb3c1e8f642622922cacbabbae6a8445d9dc33eaf", size = 338542, upload-time = "2026-06-30T07:15:16.267Z" }, + { url = "https://files.pythonhosted.org/packages/21/63/4239893be1c4d09b709b1a8f6be4188f0870084ff547f46606b8a75f1b03/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:55927d532399c2c646100ff7feb48eaa940ad70f42cd68e1328f3ded9f81ca24", size = 368180, upload-time = "2026-06-30T07:15:17.62Z" }, + { url = "https://files.pythonhosted.org/packages/1c/ca/9c5de382225234ceb37b1844ebdb140db12b2a278bb9efe2fcd19f6c82ce/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f56f1695bc5c0871cbc33dc0130fcf503aab0c57dcc5a6700a4f49eba4f2652e", size = 375067, upload-time = "2026-06-30T07:15:18.952Z" }, + { url = "https://files.pythonhosted.org/packages/87/dc/863f69d1bf04ade34b7fe0d59b9fdf6f0135fe2d7cbca74f1d665589559d/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:270b293dae9058fc9fcedab50f13cebf46fb8ed1d1d54e0521a9da5d6b211975", size = 490509, upload-time = "2026-06-30T07:15:20.434Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ef/eac16a12048b45ec7c7fa94f2be3438a5f26bf9cc8580b18a1cfd609b7f6/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:127565fead0a10943b282957bd5447804ff3160ad79f2ad2635e6d249e380680", size = 382754, upload-time = "2026-06-30T07:15:21.831Z" }, + { url = "https://files.pythonhosted.org/packages/04/8f/d2f3f532616be4d06c316ef119683e832bd3d41e112bf3a88f4151c95b17/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ecabd69db66de867690f9797f2f8fa27ba501bbc24540cbdbdc649cd15888ba6", size = 366189, upload-time = "2026-06-30T07:15:23.371Z" }, + { url = "https://files.pythonhosted.org/packages/e3/29/41a7b0e98a4b44cd676ab7598419623373eb43b20be68c084935c1a8cf88/rpds_py-2026.6.3-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:58eadac9cd119677b60e1cf8ac4052f35949d71b8a9e5556efccbe82533cf22a", size = 377750, upload-time = "2026-06-30T07:15:24.659Z" }, + { url = "https://files.pythonhosted.org/packages/2e/05/ecda0bec46f9a1565090bcdc941d023f6a25aff85fda28f89f8d19878152/rpds_py-2026.6.3-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:7491ee23305ac3eb59e492b6945881f5cd77a6f731061a3f25b77fd40f9e99a4", size = 395576, upload-time = "2026-06-30T07:15:25.987Z" }, + { url = "https://files.pythonhosted.org/packages/68/a8/6ed52f03ee6cb854ce78785cc9a9a672eb880e83fd7224d471f667d151f1/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2c99f7e8ccb3dd6e3e4bfeac657a7b208c9bac8075f4b078c02d7404c34107fa", size = 543807, upload-time = "2026-06-30T07:15:27.356Z" }, + { url = "https://files.pythonhosted.org/packages/8f/d6/156c0d3eea27ba09b92562ba2364ba124c0a061b199e17eac637cd25a5e2/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:62698275682bf121181861295c9181e789030a2d516071f5b8f3c23c170cd0fc", size = 611187, upload-time = "2026-06-30T07:15:28.931Z" }, + { url = "https://files.pythonhosted.org/packages/f1/31/774212ed989c62f7f310220089f9b0a3fb8f40f5443d1727abd5d9f52bc9/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a214c993455f99a89aaeadc9b21241900037adc9d97203e374d75513c5911822", size = 573030, upload-time = "2026-06-30T07:15:30.553Z" }, + { url = "https://files.pythonhosted.org/packages/c9/50/22f73127a41f1ce4f87fe39aadfb9a126345801c274aa93ae88456249327/rpds_py-2026.6.3-cp312-cp312-win32.whl", hash = "sha256:501f9f04a588d6a09179368c57071301445191767c64e4b52a6aa9871f1ef5ed", size = 202185, upload-time = "2026-06-30T07:15:32.027Z" }, + { url = "https://files.pythonhosted.org/packages/04/3a/f0ee4d4dde9d3b69dedf1b5f74e7a40017046d55052d173e418c6a94f960/rpds_py-2026.6.3-cp312-cp312-win_amd64.whl", hash = "sha256:2c958bf94822e9290a40aaf2a822d4bc5c88099093e3948ad6c571eca9272e5f", size = 220394, upload-time = "2026-06-30T07:15:33.359Z" }, + { url = "https://files.pythonhosted.org/packages/f3/83/3382fe37f809b59f02aac04dbc4e765b480b46ee0227ed516e3bdc4d3dfc/rpds_py-2026.6.3-cp312-cp312-win_arm64.whl", hash = "sha256:22bffe6042b9bcb0822bcd1955ec00e245daf17b4344e4ed8e9551b976b63e96", size = 215753, upload-time = "2026-06-30T07:15:34.778Z" }, + { url = "https://files.pythonhosted.org/packages/a4/9e/b818ee580026ec578138e961027a68820c40afeb1ec8f6819b54fb99e196/rpds_py-2026.6.3-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:3cfe765c1da0072636ca06628261e0ea05688e160d5c8a03e0217c3854037223", size = 343012, upload-time = "2026-06-30T07:15:36.005Z" }, + { url = "https://files.pythonhosted.org/packages/f3/6b/686d9dc4359a8f163cfbbf89ee0b4e586431de22fe8248edb63a8cf50d49/rpds_py-2026.6.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f4d78253f6996be4901669ad25319f842f740eccf4d58e3c7f3dd39e6dde1d8f", size = 338203, upload-time = "2026-06-30T07:15:37.462Z" }, + { url = "https://files.pythonhosted.org/packages/9e/9b/069aa329940f8207615e091f5eedbbd40e1e15eac68a0790fd05ccdf796c/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:54f45a148e28767bf343d33a684693c70e451c6f4c0e9904709a723fafbdfc1f", size = 367984, upload-time = "2026-06-30T07:15:39.008Z" }, + { url = "https://files.pythonhosted.org/packages/14/db/34c203e4becff3703e4d3bc121842c00b8689197f398161203a880052f4e/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:842e7b070435622248c7a2c44ae53fa1440e073cc3023bc919fed570884097a7", size = 374815, upload-time = "2026-06-30T07:15:40.253Z" }, + { url = "https://files.pythonhosted.org/packages/ee/7d/8071067d2cc453d916ad836e828c943f575e8a44612537759002a1e07381/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8020133a74bd81b4572dd8e4be028a6b1ebcd70e6726edc3918008c08bee6ee6", size = 490545, upload-time = "2026-06-30T07:15:41.729Z" }, + { url = "https://files.pythonhosted.org/packages/a3/42/da06c5aa8f0484ff07f270787434204d9f4535e2f8c3b51ed402267e63c3/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cdc7e35386f3847df728fbcb5e887e2d79c19e2fa1eba9e51b6621d23e3243af", size = 382828, upload-time = "2026-06-30T07:15:43.327Z" }, + { url = "https://files.pythonhosted.org/packages/57/d7/fe978efc2ae50abe48eb7464668ea99f53c010c60aeebb7b35ad27f23661/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:acac386b453c2516111b50985d60ce46e7fadb5ea71ae7b25f4c946935bf27cf", size = 365678, upload-time = "2026-06-30T07:15:44.992Z" }, + { url = "https://files.pythonhosted.org/packages/69/9d/1d8922e1990b2a6eb532b6ff53d3e73d2b3bbffc84116c75826bee73dfc6/rpds_py-2026.6.3-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:425560c6fa0415f27261727bb20bd097568485e5eb0c121f1949417d1c516885", size = 377811, upload-time = "2026-06-30T07:15:46.523Z" }, + { url = "https://files.pythonhosted.org/packages/b1/3d/198dceafb4fb034a6a47347e1b0735d34e0bd4a50be4e898d408ee66cb14/rpds_py-2026.6.3-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a550fb4950a06dde3beb4721f5ad4b25bf4513784665b0a8522c792e2bd822a4", size = 395382, upload-time = "2026-06-30T07:15:47.955Z" }, + { url = "https://files.pythonhosted.org/packages/1f/f1/13968e49655d40b6b19d8b9140296bbc6f1d86b3f0f6c346cf9f1adddf4b/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4f4bca01b63096f606e095734dd56e74e175f94cfbf24ff3d63281cec61f7bb7", size = 543832, upload-time = "2026-06-30T07:15:49.33Z" }, + { url = "https://files.pythonhosted.org/packages/ac/ab/289bcb1b90bd3e40a2900c561fa0e2087345ecbb094f0b870f2345142b7c/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ccffae9a092a00deb7efd545fe5e2c33c33b88e7c054337e9a74c179347d0b7d", size = 611011, upload-time = "2026-06-30T07:15:50.847Z" }, + { url = "https://files.pythonhosted.org/packages/1e/16/5043105e679436ccfbc8e5e0dd2d663ed18a8b8113515fd06a5e5d77c83e/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1cf01971c4f2c5553b772a542e4aaf191789cd331bc2cd4ff0e6e65ba49e1e97", size = 572431, upload-time = "2026-06-30T07:15:52.394Z" }, + { url = "https://files.pythonhosted.org/packages/85/ed/adab103321c0a6565d5ae1c2998349bc3ee175b82ccc5ae8fc04cc413075/rpds_py-2026.6.3-cp313-cp313-win32.whl", hash = "sha256:8c3d1e9c15b9d51ca0391e13da1a25a0a4df3c58a37c9dc368e0736cf7f69df0", size = 201710, upload-time = "2026-06-30T07:15:53.894Z" }, + { url = "https://files.pythonhosted.org/packages/7b/ed/a03b09668e74e5dabbf2e211f6468e1820c0552f7b0500082da31841bf7b/rpds_py-2026.6.3-cp313-cp313-win_amd64.whl", hash = "sha256:9250a9a0a6fd4648b3f868da8d91a4c52b5811a62df58e753d50ae4454a36f80", size = 219454, upload-time = "2026-06-30T07:15:55.25Z" }, + { url = "https://files.pythonhosted.org/packages/27/17/b8642c12930b71bc2b25831f6708ccf0f75abcd11883932ec9ce54ba3a78/rpds_py-2026.6.3-cp313-cp313-win_arm64.whl", hash = "sha256:900a67df3fd1660b035a4761c4ce73c382ea6b35f90f9863c36c6fd8bf8b09bb", size = 215063, upload-time = "2026-06-30T07:15:56.573Z" }, + { url = "https://files.pythonhosted.org/packages/b6/36/7fbe9dcdaf857fb3f63c2a2284b62492d95f5e8334e947e5fb6e7f68c9be/rpds_py-2026.6.3-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:931908d9fc855d8f74783377822be318edb6dcb19e47169dc038f9a1bf60b06e", size = 344510, upload-time = "2026-06-30T07:15:57.921Z" }, + { url = "https://files.pythonhosted.org/packages/ba/54/f785cc3d3f60839ca57a5af4927a9f347b07b2799c373fc20f7949f87c7e/rpds_py-2026.6.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d7469697dce35be237db177d42e2a2ee26e6dcc5fc052078a6fefabd288c6edd", size = 339495, upload-time = "2026-06-30T07:15:59.238Z" }, + { url = "https://files.pythonhosted.org/packages/63/ef/d4cdaf309e6b095b43597103cf8c0b951d6cca2acce68c474f75ec12e0c7/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bcfbcf66006befb9fd2aeaa9e01feaf881b4dc330a02ba07d2322b1c11be7b5d", size = 369454, upload-time = "2026-06-30T07:16:01.021Z" }, + { url = "https://files.pythonhosted.org/packages/96/4a/9559a68b7ee15db09d7981212e8c2e219d2a1d6d4faa0391d813c3496a36/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:847927daf4cffbd4e90e42bc890069897101edd015f956cb8721b3473372edda", size = 374583, upload-time = "2026-06-30T07:16:02.287Z" }, + { url = "https://files.pythonhosted.org/packages/ef/75/8964aa7d2c6e8ac43eba8eb6e6b0fdda1f46d39f2fc3e6aa9f2cb17f485d/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:aca6c1ef08a82bfe327cc156da694660f599923e2e6665b6d81c9c2d0ac9ffc8", size = 492919, upload-time = "2026-06-30T07:16:03.723Z" }, + { url = "https://files.pythonhosted.org/packages/8f/97/6908094ac804115e65aedfd90f1b5fee4eebebd3f6c4cfc5419939267565/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ae50181a047c871561212bb97f7932a2d45fb53e947bd9b57ebad85b529cbc53", size = 383725, upload-time = "2026-06-30T07:16:05.305Z" }, + { url = "https://files.pythonhosted.org/packages/d1/9c/0d1fdc2e7aba23e290d603bc494e97bd205bae262ce33c6b32a69768ed5e/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dc319e5a1de4b6913aac94bf6a2f9e847371e0a140a43dd4991db1a09bc2d504", size = 367255, upload-time = "2026-06-30T07:16:07.086Z" }, + { url = "https://files.pythonhosted.org/packages/c4/fe/f0209ca4a9ed074bc8acb44dfd0e81c3122e94c9689f5645b7973a866719/rpds_py-2026.6.3-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:e4316bf32babbed84e691e352faf967ce2f0f024174a8643c37c94a1080374fc", size = 379060, upload-time = "2026-06-30T07:16:08.525Z" }, + { url = "https://files.pythonhosted.org/packages/c6/8d/f1cc54c616b9d8897de8738aac148d20afca93f68187475fe194d09a71b9/rpds_py-2026.6.3-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8c6e5a2f750cc71c3e3b11d71661f21d6f9bc6cebc6564b1466417a1ec03ec77", size = 395960, upload-time = "2026-06-30T07:16:09.989Z" }, + { url = "https://files.pythonhosted.org/packages/fb/04/aafff00f73aeca2945f734f1d483c64ab8f472d0864ab02377fd8e89c3b2/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:4470ce197d4090875cf6affbf1f853338387428df97c4fb7b7106317b8214698", size = 545356, upload-time = "2026-06-30T07:16:11.816Z" }, + { url = "https://files.pythonhosted.org/packages/fd/cc/e229663b9e4ddac5a4acbe9085dd80a71af2a5d356b8b39d6bff233f24b0/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:ea964164cc9afa72d4d9b23cc28dafae93693c0a53e0b42acbff15b22c3f9ddd", size = 612319, upload-time = "2026-06-30T07:16:13.586Z" }, + { url = "https://files.pythonhosted.org/packages/e3/7a/8a0e6d3e6cd066af108b71b43122c3fe158dd9eb86acac626593a2582eb1/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:639c8929aa0afe81be836b04de888460d6bed38b9c54cfc18da8f6bfabf5af5d", size = 573508, upload-time = "2026-06-30T07:16:15.23Z" }, + { url = "https://files.pythonhosted.org/packages/87/03/2a69ab618a789cf6cf85c86bb844c62d090e700ab1a2aa676b3741b6c516/rpds_py-2026.6.3-cp314-cp314-win32.whl", hash = "sha256:882076c00c0a608b131187055ddc5ae29f2e7eaf870d6168980420d58528a5c8", size = 202504, upload-time = "2026-06-30T07:16:16.893Z" }, + { url = "https://files.pythonhosted.org/packages/85/62/a3892ba945f4e24c78f352e5de3c7620d8479f73f211406a97263d13c7d2/rpds_py-2026.6.3-cp314-cp314-win_amd64.whl", hash = "sha256:0be972be84cfcaf46c8c6edf690ca0f154ac17babf1f6a955a51579b34ad2dc5", size = 220380, upload-time = "2026-06-30T07:16:18.108Z" }, + { url = "https://files.pythonhosted.org/packages/3d/e7/c2bd44dc831931815ad11ebb5f430b5a0a4d3caa9de837107876c30c3432/rpds_py-2026.6.3-cp314-cp314-win_arm64.whl", hash = "sha256:2a9c6f195058cb45335e8cc3802745c603d716eb96bc9625950c1aac71c0c703", size = 215976, upload-time = "2026-06-30T07:16:19.654Z" }, + { url = "https://files.pythonhosted.org/packages/79/9c/fff7b74bce9a091ec9a012a03f9ff5f69364eaf9451060dfc4486da2ffdd/rpds_py-2026.6.3-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:f90938e92afda60266da758ee7d363447f7f0138c9559f9e1811629580582d90", size = 346840, upload-time = "2026-06-30T07:16:21.268Z" }, + { url = "https://files.pythonhosted.org/packages/e9/44/77bcb1168b33704908295533d27f10eb811e9e3e193e8993dc99572211d3/rpds_py-2026.6.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ec829541c45bca16e61c7ae50c20501f213605beb75d1aba91a6ee37fbbb56a4", size = 340282, upload-time = "2026-06-30T07:16:22.875Z" }, + { url = "https://files.pythonhosted.org/packages/87/3c/7a9081c7c9e645b39efe19e4ffbeccd80add246327cd9b888aecffd72317/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afd70d95892096cdb26f15a00c45907b17817577aa8d1c76b2dcc2788391f9e9", size = 370403, upload-time = "2026-06-30T07:16:24.415Z" }, + { url = "https://files.pythonhosted.org/packages/f7/69/af47021eb7dad6ff3396cb001c08f0f3c4d06c20253f75be6421a59fe6b7/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:29dfa0533a5d4c94d4dfa1b694fcb56c9c63aad8330ffdd816fd225d0a7a162f", size = 376055, upload-time = "2026-06-30T07:16:26.111Z" }, + { url = "https://files.pythonhosted.org/packages/81/fc/a3bcf517084396a6dd258c592567a3c011ba4557f2fde23dceaf26e74f2e/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:af05d726809bff6b141be124d4c7ce998f9c9c7f30edb1f46c07aa103d540b41", size = 494419, upload-time = "2026-06-30T07:16:27.596Z" }, + { url = "https://files.pythonhosted.org/packages/c9/eb/13d529d1788135425c7bf207f8463458ca5d92e43f3f701365b83e9dffc1/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9826217f048f620d9a712672818bf231442c1b35d96b227a07eabd11b4bb6945", size = 384848, upload-time = "2026-06-30T07:16:29.183Z" }, + { url = "https://files.pythonhosted.org/packages/8e/f4/b7ac49f30013aba8f7b9566b1dd07e81de95e708c1374b7bacc5b9bc5c9c/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:536bceea4fa4acf7e1c61da2b5786304367c816c8895be71b8f537c480b0ea1f", size = 371369, upload-time = "2026-06-30T07:16:30.912Z" }, + { url = "https://files.pythonhosted.org/packages/31/86/6260bafa622f788b07ddec0e52d810305c8b9b0b8c27f58a2ab04bf62b4f/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:bc0011654b91cc4fb2ae701bec0a0ba1e552c0714247fa7af6c59e0ccfa3a4e1", size = 379673, upload-time = "2026-06-30T07:16:32.486Z" }, + { url = "https://files.pythonhosted.org/packages/19/c3/03f1ee79a047b48daeca157c89a18509cde22b6b951d642b9b0af1be660a/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:539d75de9e0d536c84ff18dfeb805398e58227001ce09231a26a08b9aed1ee0e", size = 397500, upload-time = "2026-06-30T07:16:34.471Z" }, + { url = "https://files.pythonhosted.org/packages/f0/95/8ed0cd8c377dca12aea498f119fe639fc474d1461545c39d2b5872eb1c0f/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:166cf54d9f44fc6ceb53c7860258dde44a81406646de79f8ed3234fca3b6e538", size = 545978, upload-time = "2026-06-30T07:16:36.45Z" }, + { url = "https://files.pythonhosted.org/packages/d3/f2/0eb57f0eaa83f8fc152a7e03de968ab77e1f00732bebc892b190c6eebde7/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:d34c20167764fbcf927194d532dd7e0c56772f0a5f943fa5ef9e9afbba8fb9db", size = 613350, upload-time = "2026-06-30T07:16:38.213Z" }, + { url = "https://files.pythonhosted.org/packages/5b/de/e0674bdbc3ef7634989b3f854c3f34bc1f587d36e5bfdc5c378d57034619/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ea7bb13b7c9a29791f87a0387ba7d3ad3a6d783d827e4d3f27b40a0ff44495e2", size = 576486, upload-time = "2026-06-30T07:16:39.797Z" }, + { url = "https://files.pythonhosted.org/packages/f2/f6/21101359743cd136ada781e8210a85769578422ba460672eea0e29739200/rpds_py-2026.6.3-cp314-cp314t-win32.whl", hash = "sha256:6de4744d05bd1aa1be4ed7ea1189e3979196808008113bbbf899a460966b925e", size = 201068, upload-time = "2026-06-30T07:16:41.316Z" }, + { url = "https://files.pythonhosted.org/packages/a6/b2/9574d4d44f7760c2aa32d92a0a4f41698e33f5b204a0bf5c9758f52c79d5/rpds_py-2026.6.3-cp314-cp314t-win_amd64.whl", hash = "sha256:c7b9a2f8f4d8e90af72571d3d495deebdd7e3c75451f5b41719aee166e940fc2", size = 220600, upload-time = "2026-06-30T07:16:43.091Z" }, + { url = "https://files.pythonhosted.org/packages/08/ae/f23a2697e6ee6340a578b0f136be6483657bef0c6f9497b752bb5c0964bb/rpds_py-2026.6.3-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:e059c5dde6452b44424bd1834557556c226b57781dee1227af23518459722b13", size = 344726, upload-time = "2026-06-30T07:16:44.5Z" }, + { url = "https://files.pythonhosted.org/packages/c3/63/e7b3a1a5358dd32c930a1062d8e15b67fd6e8922e81df9e91706d66ee5c8/rpds_py-2026.6.3-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2f7c26fbc5acd2522b95d4177fe4710ffd8e9b20529e703ffbf8db4d93903f05", size = 339587, upload-time = "2026-06-30T07:16:46.255Z" }, + { url = "https://files.pythonhosted.org/packages/ec/64/10a85681916ca55fffb91b0a211f84e34297c109243484dd6394660a8a7c/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a3086b538543802f84c843911242db20447de00d8752dd0efc936dbcf02218ba", size = 369585, upload-time = "2026-06-30T07:16:48.101Z" }, + { url = "https://files.pythonhosted.org/packages/76/c2/baf95c7c38823e12ba34407c5f5767a89e5cf2233895e56f608167ae9493/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8f2e5c5ee828d42cb11760761c0af6507927bec42d0ad5458f97c9203b054617", size = 375479, upload-time = "2026-06-30T07:16:49.93Z" }, + { url = "https://files.pythonhosted.org/packages/6a/94/0aad06c72d65101e11d33528d438cda99a39ce0da99466e156158f2541d3/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ed0c1e5d10cdc7135537988c74a0188da68e2f3c30813ba3744ab1e42e0480f9", size = 492418, upload-time = "2026-06-30T07:16:51.641Z" }, + { url = "https://files.pythonhosted.org/packages/b5/17/de3f5a479a1f056535d7489819639d8cd591ea6281d700390b43b1abd745/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8c2642a7603ec0b16ed77da4555db3b4b472341904873788327c0b0d7b95f1bb", size = 384123, upload-time = "2026-06-30T07:16:53.622Z" }, + { url = "https://files.pythonhosted.org/packages/46/7d/bf09bd1b145bb2671c03e1e6d1ab8651858d90d8c7dfeadd85a37a934fd8/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8e4320744c1ffdd95a603def63344bfab2d33edeab301c5007e7de9f9f5b3885", size = 367351, upload-time = "2026-06-30T07:16:55.241Z" }, + { url = "https://files.pythonhosted.org/packages/a3/ea/1bb734f314b8be319149ddee80b18bd41372bdcfbdf88d28131c0cd37719/rpds_py-2026.6.3-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:a9f4645593036b81bbdb36b9c8e0ea0d1c3fee968c4d59db0344c14087ef143a", size = 378827, upload-time = "2026-06-30T07:16:56.841Z" }, + { url = "https://files.pythonhosted.org/packages/4b/93/d9611e5b25e26df9a3649813ed66193ace9347a7c7fc4ab7cf70e94851c0/rpds_py-2026.6.3-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e55d236be29255554da47abe5c577637db7c24a02b8b46f0ca9524c855801868", size = 395966, upload-time = "2026-06-30T07:16:58.557Z" }, + { url = "https://files.pythonhosted.org/packages/c3/cb/99d77e16e5534ae1d90629bbe419ba6ee170833a6a85e3aa1cc41726fbbc/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:24e9c5386e16669b674a69c156c8eeefcb578f3b3397b713b08e6d60f3c7b187", size = 545680, upload-time = "2026-06-30T07:17:00.164Z" }, + { url = "https://files.pythonhosted.org/packages/59/15/11a29755f790cef7a2f755e8e14f4f0c33f39489e1893a632a2eee59672b/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:c60924535c75f1566b6eb75b5c31a48a43fef04fa2d0d201acbad8a9969c6107", size = 611853, upload-time = "2026-06-30T07:17:01.962Z" }, + { url = "https://files.pythonhosted.org/packages/68/86/0c27547e21644da938fb530f7e1a8148dd24d02db07e7a5f2567a17ce710/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:38a2fea2787428f811719ceb9114cb78964a3138838320c29ac39526c79c16ba", size = 573715, upload-time = "2026-06-30T07:17:03.693Z" }, + { url = "https://files.pythonhosted.org/packages/29/71/4d8fcf700931815594bce892255bbd973b94efaf0fc1932b0590df18d886/rpds_py-2026.6.3-cp315-cp315-win32.whl", hash = "sha256:d483fe17f01ad64b7bf7cc38fcefff1ca9fb83f8c2b2542b68f97ffe0611b369", size = 202864, upload-time = "2026-06-30T07:17:05.746Z" }, + { url = "https://files.pythonhosted.org/packages/eb/62/b577562de0edbb55b2be85ce5fd09c33e386b9b13eee09833af4240fd5c4/rpds_py-2026.6.3-cp315-cp315-win_amd64.whl", hash = "sha256:67e3a721ffc5d8d2210d3671872298c4a84e4b8035cfe42ffd7cde35d772b146", size = 220430, upload-time = "2026-06-30T07:17:07.471Z" }, + { url = "https://files.pythonhosted.org/packages/c8/95/d6d0b2509825141eef60669a5739eec88dbc6a48053d6c92993a5704defe/rpds_py-2026.6.3-cp315-cp315-win_arm64.whl", hash = "sha256:6e84adbcf4bf841aed8116a8264b9f50b4cb3e7bd89b516122e616ac56ca269e", size = 215877, upload-time = "2026-06-30T07:17:09.008Z" }, + { url = "https://files.pythonhosted.org/packages/b7/bf/f3ea278f0afd615c1d0f19cb69043a41526e2bb600c2b536eb192218eb27/rpds_py-2026.6.3-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:ae6dd8f10bd17aad820876d24caec9efdafd80a318d16c0a48edb5e136902c6b", size = 346933, upload-time = "2026-06-30T07:17:10.762Z" }, + { url = "https://files.pythonhosted.org/packages/9d/29/9907bdf1c5346763cf10b7f6852aad86652168c259def904cbe0082c5864/rpds_py-2026.6.3-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:bdbd97738551fca3917c1bd7188bec1920bb520104f28e7e1007f9ceb17b7690", size = 340274, upload-time = "2026-06-30T07:17:12.266Z" }, + { url = "https://files.pythonhosted.org/packages/6f/2c/8e03767b5778ef25cebf74a7a91a2c3806f8eced4c92cb7406bbe060756d/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8b95977e7211527ab0ba576e286d023389fbeeb32a6b7b771665d333c60e5342", size = 370763, upload-time = "2026-06-30T07:17:14.107Z" }, + { url = "https://files.pythonhosted.org/packages/2e/e1/df2a7e1ba2efd796af26194250b8d42c821b46592311595162af9ef0528d/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d15fde0e6fb0d88a60d221204873743e5d9f0b7d29165e62cd86d0413ad74ba6", size = 376467, upload-time = "2026-06-30T07:17:15.76Z" }, + { url = "https://files.pythonhosted.org/packages/6b/de/8a0814d1946af29cb068fb259aa8622f856df1d0bab58429448726b537f5/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a136d453475ac0fcbda502ef1e6504bd28d6d904700915d278deeab0d00fe140", size = 496689, upload-time = "2026-06-30T07:17:17.308Z" }, + { url = "https://files.pythonhosted.org/packages/df/f3/f19e0c852ba13694f5a79f3b719331051573cb5693feacf8a88ffffc3a71/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f826877d462181e5eb1c26a0026b8d0cab05d99844ecb6d8bf3627a2ca0c0442", size = 385340, upload-time = "2026-06-30T07:17:18.928Z" }, + { url = "https://files.pythonhosted.org/packages/e2/ae/7ec3a9d2d4351f99e37bcb06b6b6f954512646bfdbf9742e1de727865daf/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:79486287de1730dbaff3dbd124d0ca4d2ef7f9d29bf2544f1f93c09b5bcbbd12", size = 372179, upload-time = "2026-06-30T07:17:20.539Z" }, + { url = "https://files.pythonhosted.org/packages/d3/ac/9cee911dff2aaa9a5a8354f6610bf2e6a616de9197c5fff4f54f82585f1e/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:808345f53cb952433ca2816f1604ff3515608a81784954f38d4452acfe8e61d5", size = 379993, upload-time = "2026-06-30T07:17:22.212Z" }, + { url = "https://files.pythonhosted.org/packages/83/6b/7c2a07ba88d1e9a936612f7a5d067467ed03d971d5a06f7d309dff044a7e/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1967debc37f64f2c4dc90a7f563aec558b471966e12adcac4e1c4240496b6ebf", size = 398909, upload-time = "2026-06-30T07:17:23.66Z" }, + { url = "https://files.pythonhosted.org/packages/97/0b/776ffcb66783637b0031f6d58d6fb55913c8b5abf00aeecd46bf933fb477/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:f0840b5b17057f7fd918b76183a4b5a0635f43e14eb2ce60dce1d4ee4707ea00", size = 546584, upload-time = "2026-06-30T07:17:25.264Z" }, + { url = "https://files.pythonhosted.org/packages/55/33/ba3bc04d7092bd553c9b2b195624992d2cc4f3de1f380b7b93cbee67bd79/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:faa679d19a6696fd54259ad321251ad77a13e70e03dd834daa762a44fb6196ef", size = 614357, upload-time = "2026-06-30T07:17:26.888Z" }, + { url = "https://files.pythonhosted.org/packages/8b/71/14edf065f04630b1a8472f7653cad03f6c478bcf95ea0e6aed55451e33ea/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:23a439f31ccbeff1574e24889128821d1f7917470e830cf6544dced1c662262a", size = 576533, upload-time = "2026-06-30T07:17:28.546Z" }, + { url = "https://files.pythonhosted.org/packages/ba/76/65002b08596c389105720a8c0d22298b8dc25a4baf89b2ce431343c8b1de/rpds_py-2026.6.3-cp315-cp315t-win32.whl", hash = "sha256:913ca42ccad3f8cc6e292b587ae8ae49c8c823e5dce51a736252fc7c7cdfa577", size = 201204, upload-time = "2026-06-30T07:17:30.193Z" }, + { url = "https://files.pythonhosted.org/packages/8c/97/d855d6b3c322d1f27e26f5241c42016b56cf01377ea8ed348285f54652f0/rpds_py-2026.6.3-cp315-cp315t-win_amd64.whl", hash = "sha256:ae3d4fe8c0b9213624fdce7279d70e3b148b682ca20719ebd193a23ebfa47324", size = 220719, upload-time = "2026-06-30T07:17:31.788Z" }, + { url = "https://files.pythonhosted.org/packages/b4/9c/f0d19ac587fd0e4ab6b72cda355e9c5a6166b01ef7e064e437aef8eb9fef/rpds_py-2026.6.3-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:4cf2d36a2357e4d07bb5a4f98801265327b48256867816cfd2ceb001e9754a8f", size = 349791, upload-time = "2026-06-30T07:17:33.315Z" }, + { url = "https://files.pythonhosted.org/packages/38/c7/1d49d204c9fd2ee6c537601dc4c1ba921e03363ca576bfab94a00254ac9a/rpds_py-2026.6.3-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:30c6dc199b24a5e3e81d50da0f00858c5bbdb2617a750395687f4339c5818171", size = 352842, upload-time = "2026-06-30T07:17:34.897Z" }, + { url = "https://files.pythonhosted.org/packages/ac/e5/c0b5dc93cd0d4c06ce1f438907649514e2ea077bcd911e3154a51e96c38e/rpds_py-2026.6.3-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9891e594296ab9dada6551c8e7b387b2721f27a67eecd528412e8906247a7b90", size = 382094, upload-time = "2026-06-30T07:17:36.514Z" }, + { url = "https://files.pythonhosted.org/packages/0d/54/ec0e907b4ca8d541112db352409bd15f871c9b243e0c92c9b5a46ae96f01/rpds_py-2026.6.3-pp311-pypy311_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:b5c2dc92304aa48a4a60443b548bb12f12e119d4b72f314015e67b9e1be97fca", size = 388662, upload-time = "2026-06-30T07:17:38.235Z" }, + { url = "https://files.pythonhosted.org/packages/d3/f4/921c22a4fd0f1c1ac13a3996ffbf0aa67951e2c8ad0d1d9574938a2932e8/rpds_py-2026.6.3-pp311-pypy311_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:127e08c0642d880cf32ca47ec2a4a77b901f7e2dd1ad9762adb13955d72ffcc9", size = 504896, upload-time = "2026-06-30T07:17:39.689Z" }, + { url = "https://files.pythonhosted.org/packages/0b/1b/a114b972cefa1ab1cdb3c7bb177cd3844a12826c507c722d3a73516dbbaf/rpds_py-2026.6.3-pp311-pypy311_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8bb68f03f395eb793220b45c097bd4d8c32944393da0fad8b999efac0868fc8c", size = 391545, upload-time = "2026-06-30T07:17:41.336Z" }, + { url = "https://files.pythonhosted.org/packages/4e/98/af9b3db77d47fcbe6c8c1f36e2c2147ec70292819e99c325f871584a1c11/rpds_py-2026.6.3-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a3450b693fde92133e9f51060568a4c31fcca76d5e53bbd611e689ca446517e9", size = 380059, upload-time = "2026-06-30T07:17:42.857Z" }, + { url = "https://files.pythonhosted.org/packages/c9/ba/0efd8668b97c1d26a61566386c636a7a7a09829e474fdf807caa15a2c844/rpds_py-2026.6.3-pp311-pypy311_pp73-manylinux_2_31_riscv64.whl", hash = "sha256:5e8d07bddee435a2ff6f1920e18feff28d0bc4533e42f4bf6927fbd073312c41", size = 393235, upload-time = "2026-06-30T07:17:44.637Z" }, + { url = "https://files.pythonhosted.org/packages/62/90/8c139ee9690f73b0829f32647de6f40d826f8f443af6fa72644f96351aac/rpds_py-2026.6.3-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:3a83ae6c67b7676b9878378547ca8e93ed77a580037bcbcd1d32f739e1e6089c", size = 413008, upload-time = "2026-06-30T07:17:46.225Z" }, + { url = "https://files.pythonhosted.org/packages/9c/97/0043896fdd7828ce09a1d9a8b06433714d0960fc4ff3fc4aa72b666b764e/rpds_py-2026.6.3-pp311-pypy311_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:2bfd04c19ddbd6640de0b51894d764bd2758854d5b75bd102d2ef10cb9c293a9", size = 558118, upload-time = "2026-06-30T07:17:47.759Z" }, + { url = "https://files.pythonhosted.org/packages/f6/40/02355f0e134f783a8f9814c4680a1bd311d37671577a5964ea838573ff37/rpds_py-2026.6.3-pp311-pypy311_pp73-musllinux_1_2_i686.whl", hash = "sha256:ca6546b66be9dc4738b1b043d5ebd5488c66c578c5ff0fd0e8065313fe3afb76", size = 623138, upload-time = "2026-06-30T07:17:49.355Z" }, + { url = "https://files.pythonhosted.org/packages/10/85/48f0abdcef5cce4e034c7a5b0ceeceba0b01bf0d942824f4bb720afe2dec/rpds_py-2026.6.3-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:8e65860d238379ed982fd9ba690579b5e95af2f4840f99c772816dbe573cb826", size = 586486, upload-time = "2026-06-30T07:17:51.141Z" }, +] + [[package]] name = "ruff" version = "0.15.7" @@ -577,6 +1289,32 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8f/e8/726643a3ea68c727da31570bde48c7a10f1aa60eddd628d94078fec586ff/ruff-0.15.7-py3-none-win_arm64.whl", hash = "sha256:18e8d73f1c3fdf27931497972250340f92e8c861722161a9caeb89a58ead6ed2", size = 11023304, upload-time = "2026-03-19T16:26:51.669Z" }, ] +[[package]] +name = "sse-starlette" +version = "3.4.8" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "starlette" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f8/00/b42a44342a054d58cb1115d7c8aa9cb4290dd9442f9c1b91a4b8173dba22/sse_starlette-3.4.8.tar.gz", hash = "sha256:ed89ffbb75cbf78a5fe2f2109cd584792ee7f9dfac96f791db546df8f15f3f9c", size = 32548, upload-time = "2026-08-05T11:19:49.982Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dd/3a/764912c58293d95b6dcdf4cc255f9d10de310580ced547b082eb9d72018c/sse_starlette-3.4.8-py3-none-any.whl", hash = "sha256:6e82314c786709a3cd9520f2285cf9fff90e181e598e8a357b0cf80f66afba0d", size = 16516, upload-time = "2026-08-05T11:19:48.748Z" }, +] + +[[package]] +name = "starlette" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b5/b4/205b0d5241d934e8add0c38aa924c4f9fb7330834ff11e5444db964ec3f9/starlette-1.6.0.tar.gz", hash = "sha256:d4e3ac5e546444960c710297a3c9fc3f7ebae1b7e963f3d36173b49da535be9b", size = 2716969, upload-time = "2026-08-08T18:27:57.512Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c8/cb/6a6a47d5b464bd08695d254f3da6e7986cc70c9fa5d778eda57538edfe56/starlette-1.6.0-py3-none-any.whl", hash = "sha256:a86dd39d14bb45f85a3d18525215a9ef0cfd1f192ac793220e72598c90335f0c", size = 75969, upload-time = "2026-08-08T18:27:56.196Z" }, +] + [[package]] name = "tomli" version = "2.4.0" @@ -651,3 +1389,17 @@ sdist = { url = "https://files.pythonhosted.org/packages/55/e3/70399cb7dd41c10ac wheels = [ { url = "https://files.pythonhosted.org/packages/dc/9b/47798a6c91d8bdb567fe2698fe81e0c6b7cb7ef4d13da4114b41d239f65d/typing_inspection-0.4.2-py3-none-any.whl", hash = "sha256:4ed1cacbdc298c220f1bd249ed5287caa16f34d44ef4e9c3d0cbad5b521545e7", size = 14611, upload-time = "2025-10-01T02:14:40.154Z" }, ] + +[[package]] +name = "uvicorn" +version = "0.52.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "h11" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/03/18/ccce41535dee1be77735592bd19965f3972c82e07ee703d324709496b716/uvicorn-0.52.1.tar.gz", hash = "sha256:112ec661814189acbccd3f7b86460147cc065fc92c0821afa78918780e4354dd", size = 100571, upload-time = "2026-08-01T18:19:30.732Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c7/d5/68e6e9bca63c0badf67002890a46d3784c958de45b65e1275ec583ca1f06/uvicorn-0.52.1-py3-none-any.whl", hash = "sha256:e4403f9d93188cf9d1088e9f40e3acd12630e2df8675316704379a7fc20fff6a", size = 79859, upload-time = "2026-08-01T18:19:29.294Z" }, +] From a5d7ff9c8648a1ed179db89fa766ac8063785a7f Mon Sep 17 00:00:00 2001 From: User Date: Tue, 11 Aug 2026 17:29:34 -0700 Subject: [PATCH 02/30] refactor: make in-process MCP server deps an optional extra Core install now depends only on pydantic and typing-extensions; mcp/starlette/uvicorn move to the "droid-sdk[mcp]" extra. Importing droid_sdk.mcp without the extra raises a clear ImportError, and external MCP server configs stay importable from the package root. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- README.md | 8 +++++--- docs/python-sdk-reference.md | 14 ++++++++++++-- pyproject.toml | 12 +++++++++++- src/droid_sdk/mcp.py | 24 ++++++++++++++++-------- tests/test_v5_mcp.py | 20 ++++++++++++++++++++ uv.lock | 21 +++++++++++++++++---- 6 files changed, 81 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index e8a0899..2aeb9ae 100644 --- a/README.md +++ b/README.md @@ -129,9 +129,11 @@ a no-op. ## MCP and custom runtime -External stdio, HTTP, and SSE configs live in `droid_sdk.mcp`. Annotated -Python functions can be exposed through an authenticated loopback-only -Streamable HTTP server: +External stdio, HTTP, and SSE configs are importable from the package root. +Annotated Python functions can be exposed through an authenticated +loopback-only Streamable HTTP server; this in-process server support lives in +`droid_sdk.mcp` and requires the `mcp` extra +(`pip install "droid-sdk[mcp]"`): ```python from droid_sdk import SessionConfig diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index ec79b1c..3a1e82a 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -26,6 +26,12 @@ interruption, compaction, or rewind. `Session` does not have a `run()` method. pip install droid-sdk ``` +In-process MCP tool servers (`droid_sdk.mcp`) need the `mcp` extra: + +```bash +pip install "droid-sdk[mcp]" +``` + Requirements: - Python 3.10 or later @@ -1259,7 +1265,9 @@ Skills may come from project, personal, built-in, or automation settings. ### In-process MCP tools -Use `@tool` to expose an annotated Python function: +In-process servers require the `mcp` extra +(`pip install "droid-sdk[mcp]"`). Use `@tool` to expose an annotated Python +function: ```python from droid_sdk.mcp import create_sdk_mcp_server, tool @@ -1309,8 +1317,10 @@ the server. Sessions normally own these calls. ### External MCP servers +External server configs do not need the `mcp` extra: + ```python -from droid_sdk.mcp import HttpMcpServerConfig, StdioMcpServerConfig +from droid_sdk import HttpMcpServerConfig, StdioMcpServerConfig config = SessionConfig( mcp_servers=[ diff --git a/pyproject.toml b/pyproject.toml index 0b5b8ed..996906a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,8 +6,13 @@ readme = "README.md" license = {text = "Apache-2.0"} requires-python = ">=3.10" dependencies = [ - "mcp>=1.27,<2", "pydantic>=2.0", + "typing-extensions>=4.4", +] + +[project.optional-dependencies] +mcp = [ + "mcp>=1.27,<2", "starlette>=0.40", "uvicorn>=0.31,<1", ] @@ -20,6 +25,11 @@ dev = [ "pyright", "ruff", "pytest-cov", + # The dev environment always includes the "mcp" extra's dependencies so + # the in-process MCP server tests run without extra flags. + "mcp>=1.27,<2", + "starlette>=0.40", + "uvicorn>=0.31,<1", ] [build-system] diff --git a/src/droid_sdk/mcp.py b/src/droid_sdk/mcp.py index 422b1d7..b368da2 100644 --- a/src/droid_sdk/mcp.py +++ b/src/droid_sdk/mcp.py @@ -14,15 +14,23 @@ from dataclasses import dataclass, field from typing import Any, ParamSpec, cast, get_type_hints, overload -import uvicorn -from mcp import types as mcp_types -from mcp.server.lowlevel import Server as McpServer -from mcp.server.streamable_http_manager import StreamableHTTPSessionManager +try: + import uvicorn + from mcp import types as mcp_types + from mcp.server.lowlevel import Server as McpServer + from mcp.server.streamable_http_manager import StreamableHTTPSessionManager + from starlette.applications import Starlette + from starlette.responses import JSONResponse, Response + from starlette.routing import Route + from starlette.types import Receive, Scope, Send +except ImportError as _missing_extra: + raise ImportError( + "In-process MCP servers require the 'mcp' extra: " + 'pip install "droid-sdk[mcp]". External MCP server configs are ' + "importable from the droid_sdk package root without it." + ) from _missing_extra + from pydantic import ConfigDict, TypeAdapter, create_model -from starlette.applications import Starlette -from starlette.responses import JSONResponse, Response -from starlette.routing import Route -from starlette.types import Receive, Scope, Send from droid_sdk._high_level._immutable import FrozenJsonValue, thaw_json from droid_sdk._high_level.extensions import ( diff --git a/tests/test_v5_mcp.py b/tests/test_v5_mcp.py index 58b60df..eaea2d5 100644 --- a/tests/test_v5_mcp.py +++ b/tests/test_v5_mcp.py @@ -1,6 +1,8 @@ from __future__ import annotations import asyncio +import importlib +import sys from datetime import datetime, timezone from typing import TYPE_CHECKING @@ -50,6 +52,24 @@ def aliased() -> AliasedOutput: ) +def test_mcp_module_requires_extra(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delitem(sys.modules, "droid_sdk.mcp", raising=False) + monkeypatch.setitem(sys.modules, "uvicorn", None) + with pytest.raises(ImportError, match=r"droid-sdk\[mcp\]"): + importlib.import_module("droid_sdk.mcp") + + +def test_package_root_imports_without_mcp_extra( + monkeypatch: pytest.MonkeyPatch, +) -> None: + for name in ("uvicorn", "starlette", "mcp"): + monkeypatch.setitem(sys.modules, name, None) + for name in [key for key in sys.modules if key.split(".")[0] == "droid_sdk"]: + monkeypatch.delitem(sys.modules, name) + module = importlib.import_module("droid_sdk") + assert module.StdioMcpServerConfig is not None + + @pytest.mark.asyncio async def test_tool_validates_arguments_for_sync_and_async_handlers() -> None: result = await add.handler({"a": 2, "b": 3}) diff --git a/uv.lock b/uv.lock index dd8d620..79e6b2d 100644 --- a/uv.lock +++ b/uv.lock @@ -371,38 +371,51 @@ name = "droid-sdk" version = "0.1.3" source = { editable = "." } dependencies = [ - { name = "mcp" }, { name = "pydantic" }, + { name = "typing-extensions" }, +] + +[package.optional-dependencies] +mcp = [ + { name = "mcp" }, { name = "starlette" }, { name = "uvicorn" }, ] [package.dev-dependencies] dev = [ + { name = "mcp" }, { name = "mypy" }, { name = "pyright" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-cov" }, { name = "ruff" }, + { name = "starlette" }, + { name = "uvicorn" }, ] [package.metadata] requires-dist = [ - { name = "mcp", specifier = ">=1.27,<2" }, + { name = "mcp", marker = "extra == 'mcp'", specifier = ">=1.27,<2" }, { name = "pydantic", specifier = ">=2.0" }, - { name = "starlette", specifier = ">=0.40" }, - { name = "uvicorn", specifier = ">=0.31,<1" }, + { name = "starlette", marker = "extra == 'mcp'", specifier = ">=0.40" }, + { name = "typing-extensions", specifier = ">=4.4" }, + { name = "uvicorn", marker = "extra == 'mcp'", specifier = ">=0.31,<1" }, ] +provides-extras = ["mcp"] [package.metadata.requires-dev] dev = [ + { name = "mcp", specifier = ">=1.27,<2" }, { name = "mypy" }, { name = "pyright" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-cov" }, { name = "ruff" }, + { name = "starlette", specifier = ">=0.40" }, + { name = "uvicorn", specifier = ">=0.31,<1" }, ] [[package]] From d7829decece03307dfac49bec9565f5527491b6e Mon Sep 17 00:00:00 2001 From: User Date: Tue, 11 Aug 2026 17:36:23 -0700 Subject: [PATCH 03/30] refactor: remove low-level client dependency on the high-level layer DroidClient no longer imports InteractionDispatcher or carries a second handler mechanism. Session owns one dispatcher and registers it through the existing set_permission_handler/set_ask_user_handler slots, swapping only the dispatcher error sink per turn. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- src/droid_sdk/_high_level/session.py | 13 ++++---- src/droid_sdk/client.py | 48 ++-------------------------- tests/test_v5_session.py | 27 ++++++---------- tests/test_v5_streaming_core.py | 29 ++++++++--------- 4 files changed, 33 insertions(+), 84 deletions(-) diff --git a/src/droid_sdk/_high_level/session.py b/src/droid_sdk/_high_level/session.py index 36566ce..31d287d 100644 --- a/src/droid_sdk/_high_level/session.py +++ b/src/droid_sdk/_high_level/session.py @@ -67,6 +67,7 @@ StdioMcpServerConfig, ToolInfo, ) +from droid_sdk._high_level.interaction_adapter import InteractionDispatcher from droid_sdk._high_level.interactions import InteractionHandlers from droid_sdk._high_level.messages import ( ContextUsage, @@ -274,6 +275,7 @@ def __init__( self._reasoning_effort = reasoning_effort self._config = config or SessionConfig() self._interactions = interactions or InteractionHandlers() + self._dispatcher = InteractionDispatcher(self._interactions) self._runtime_config = runtime or Runtime() self._observability = ObservabilityAdapter(self._runtime_config.observability) self._api_key = api_key @@ -528,7 +530,8 @@ async def _open_impl(self) -> None: ), cwd=str(requested_cwd), ) from exc - client.set_interaction_handlers(self._interactions) + client.set_permission_handler(self._dispatcher.handle_permission) + client.set_ask_user_handler(self._dispatcher.handle_question) if self._resume_id is not None: session_start_attempted = True @@ -886,10 +889,7 @@ def stream( async def start(stream: RunStream[Any, Any]) -> None: nonlocal stream_unsubscribes client = self._require_client() - client.set_interaction_handlers( - self._interactions, - error_sink=stream.queue_error_event, - ) + self._dispatcher.error_sink = stream.queue_error_event unsubscribe = client.on_notification(stream.feed_notification) unsubscribe_error = client.on_error(stream.feed_error) self._subscriptions.update((unsubscribe, unsubscribe_error)) @@ -931,8 +931,7 @@ async def finish(interrupt: bool) -> None: self._active_stream = None if self._state is _State.BUSY: self._state = _State.OPEN - if client is not None: - client.set_interaction_handlers(self._interactions) + self._dispatcher.error_sink = None if interrupt and client is not None: task = asyncio.create_task(client.interrupt_session()) task.add_done_callback(_consume_task_result) diff --git a/src/droid_sdk/client.py b/src/droid_sdk/client.py index 818e753..560af72 100644 --- a/src/droid_sdk/client.py +++ b/src/droid_sdk/client.py @@ -17,7 +17,6 @@ from types import TracebackType # noqa: TC003 from typing import TYPE_CHECKING, Any, Literal -from droid_sdk._high_level.interaction_adapter import InteractionDispatcher from droid_sdk.errors import ( ConnectionError as DroidConnectionError, ) @@ -112,9 +111,6 @@ if TYPE_CHECKING: from pydantic import BaseModel - from droid_sdk._high_level.interactions import InteractionHandlers - from droid_sdk._high_level.messages import ErrorEvent as HighLevelErrorEvent - logger = logging.getLogger(__name__) # Type alias for notification listener callbacks @@ -195,7 +191,6 @@ def __init__( # Client-level server→client request handlers self._permission_handler: Callable[..., Any] | None = None self._ask_user_handler: Callable[..., Any] | None = None - self._interaction_dispatcher: InteractionDispatcher | None = None # ---------------------------------------------------------- # Properties @@ -281,7 +276,6 @@ async def close(self) -> None: self._error_listeners.clear() self._permission_handler = None self._ask_user_handler = None - self._interaction_dispatcher = None if self._protocol is not None: await self._protocol.close() @@ -1778,49 +1772,18 @@ def unsubscribe() -> None: # Server→client request handlers # ---------------------------------------------------------- - def set_interaction_handlers( - self, - handlers: InteractionHandlers, - *, - error_sink: Callable[[HighLevelErrorEvent], None] | None = None, - ) -> None: - """Register immutable high-level interaction handlers. - - Handler failures return the protocol cancellation response and are - reported to ``error_sink`` as content-free :class:`ErrorEvent` values. - """ - dispatcher = InteractionDispatcher( - handlers, - error_sink=error_sink, - ) - self._permission_handler = None - self._ask_user_handler = None - self._interaction_dispatcher = dispatcher - if self._protocol is not None: - self._protocol.set_permission_handler(self._dispatch_permission_request) - self._protocol.set_ask_user_handler(self._dispatch_ask_user_request) - - def clear_interaction_handlers(self) -> None: - """Clear high-level handlers and restore protocol cancellation defaults.""" - self._permission_handler = None - self._ask_user_handler = None - self._interaction_dispatcher = None - if self._protocol is not None: - self._protocol.set_permission_handler(self._dispatch_permission_request) - self._protocol.set_ask_user_handler(self._dispatch_ask_user_request) - def set_permission_handler(self, handler: Callable[..., Any]) -> None: """Register a handler for server→client permission requests. The handler receives the request params dict and should return - a ``ToolConfirmationOutcome`` string value (or any string). + a ``ToolConfirmationOutcome`` string value or a complete response + dict (``{"selectedOption": ...}``). Async handlers are awaited. Replaces any previously registered handler. Args: - handler: Sync or async callable ``(params) -> str``. + handler: Sync or async callable ``(params) -> str | dict``. """ - self._interaction_dispatcher = None self._permission_handler = handler # Update protocol engine if already connected if self._protocol is not None: @@ -1846,7 +1809,6 @@ def set_ask_user_handler(self, handler: Callable[..., Any]) -> None: Args: handler: Sync or async callable ``(params) -> dict``. """ - self._interaction_dispatcher = None self._ask_user_handler = handler if self._protocol is not None: self._protocol.set_ask_user_handler(self._dispatch_ask_user_request) @@ -1901,8 +1863,6 @@ def _dispatch_permission_request(self, params: dict[str, Any]) -> Any: If no handler is set, returns the default Cancel outcome. """ - if self._interaction_dispatcher is not None: - return self._interaction_dispatcher.handle_permission(params) handler = self._permission_handler if handler is None: return "cancel" @@ -1913,8 +1873,6 @@ def _dispatch_ask_user_request(self, params: dict[str, Any]) -> Any: If no handler is set, returns the default cancelled response. """ - if self._interaction_dispatcher is not None: - return self._interaction_dispatcher.handle_question(params) handler = self._ask_user_handler if handler is None: return {"cancelled": True, "answers": []} diff --git a/tests/test_v5_session.py b/tests/test_v5_session.py index 73041b6..1846819 100644 --- a/tests/test_v5_session.py +++ b/tests/test_v5_session.py @@ -30,7 +30,6 @@ SessionReplacementError, TextDocumentSource, ) -from droid_sdk._high_level.interaction_adapter import InteractionDispatcher from droid_sdk.mcp import create_sdk_mcp_server from droid_sdk.observability import LogEvent, MetricEvent, Observability from droid_sdk.schemas.enums import ( @@ -93,7 +92,8 @@ def __init__(self, **kwargs: object) -> None: self.mcp_calls: list[dict[str, Any]] = [] self.callbacks: list[Callable[[dict[str, Any]], None]] = [] self.error_callbacks: list[Callable[[Exception], None]] = [] - self.dispatcher: InteractionDispatcher | None = None + self.permission_handler: Callable[..., Any] | None = None + self.ask_user_handler: Callable[..., Any] | None = None self.interrupt_calls = 0 self.close_calls = 0 self.close_session_calls = 0 @@ -122,16 +122,11 @@ async def initialize_session(self, **kwargs: Any) -> SimpleNamespace: async def update_session_settings(self, **kwargs: Any) -> None: self.update_calls.append(kwargs) - def set_interaction_handlers( - self, - handlers: object, - *, - error_sink: object | None = None, - ) -> None: - self.dispatcher = InteractionDispatcher( - cast("InteractionHandlers", handlers), - error_sink=cast("Any", error_sink), - ) + def set_permission_handler(self, handler: Callable[..., Any]) -> None: + self.permission_handler = handler + + def set_ask_user_handler(self, handler: Callable[..., Any]) -> None: + self.ask_user_handler = handler def on_error( self, @@ -995,11 +990,9 @@ def throwing(_request: object) -> object: await session.open() stream = session.stream("interact") await stream.__aenter__() - dispatcher = FakeClient.instances[0].dispatcher - assert dispatcher is not None - assert await dispatcher.handle_permission(permission_params()) == { - "selectedOption": "cancel" - } + handle_permission = FakeClient.instances[0].permission_handler + assert handle_permission is not None + assert await handle_permission(permission_params()) == {"selectedOption": "cancel"} event = await anext(stream.__aiter__()) assert isinstance(event, ErrorEvent) diff --git a/tests/test_v5_streaming_core.py b/tests/test_v5_streaming_core.py index e1cac8e..c80ea4d 100644 --- a/tests/test_v5_streaming_core.py +++ b/tests/test_v5_streaming_core.py @@ -1296,20 +1296,9 @@ def throwing_sink(event: ErrorEvent) -> None: @pytest.mark.asyncio -async def test_clearing_high_level_handlers_cannot_reactivate_legacy_approval() -> None: +async def test_dispatcher_registers_through_low_level_handler_slots() -> None: client = DroidClient(exec_path="/not-used") - legacy_calls = 0 - - def approve_legacy(params: dict[str, object]) -> str: - nonlocal legacy_calls - legacy_calls += 1 - return "proceed_once" - - client.set_permission_handler(approve_legacy) - client.set_ask_user_handler( - lambda params: {"cancelled": False, "answers": ["legacy"]} - ) - client.set_interaction_handlers( + dispatcher = InteractionDispatcher( InteractionHandlers( on_permission=lambda request: request.respond( ToolConfirmationOutcome.PROCEED_ONCE @@ -1317,11 +1306,21 @@ def approve_legacy(params: dict[str, object]) -> str: on_question=lambda request: request.cancel(), ) ) - client.clear_interaction_handlers() + client.set_permission_handler(dispatcher.handle_permission) + client.set_ask_user_handler(dispatcher.handle_question) + + assert await client._dispatch_permission_request(_permission_params()) == { + "selectedOption": "proceed_once" + } + assert await client._dispatch_ask_user_request(_question_params()) == { + "cancelled": True, + "answers": [], + } + client.clear_permission_handler() + client.clear_ask_user_handler() assert client._dispatch_permission_request({}) == "cancel" assert client._dispatch_ask_user_request({}) == { "cancelled": True, "answers": [], } - assert legacy_calls == 0 From ff343c5aa41f01c9935b33f4e55a9356017abe8f Mon Sep 17 00:00:00 2001 From: User Date: Tue, 11 Aug 2026 18:04:07 -0700 Subject: [PATCH 04/30] refactor: consolidate wire/public converters into one module Session and streaming each carried their own copies of the wire<->public converters (settings, MCP status, usage, notification extraction), and the copies had already diverged: session's settings merge re-parsed raw camelCase dicts by hand with per-field fallbacks while streaming validated typed payloads. All shared conversions now live in _high_level/_convert.py with one strictly typed implementation per concept, and the settings merge goes through the validated SettingsUpdatedPayload model with model_fields_set deciding which explicit nulls clear a value. The third copy of _consume_task_result (transport, session, streaming) moves to droid_sdk/_util.py. The session test fixture now builds a real wire SessionSettings model instead of a SimpleNamespace so converter changes are exercised against the actual schema. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- src/droid_sdk/_high_level/_convert.py | 462 +++++++++++++++++++++++ src/droid_sdk/_high_level/session.py | 502 ++++--------------------- src/droid_sdk/_high_level/streaming.py | 212 ++--------- src/droid_sdk/_util.py | 15 + src/droid_sdk/transport.py | 8 +- tests/test_v5_session.py | 12 +- 6 files changed, 586 insertions(+), 625 deletions(-) create mode 100644 src/droid_sdk/_high_level/_convert.py create mode 100644 src/droid_sdk/_util.py diff --git a/src/droid_sdk/_high_level/_convert.py b/src/droid_sdk/_high_level/_convert.py new file mode 100644 index 0000000..357937b --- /dev/null +++ b/src/droid_sdk/_high_level/_convert.py @@ -0,0 +1,462 @@ +"""Canonical conversions between wire schemas and public high-level models. + +Every wire<->public conversion shared by more than one high-level module +lives here so each concept is converted in exactly one place. +""" + +from __future__ import annotations + +import dataclasses +from collections.abc import Mapping, Sequence +from enum import Enum +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal, cast + +from pydantic import BaseModel, TypeAdapter, ValidationError + +from droid_sdk._high_level.attachments import ( + Document, + PdfDocumentSource, + TextDocumentSource, +) +from droid_sdk._high_level.config import ( + SandboxSettings, + SessionSettings, + SessionSettingsUpdate, + SessionSource, + SessionTag, +) +from droid_sdk._high_level.enums import ( + Autonomy, + McpServerStatus, + McpServerType, + Mode, + ReasoningEffort, + ToolCategory, +) +from droid_sdk._high_level.extensions import ( + HttpMcpServerConfig, + McpConfigError, + McpServerConfig, + McpServerStatusInfo, + McpStatusSummary, + SdkMcpServer, + StdioMcpServerConfig, +) +from droid_sdk._high_level.messages import McpStatusChanged, Usage +from droid_sdk.errors import DroidProtocolError +from droid_sdk.schemas.cli import ( + McpStatusChangedNotification, + SessionNotification, + SessionNotificationUnion, + SettingsUpdatedPayload, +) +from droid_sdk.schemas.client import HttpHeader as WireHttpHeader +from droid_sdk.schemas.client import ( + HttpMcpConfig, + SseMcpConfig, + StdioMcpConfig, +) +from droid_sdk.schemas.client import McpOAuthOptions as WireMcpOAuthOptions +from droid_sdk.schemas.client import SessionSettings as WireSessionSettings +from droid_sdk.schemas.enums import ReasoningEffort as WireReasoningEffort +from droid_sdk.schemas.enums import SessionNotificationType + +if TYPE_CHECKING: + from droid_sdk.schemas.mcp import McpServerStatusInfo as WireMcpServerStatusInfo + from droid_sdk.schemas.mcp import McpStatusSummary as WireMcpStatusSummary + from droid_sdk.schemas.session import TokenUsage as WireTokenUsage + +_NOTIFICATION_ADAPTER: TypeAdapter[SessionNotificationUnion] = TypeAdapter( + SessionNotificationUnion +) +_KNOWN_NOTIFICATION_TYPES = frozenset(item.value for item in SessionNotificationType) + + +# ---------------------------------------------------------- +# Outgoing: public values -> wire payloads +# ---------------------------------------------------------- + + +def wire_reasoning(value: ReasoningEffort | None) -> WireReasoningEffort | None: + return None if value is None else WireReasoningEffort(value.value) + + +def wire_source(value: SessionSource | None) -> dict[str, object] | None: + if value is None: + return None + return { + key: item.value if isinstance(item, Enum) else item + for key, item in ( + (field, getattr(value, field)) for field in value.__dataclass_fields__ + ) + if item is not None + } + + +def wire_tags(values: Sequence[SessionTag]) -> list[dict[str, Any]]: + return [ + { + "name": value.name, + **({} if value.metadata is None else {"metadata": dict(value.metadata)}), + } + for value in values + ] + + +def mcp_config_to_wire(value: McpServerConfig) -> dict[str, Any]: + if isinstance(value, SdkMcpServer): + raise TypeError("SDK MCP servers must be started before serialization") + try: + if isinstance(value, StdioMcpServerConfig): + model: BaseModel = StdioMcpConfig( + name=value.name, + command=value.command, + args=list(value.args), + env=dict(value.env), + ) + else: + oauth: WireMcpOAuthOptions | Literal[False] | None + if value.oauth is None or value.oauth is False: + oauth = value.oauth + else: + oauth = WireMcpOAuthOptions.model_validate( + { + field: (item.value if isinstance(item, Enum) else item) + for field, item in ( + (field, getattr(value.oauth, field)) + for field in value.oauth.__dataclass_fields__ + ) + if item is not None + } + ) + headers = [ + WireHttpHeader(name=header.name, value=header.value) + for header in value.headers + ] + if isinstance(value, HttpMcpServerConfig): + model = HttpMcpConfig( + type="http", + name=value.name, + url=value.url, + headers=headers, + oauth=oauth, + ) + else: + model = SseMcpConfig( + type="sse", + name=value.name, + url=value.url, + headers=headers, + oauth=oauth, + ) + except (ValidationError, ValueError): + raise ValueError("Invalid MCP server configuration") from None + return model.model_dump(by_alias=True, exclude_none=True) + + +def document_to_wire(document: Document) -> dict[str, Any]: + source = document.source + if isinstance(source, TextDocumentSource): + return { + "type": "text", + "mediaType": "text/plain", + "data": source.data, + "name": source.name, + } + assert isinstance(source, PdfDocumentSource) + return { + "type": "base64", + "mediaType": "application/pdf", + "data": source.data, + "parsedData": source.parsed_data, + "name": source.name, + "path": source.path, + } + + +def list_or_none(value: object) -> list[str] | None: + if value is None: + return None + return sorted(cast("Sequence[str]", value)) + + +def header_mapping(values: list[object]) -> dict[str, str]: + result: dict[str, str] = {} + for value in values: + if not isinstance(value, Mapping): + continue + header = cast("Mapping[str, object]", value) + name = header.get("name") + content = header.get("value") + if isinstance(name, str) and isinstance(content, str): + result[name] = content + return result + + +# ---------------------------------------------------------- +# Incoming: wire payloads -> public values +# ---------------------------------------------------------- + + +def _notification_type(raw: object) -> str | None: + if not isinstance(raw, Mapping): + return None + payload = cast("Mapping[str, object]", raw) + params = payload.get("params") + if isinstance(params, Mapping): + params_mapping = cast("Mapping[str, object]", params) + notification = params_mapping.get("notification") + if isinstance(notification, Mapping): + payload = cast("Mapping[str, object]", notification) + value = payload.get("type") + return value if isinstance(value, str) else None + + +def _raise_for_invalid_known_notification(raw: object) -> None: + notification_type = _notification_type(raw) + if notification_type in _KNOWN_NOTIFICATION_TYPES: + raise DroidProtocolError( + f"Invalid {notification_type} notification payload" + ) from None + + +def inner_notification(raw: object) -> SessionNotificationUnion | None: + """Validate a raw notification into the typed inner payload. + + Returns ``None`` for unrelated payloads and raises + :class:`DroidProtocolError` when a known notification type fails + validation. + """ + raw_object: object = raw + if isinstance(raw, SessionNotification): + return raw.params.notification + if isinstance(raw, Mapping): + mapping = cast("Mapping[str, object]", raw) + params = mapping.get("params") + if isinstance(params, Mapping) and "notification" in params: + try: + return SessionNotification.model_validate( + raw_object + ).params.notification + except ValidationError: + _raise_for_invalid_known_notification(raw_object) + return None + try: + return _NOTIFICATION_ADAPTER.validate_python(raw_object) + except ValidationError: + _raise_for_invalid_known_notification(raw_object) + return None + + +def raw_inner_notification(raw: Mapping[str, Any]) -> dict[str, Any] | None: + """Extract the inner notification dict without validating its payload.""" + params = cast("object", raw.get("params")) + if not isinstance(params, Mapping): + return None + inner = cast("Mapping[str, object]", params).get("notification") + return cast("dict[str, Any]", inner) if isinstance(inner, dict) else None + + +def usage_from_wire(value: WireTokenUsage) -> Usage: + return Usage( + input_tokens=value.input_tokens, + output_tokens=value.output_tokens, + cache_creation_tokens=value.cache_creation_tokens, + cache_read_tokens=value.cache_read_tokens, + thinking_tokens=value.thinking_tokens, + factory_credits=value.factory_credits, + ) + + +def settings_update_from_wire( + value: SettingsUpdatedPayload | WireSessionSettings, +) -> SessionSettingsUpdate: + mode = None + if value.interaction_mode is not None and value.interaction_mode.value in { + "auto", + "spec", + }: + mode = Mode(value.interaction_mode.value) + elif value.autonomy_mode is not None: + mode = Mode.SPEC if value.autonomy_mode.value == "spec" else Mode.AUTO + autonomy = ( + None if value.autonomy_level is None else Autonomy(value.autonomy_level.value) + ) + if autonomy is None and value.autonomy_mode is not None: + autonomy = { + "normal": Autonomy.OFF, + "auto-low": Autonomy.LOW, + "auto-medium": Autonomy.MEDIUM, + "auto-high": Autonomy.HIGH, + }.get(value.autonomy_mode.value) + return SessionSettingsUpdate( + model=value.model_id, + reasoning_effort=( + None + if value.reasoning_effort is None + else ReasoningEffort(value.reasoning_effort.value) + ), + mode=mode, + autonomy=autonomy, + spec_model=value.spec_mode_model_id, + spec_reasoning_effort=( + None + if value.spec_mode_reasoning_effort is None + else ReasoningEffort(value.spec_mode_reasoning_effort.value) + ), + tags=( + None + if value.tags is None + else tuple( + SessionTag(name=tag.name, metadata=tag.metadata) for tag in value.tags + ) + ), + additional_tools=( + None + if value.additional_tool_ids is None + else set(value.additional_tool_ids) + ), + enabled_tools=( + None if value.enabled_tool_ids is None else set(value.enabled_tool_ids) + ), + disabled_tools=( + None if value.disabled_tool_ids is None else set(value.disabled_tool_ids) + ), + restrict_tools=( + None if value.restrict_tool_ids is None else set(value.restrict_tool_ids) + ), + compaction_threshold_check_enabled=value.compaction_threshold_check_enabled, + ) + + +def full_settings_from_wire(value: WireSessionSettings) -> SessionSettings: + update = settings_update_from_wire(value) + sandbox = value.sandbox + return SessionSettings( + model=value.model_id, + reasoning_effort=ReasoningEffort(value.reasoning_effort.value), + mode=update.mode, + autonomy=update.autonomy, + spec_model=update.spec_model, + spec_reasoning_effort=update.spec_reasoning_effort, + tags=update.tags or (), + sandbox=( + None + if sandbox is None + else SandboxSettings( + enabled=sandbox.enabled, + mode=None if sandbox.mode is None else sandbox.mode.value, + ) + ), + additional_tools=update.additional_tools, + enabled_tools=update.enabled_tools, + disabled_tools=update.disabled_tools, + restrict_tools=update.restrict_tools, + ) + + +# Fields where an explicitly transmitted null clears the current value; for +# every other field null means "unchanged". +_CLEARABLE_SETTINGS_FIELDS = ( + ("mode", "interaction_mode"), + ("autonomy", "autonomy_level"), + ("spec_model", "spec_mode_model_id"), + ("spec_reasoning_effort", "spec_mode_reasoning_effort"), +) + + +def merged_settings( + current: SessionSettings, + payload: SettingsUpdatedPayload, +) -> SessionSettings: + update = settings_update_from_wire(payload) + changes: dict[str, Any] = { + name: value + for name, value in ( + ("model", update.model), + ("reasoning_effort", update.reasoning_effort), + ("mode", update.mode), + ("autonomy", update.autonomy), + ("spec_model", update.spec_model), + ("spec_reasoning_effort", update.spec_reasoning_effort), + ("tags", update.tags), + ("additional_tools", update.additional_tools), + ("enabled_tools", update.enabled_tools), + ("disabled_tools", update.disabled_tools), + ("restrict_tools", update.restrict_tools), + ) + if value is not None + } + provided = payload.model_fields_set + for public_name, wire_name in _CLEARABLE_SETTINGS_FIELDS: + if public_name not in changes and wire_name in provided: + changes[public_name] = None + return dataclasses.replace(current, **changes) + + +def mcp_server_from_wire(value: WireMcpServerStatusInfo) -> McpServerStatusInfo: + return McpServerStatusInfo( + name=value.name, + status=McpServerStatus(value.status.value), + source=value.source.value, + is_managed=value.is_managed, + server_type=McpServerType(value.server_type.value), + error=value.error, + tool_count=value.tool_count, + has_auth_tokens=value.has_auth_tokens, + requires_auth=value.requires_auth, + pending_auth_url=value.pending_auth_url, + pending_auth_message=value.pending_auth_message, + pending_auth_state=value.pending_auth_state, + ) + + +def mcp_summary_from_wire(value: WireMcpStatusSummary) -> McpStatusSummary: + return McpStatusSummary( + total=value.total, + connected=value.connected, + connecting=value.connecting, + failed=value.failed, + disabled=value.disabled, + config_error=( + None + if value.config_error is None + else McpConfigError(value.config_error.path, value.config_error.message) + ), + ) + + +def mcp_status_from_wire( + notification: McpStatusChangedNotification, +) -> McpStatusChanged: + return McpStatusChanged( + servers=tuple(mcp_server_from_wire(server) for server in notification.servers), + summary=mcp_summary_from_wire(notification.summary), + ) + + +def tool_category(value: str | None) -> ToolCategory: + try: + return ToolCategory(value) + except ValueError: + return ToolCategory.OTHER + + +def load_cwd(result: object, fallback: Path) -> Path: + """Read the loaded session's cwd out of the result's extra fields. + + The load result does not yet model cwd/worktree in its schema, so this + probes ``model_extra`` and falls back to the caller-supplied path. + """ + extra = cast("dict[str, object]", getattr(result, "model_extra", None) or {}) + cwd = extra.get("cwd") + if isinstance(cwd, str): + return Path(cwd) + worktree = extra.get("worktree") + if isinstance(worktree, Mapping): + typed_worktree = cast("Mapping[str, object]", worktree) + path = typed_worktree.get("path") + if isinstance(path, str): + return Path(path) + return fallback diff --git a/src/droid_sdk/_high_level/session.py b/src/droid_sdk/_high_level/session.py index 31d287d..825c125 100644 --- a/src/droid_sdk/_high_level/session.py +++ b/src/droid_sdk/_high_level/session.py @@ -9,24 +9,33 @@ import importlib.metadata import os import uuid -from collections.abc import Callable, Mapping, Sequence from datetime import datetime from enum import Enum from pathlib import Path -from typing import Any, Literal, TypeVar, cast, overload +from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast, overload from pydantic import BaseModel, ValidationError -from droid_sdk._high_level._immutable import JsonObject -from droid_sdk._high_level.attachments import ( - Document, - Image, - PdfDocumentSource, - TextDocumentSource, +from droid_sdk._high_level._convert import ( + document_to_wire, + full_settings_from_wire, + header_mapping, + list_or_none, + load_cwd, + mcp_config_to_wire, + mcp_server_from_wire, + mcp_summary_from_wire, + merged_settings, + raw_inner_notification, + tool_category, + wire_reasoning, + wire_source, + wire_tags, ) +from droid_sdk._high_level._immutable import JsonObject +from droid_sdk._high_level.attachments import Document, Image from droid_sdk._high_level.config import ( JsonSchema, - SandboxSettings, SessionConfig, SessionSettings, SessionSource, @@ -36,21 +45,15 @@ from droid_sdk._high_level.enums import ( Autonomy, ContextAccuracy, - McpServerStatus, - McpServerType, Mode, ReasoningEffort, - ToolCategory, ) from droid_sdk._high_level.extensions import ( CompactOutcome, HttpMcpServerConfig, - McpConfigError, McpMutationResult, McpServerConfig, McpServersResult, - McpServerStatusInfo, - McpStatusSummary, McpToolInfo, McpToolInputSchema, RewindEvictedFile, @@ -78,6 +81,7 @@ from droid_sdk._high_level.output import prepare_output_adapter from droid_sdk._high_level.runtime import Runtime from droid_sdk._high_level.streaming import RunStream +from droid_sdk._util import consume_task_result from droid_sdk.client import DroidClient from droid_sdk.errors import ( DroidConnectionError, @@ -90,18 +94,8 @@ SessionReplacementError, ) from droid_sdk.observability import ObservabilityAdapter -from droid_sdk.schemas.client import ( - AddUserMessageRequestParams, - HttpMcpConfig, - SseMcpConfig, - StdioMcpConfig, -) -from droid_sdk.schemas.client import ( - HttpHeader as WireHttpHeader, -) -from droid_sdk.schemas.client import ( - McpOAuthOptions as WireMcpOAuthOptions, -) +from droid_sdk.schemas.cli import SettingsUpdatedNotification +from droid_sdk.schemas.client import AddUserMessageRequestParams from droid_sdk.schemas.enums import ( AutonomyLevel as WireAutonomy, ) @@ -112,11 +106,11 @@ from droid_sdk.schemas.enums import ( McpServerType as WireMcpServerType, ) -from droid_sdk.schemas.enums import ( - ReasoningEffort as WireReasoningEffort, -) from droid_sdk.transport import ProcessTransport +if TYPE_CHECKING: + from collections.abc import Callable, Mapping, Sequence + ModelT = TypeVar("ModelT", bound=BaseModel) @@ -138,124 +132,6 @@ class _State(Enum): CLOSED = "closed" -def _wire_reasoning(value: ReasoningEffort | None) -> WireReasoningEffort | None: - return None if value is None else WireReasoningEffort(value.value) - - -def _wire_source(value: SessionSource | None) -> dict[str, object] | None: - if value is None: - return None - return { - key: item.value if isinstance(item, Enum) else item - for key, item in ( - (field, getattr(value, field)) for field in value.__dataclass_fields__ - ) - if item is not None - } - - -def _wire_tags(values: Sequence[SessionTag]) -> list[dict[str, Any]]: - return [ - { - "name": value.name, - **({} if value.metadata is None else {"metadata": dict(value.metadata)}), - } - for value in values - ] - - -def _settings(value: Any) -> SessionSettings: - mode = ( - None - if value.interaction_mode is None - or value.interaction_mode.value not in {"auto", "spec"} - else Mode(value.interaction_mode.value) - ) - autonomy = ( - None if value.autonomy_level is None else Autonomy(value.autonomy_level.value) - ) - sandbox = ( - None - if value.sandbox is None - else SandboxSettings( - enabled=value.sandbox.enabled, - mode=None if value.sandbox.mode is None else value.sandbox.mode.value, - ) - ) - return SessionSettings( - model=value.model_id, - reasoning_effort=ReasoningEffort(value.reasoning_effort.value), - mode=mode, - autonomy=autonomy, - spec_model=value.spec_mode_model_id, - spec_reasoning_effort=( - None - if value.spec_mode_reasoning_effort is None - else ReasoningEffort(value.spec_mode_reasoning_effort.value) - ), - tags=tuple( - SessionTag(name=tag.name, metadata=tag.metadata) - for tag in (value.tags or ()) - ), - sandbox=sandbox, - additional_tools=value.additional_tool_ids, - enabled_tools=value.enabled_tool_ids, - disabled_tools=value.disabled_tool_ids, - restrict_tools=value.restrict_tool_ids, - ) - - -def _mcp_config(value: McpServerConfig) -> dict[str, Any]: - if isinstance(value, SdkMcpServer): - raise TypeError("SDK MCP servers must be started before serialization") - try: - if isinstance(value, StdioMcpServerConfig): - model: BaseModel = StdioMcpConfig( - name=value.name, - command=value.command, - args=list(value.args), - env=dict(value.env), - ) - else: - oauth: WireMcpOAuthOptions | Literal[False] | None - if value.oauth is None or value.oauth is False: - oauth = value.oauth - else: - oauth = WireMcpOAuthOptions.model_validate( - { - field: (item.value if isinstance(item, Enum) else item) - for field, item in ( - (field, getattr(value.oauth, field)) - for field in value.oauth.__dataclass_fields__ - ) - if item is not None - } - ) - headers = [ - WireHttpHeader(name=header.name, value=header.value) - for header in value.headers - ] - if isinstance(value, HttpMcpServerConfig): - model = HttpMcpConfig( - type="http", - name=value.name, - url=value.url, - headers=headers, - oauth=oauth, - ) - else: - model = SseMcpConfig( - type="sse", - name=value.name, - url=value.url, - headers=headers, - oauth=oauth, - ) - except (ValidationError, ValueError): - raise ValueError("Invalid MCP server configuration") from None - return model.model_dump(by_alias=True, exclude_none=True) - - class Session: """A lazy, single-turn-at-a-time Droid session.""" @@ -483,9 +359,9 @@ async def _open_impl(self) -> None: if isinstance(server, SdkMcpServer): started.append(server) config = await server.start() - configs.append(_mcp_config(config)) + configs.append(mcp_config_to_wire(config)) else: - configs.append(_mcp_config(server)) + configs.append(mcp_config_to_wire(server)) self._load_mcp_configs = configs runtime = self._runtime_config @@ -538,7 +414,7 @@ async def _open_impl(self) -> None: load_result = await client.load_session( session_id=self._resume_id, mcp_servers=configs or None, - disabled_tool_ids=_list_or_none( + disabled_tool_ids=list_or_none( self._resume_options["disabled_tools"] ), auto_reject_permission_requests=cast( @@ -549,7 +425,7 @@ async def _open_impl(self) -> None: "bool | None", self._resume_options["disable_builtin_skills"], ), - session_source=_wire_source( + session_source=wire_source( cast( "SessionSource | None", self._resume_options["session_source"], @@ -557,7 +433,7 @@ async def _open_impl(self) -> None: ), ) session_id = self._resume_id - cwd_value = _load_cwd(load_result, requested_cwd) + cwd_value = load_cwd(load_result, requested_cwd) wire_settings = load_result.settings else: sdk_tag = SessionTag( @@ -585,17 +461,17 @@ async def _open_impl(self) -> None: else WireAutonomy(self._config.autonomy.value) ), model_id=self._model, - reasoning_effort=_wire_reasoning(self._reasoning_effort), + reasoning_effort=wire_reasoning(self._reasoning_effort), spec_mode_model_id=self._config.spec_model, - spec_mode_reasoning_effort=_wire_reasoning( + spec_mode_reasoning_effort=wire_reasoning( self._config.spec_reasoning_effort ), - additional_tool_ids=_list_or_none(self._config.additional_tools), - enabled_tool_ids=_list_or_none(self._config.enabled_tools), - disabled_tool_ids=_list_or_none(self._config.disabled_tools), - restrict_tool_ids=_list_or_none(self._config.restrict_tools), - session_source=_wire_source(self._config.session_source), - tags=cast("Any", _wire_tags(tags)), + additional_tool_ids=list_or_none(self._config.additional_tools), + enabled_tool_ids=list_or_none(self._config.enabled_tools), + disabled_tool_ids=list_or_none(self._config.disabled_tools), + restrict_tool_ids=list_or_none(self._config.restrict_tools), + session_source=wire_source(self._config.session_source), + tags=cast("Any", wire_tags(tags)), auto_reject_permission_requests=( self._config.auto_reject_permission_requests ), @@ -608,7 +484,7 @@ async def _open_impl(self) -> None: self._client = client self._id = session_id self._cwd = cwd_value - self._settings = _settings(wire_settings) + self._settings = full_settings_from_wire(wire_settings) self._sdk_servers = started self._bind_metadata() if self._state is _State.OPENING: @@ -910,7 +786,7 @@ async def start(stream: RunStream[Any, Any]) -> None: for image in images ] or None, - "files": [_document_source(file) for file in files] or None, + "files": [document_to_wire(file) for file in files] or None, "outputFormat": adapter.output_format, } ) @@ -934,7 +810,7 @@ async def finish(interrupt: bool) -> None: self._dispatcher.error_sink = None if interrupt and client is not None: task = asyncio.create_task(client.interrupt_session()) - task.add_done_callback(_consume_task_result) + task.add_done_callback(consume_task_result) if interrupt: status = "interrupted" elif stream_value.completed: @@ -1006,20 +882,20 @@ async def update_settings( explicit_null_fields.append("specModeReasoningEffort") await self._require_client().update_session_settings( model_id=model, - reasoning_effort=_wire_reasoning(reasoning_effort), + reasoning_effort=wire_reasoning(reasoning_effort), interaction_mode=( None if mode is None else DroidInteractionMode(mode.value) ), autonomy_level=(None if autonomy is None else WireAutonomy(autonomy.value)), spec_mode_model_id=spec_model_value, - spec_mode_reasoning_effort=_wire_reasoning(spec_reasoning_value), - tags=cast("Any", None if tags is None else _wire_tags(tags)), + spec_mode_reasoning_effort=wire_reasoning(spec_reasoning_value), + tags=cast("Any", None if tags is None else wire_tags(tags)), compaction_token_limit=compaction_token_limit, compaction_threshold_check_enabled=(compaction_threshold_check_enabled), - additional_tool_ids=_list_or_none(additional_tools), - enabled_tool_ids=_list_or_none(enabled_tools), - disabled_tool_ids=_list_or_none(disabled_tools), - restrict_tool_ids=_list_or_none(restrict_tools), + additional_tool_ids=list_or_none(additional_tools), + enabled_tool_ids=list_or_none(enabled_tools), + disabled_tool_ids=list_or_none(disabled_tools), + restrict_tool_ids=list_or_none(restrict_tools), explicit_null_fields=explicit_null_fields, ) for key, value in ( @@ -1080,7 +956,7 @@ def on_notification( self._ensure_active() def dispatch(raw: dict[str, Any]) -> None: - inner = _inner_notification(raw) + inner = raw_inner_notification(raw) if inner is None: return if type is None or inner.get("type") == type: @@ -1116,10 +992,10 @@ async def list_tools( ), autonomy_level=(None if autonomy is None else WireAutonomy(autonomy.value)), spec_mode_model_id=spec_model, - additional_tool_ids=_list_or_none(additional_tools), - enabled_tool_ids=_list_or_none(enabled_tools), - disabled_tool_ids=_list_or_none(disabled_tools), - restrict_tool_ids=_list_or_none(restrict_tools), + additional_tool_ids=list_or_none(additional_tools), + enabled_tool_ids=list_or_none(enabled_tools), + disabled_tool_ids=list_or_none(disabled_tools), + restrict_tool_ids=list_or_none(restrict_tools), skip_permissions_unsafe=skip_permissions_unsafe, ) return [ @@ -1127,7 +1003,7 @@ async def list_tools( id=item.llm_id or item.id, display_name=item.display_name or item.llm_id or item.id, description=item.description or "", - category=_tool_category(item.category), + category=tool_category(item.category), default_allowed=item.default_allowed, allowed=item.currently_allowed, ) @@ -1197,8 +1073,8 @@ async def list_mcp_servers(self) -> McpServersResult: self._ensure_active() result = await self._require_client().list_mcp_servers() return McpServersResult( - servers=tuple(_mcp_server(item) for item in result.servers), - summary=_mcp_summary(result.summary), + servers=tuple(mcp_server_from_wire(item) for item in result.servers), + summary=mcp_summary_from_wire(result.summary), ) async def list_mcp_tools(self) -> list[McpToolInfo]: @@ -1229,7 +1105,7 @@ async def add_mcp_server( config: StdioMcpServerConfig | HttpMcpServerConfig | SseMcpServerConfig, ) -> McpMutationResult: self._ensure_active() - raw = _mcp_config(config) + raw = mcp_config_to_wire(config) headers = cast("object", raw.get("headers")) result = await self._require_client().add_mcp_server( name=config.name, @@ -1238,7 +1114,7 @@ async def add_mcp_server( headers=( None if not isinstance(headers, list) - else _header_mapping(cast("list[object]", headers)) + else header_mapping(cast("list[object]", headers)) ), command=cast("str | None", raw.get("command")), args=cast("list[str] | None", raw.get("args")), @@ -1396,7 +1272,7 @@ async def fork( _, successor = await self._replacement_operation( lambda: self._require_client().fork_session( title=title, - tags=cast("Any", None if tags is None else _wire_tags(tags)), + tags=cast("Any", None if tags is None else wire_tags(tags)), ) ) return successor @@ -1518,8 +1394,8 @@ async def _restore_after_cancelled_replacement(self, successor: Session) -> None client = successor._require_client() try: restored = await self._load_with_policies(client, self.id) - self._settings = _settings(restored.settings) - self._cwd = _load_cwd(restored, self._cwd or Path.cwd()) + self._settings = full_settings_from_wire(restored.settings) + self._cwd = load_cwd(restored, self._cwd or Path.cwd()) except BaseException: self._state = _State.CLOSING with contextlib.suppress(BaseException): @@ -1559,8 +1435,8 @@ async def _attach_replacement(self, replacement_id: str) -> Session: except BaseException as cause: try: restored = await self._load_with_policies(client, self.id) - self._settings = _settings(restored.settings) - self._cwd = _load_cwd(restored, self._cwd or Path.cwd()) + self._settings = full_settings_from_wire(restored.settings) + self._cwd = load_cwd(restored, self._cwd or Path.cwd()) except BaseException as rollback: self._state = _State.CLOSING with contextlib.suppress(BaseException): @@ -1575,8 +1451,8 @@ async def _attach_replacement(self, replacement_id: str) -> Session: successor = object.__new__(Session) successor.__dict__ = self.__dict__.copy() successor._id = replacement_id - successor._settings = _settings(loaded.settings) - successor._cwd = _load_cwd(loaded, self._cwd or Path.cwd()) + successor._settings = full_settings_from_wire(loaded.settings) + successor._cwd = load_cwd(loaded, self._cwd or Path.cwd()) successor._state = _State.OPEN successor._active_stream = None successor._subscriptions = set() @@ -1600,9 +1476,9 @@ async def _load_with_policies( loaded = await client.load_session( session_id=session_id, mcp_servers=self._load_mcp_configs or None, - additional_tool_ids=_list_or_none(self._load_options["additional_tools"]), - enabled_tool_ids=_list_or_none(self._load_options["enabled_tools"]), - disabled_tool_ids=_list_or_none(self._load_options["disabled_tools"]), + additional_tool_ids=list_or_none(self._load_options["additional_tools"]), + enabled_tool_ids=list_or_none(self._load_options["enabled_tools"]), + disabled_tool_ids=list_or_none(self._load_options["disabled_tools"]), auto_reject_permission_requests=cast( "bool | None", self._load_options["auto_reject_permission_requests"], @@ -1611,11 +1487,11 @@ async def _load_with_policies( "bool | None", self._load_options["disable_builtin_skills"], ), - session_source=_wire_source( + session_source=wire_source( cast("SessionSource | None", self._load_options["session_source"]) ), ) - restrict_tools = _list_or_none(self._load_options["restrict_tools"]) + restrict_tools = list_or_none(self._load_options["restrict_tools"]) if restrict_tools is not None: await client.update_session_settings( restrict_tool_ids=restrict_tools, @@ -1626,16 +1502,20 @@ def _bind_metadata(self) -> None: client = self._require_client() def update(raw: dict[str, Any]) -> None: - inner = _inner_notification(raw) + inner = raw_inner_notification(raw) if inner is None: return if inner.get("type") == "settings_updated": - settings = inner.get("settings") - if isinstance(settings, Mapping) and self._settings is not None: - self._settings = _merge_settings( - self._settings, - cast("Mapping[str, object]", settings), - ) + if self._settings is None: + return + try: + notification = SettingsUpdatedNotification.model_validate(inner) + except ValidationError: + return + self._settings = merged_settings( + self._settings, + notification.settings, + ) return if inner.get("type") == "session_working_directory_changed": cwd = inner.get("cwd") @@ -1767,231 +1647,9 @@ async def run( raise -def _list_or_none(value: object) -> list[str] | None: - if value is None: - return None - return sorted(cast("Sequence[str]", value)) - - async def _replacement_handoff_checkpoint() -> None: """Give cancellation a deterministic handoff point after replacement.""" await asyncio.sleep(0) -def _consume_task_result(task: asyncio.Future[Any]) -> None: - with contextlib.suppress(BaseException): - task.result() - - -def _load_cwd(result: Any, fallback: Path) -> Path: - extra = cast("dict[str, object]", result.model_extra or {}) - cwd = extra.get("cwd") - if isinstance(cwd, str): - return Path(cwd) - worktree = extra.get("worktree") - if isinstance(worktree, Mapping): - typed_worktree = cast("Mapping[str, object]", worktree) - path = typed_worktree.get("path") - if isinstance(path, str): - return Path(path) - return fallback - - -def _document_source(document: Document) -> dict[str, Any]: - source = document.source - if isinstance(source, TextDocumentSource): - return { - "type": "text", - "mediaType": "text/plain", - "data": source.data, - "name": source.name, - } - assert isinstance(source, PdfDocumentSource) - return { - "type": "base64", - "mediaType": "application/pdf", - "data": source.data, - "parsedData": source.parsed_data, - "name": source.name, - "path": source.path, - } - - -def _inner_notification(raw: Mapping[str, Any]) -> dict[str, Any] | None: - params = cast("object", raw.get("params")) - if not isinstance(params, Mapping): - return None - inner = cast("Mapping[str, object]", params).get("notification") - return cast("dict[str, Any]", inner) if isinstance(inner, dict) else None - - -def _header_mapping(values: list[object]) -> dict[str, str]: - result: dict[str, str] = {} - for value in values: - if not isinstance(value, Mapping): - continue - header = cast("Mapping[str, object]", value) - name = header.get("name") - content = header.get("value") - if isinstance(name, str) and isinstance(content, str): - result[name] = content - return result - - -def _tool_category(value: str | None) -> ToolCategory: - try: - return ToolCategory(value) - except ValueError: - return ToolCategory.OTHER - - -def _merge_settings( - current: SessionSettings, - update: Mapping[str, object], -) -> SessionSettings: - def enum_value( - key: str, - enum: type[Enum], - fallback: object, - *, - allow_none: bool = False, - ) -> object: - value = update.get(key, fallback) - if value is fallback: - return fallback - if value is None and allow_none: - return None - try: - return enum(value) - except (TypeError, ValueError): - return fallback - - tags: Sequence[SessionTag] = current.tags - raw_tags = update.get("tags") - if isinstance(raw_tags, list): - parsed_tags: list[SessionTag] = [] - for raw_tag in cast("list[object]", raw_tags): - if not isinstance(raw_tag, Mapping): - continue - tag = cast("Mapping[str, object]", raw_tag) - name = tag.get("name") - metadata = tag.get("metadata") - if isinstance(name, str): - parsed_tags.append( - SessionTag( - name=name, - metadata=( - cast("Mapping[str, str]", metadata) - if isinstance(metadata, Mapping) - else None - ), - ) - ) - tags = parsed_tags - - def tool_set(key: str, fallback: object) -> object: - value = update.get(key, fallback) - if isinstance(value, list) and all( - isinstance(item, str) for item in cast("list[object]", value) - ): - return frozenset(cast("list[str]", value)) - return fallback - - model = update.get("modelId", current.model) - spec_model = update.get("specModeModelId", current.spec_model) - return SessionSettings( - model=model if isinstance(model, str) else current.model, - reasoning_effort=cast( - "ReasoningEffort", - enum_value( - "reasoningEffort", - ReasoningEffort, - current.reasoning_effort, - ), - ), - mode=cast( - "Mode | None", - enum_value( - "interactionMode", - Mode, - current.mode, - allow_none=True, - ), - ), - autonomy=cast( - "Autonomy | None", - enum_value( - "autonomyLevel", - Autonomy, - current.autonomy, - allow_none=True, - ), - ), - spec_model=( - spec_model - if isinstance(spec_model, str) or spec_model is None - else current.spec_model - ), - spec_reasoning_effort=cast( - "ReasoningEffort | None", - enum_value( - "specModeReasoningEffort", - ReasoningEffort, - current.spec_reasoning_effort, - allow_none=True, - ), - ), - tags=tags, - sandbox=current.sandbox, - additional_tools=cast( - "set[str] | frozenset[str] | None", - tool_set("additionalToolIds", current.additional_tools), - ), - enabled_tools=cast( - "set[str] | frozenset[str] | None", - tool_set("enabledToolIds", current.enabled_tools), - ), - disabled_tools=cast( - "set[str] | frozenset[str] | None", - tool_set("disabledToolIds", current.disabled_tools), - ), - restrict_tools=cast( - "set[str] | frozenset[str] | None", - tool_set("restrictToolIds", current.restrict_tools), - ), - ) - - -def _mcp_summary(value: Any) -> McpStatusSummary: - return McpStatusSummary( - total=value.total, - connected=value.connected, - connecting=value.connecting, - failed=value.failed, - disabled=value.disabled, - config_error=( - None - if value.config_error is None - else McpConfigError(value.config_error.path, value.config_error.message) - ), - ) - - -def _mcp_server(value: Any) -> McpServerStatusInfo: - return McpServerStatusInfo( - name=value.name, - status=McpServerStatus(value.status.value), - source=value.source.value, - is_managed=value.is_managed, - server_type=McpServerType(value.server_type.value), - error=value.error, - tool_count=value.tool_count, - has_auth_tokens=value.has_auth_tokens, - requires_auth=value.requires_auth, - pending_auth_url=value.pending_auth_url, - pending_auth_message=value.pending_auth_message, - pending_auth_state=value.pending_auth_state, - ) - - __all__ = ["Session", "run"] diff --git a/src/droid_sdk/_high_level/streaming.py b/src/droid_sdk/_high_level/streaming.py index 0b6fbc4..cd88340 100644 --- a/src/droid_sdk/_high_level/streaming.py +++ b/src/droid_sdk/_high_level/streaming.py @@ -3,7 +3,6 @@ from __future__ import annotations import asyncio -import contextlib import inspect import json import math @@ -14,35 +13,27 @@ from decimal import Decimal from typing import TYPE_CHECKING, Any, Generic, NoReturn, cast -from pydantic import BaseModel, TypeAdapter, ValidationError +from pydantic import BaseModel, ValidationError from typing_extensions import TypeVar +from droid_sdk._high_level._convert import ( + inner_notification, + mcp_status_from_wire, + settings_update_from_wire, + usage_from_wire, +) from droid_sdk._high_level._immutable import FrozenJsonObject, freeze_json_object from droid_sdk._high_level.attachments import ( Base64ImageSource, PdfDocumentSource, TextDocumentSource, ) -from droid_sdk._high_level.config import ( - SessionSettingsUpdate, - SessionTag, -) from droid_sdk._high_level.enums import ( - Autonomy, ErrorType, McpAuthOutcome, - McpServerStatus, - McpServerType, - Mode, - ReasoningEffort, ToolConfirmationOutcome, WorkingState, ) -from droid_sdk._high_level.extensions import ( - McpConfigError, - McpServerStatusInfo, - McpStatusSummary, -) from droid_sdk._high_level.messages import ( AssistantMessage, ContentBlock, @@ -52,7 +43,6 @@ ImageBlock, McpAuthCompleted, McpAuthRequired, - McpStatusChanged, Message, PermissionResolved, RedactedThinkingBlock, @@ -83,6 +73,7 @@ UserMessage, WorkingStateChanged, ) +from droid_sdk._util import consume_task_result from droid_sdk.errors import DroidProtocolError, StreamIncompleteError from droid_sdk.schemas import messages as wire_messages from droid_sdk.schemas.cli import ( @@ -98,7 +89,6 @@ McpAuthRequiredNotification, McpStatusChangedNotification, PermissionResolvedNotification, - SessionNotification, SessionNotificationUnion, SessionTitleUpdatedNotification, SessionTokenUsageChangedNotification, @@ -111,18 +101,14 @@ ToolProgressUpdateNotification, ToolResultNotification, ) -from droid_sdk.schemas.enums import AgentTurnCompletionReason, SessionNotificationType +from droid_sdk.schemas.enums import AgentTurnCompletionReason if TYPE_CHECKING: from droid_sdk._high_level.output import OutputAdapter T = TypeVar("T") E = TypeVar("E", bound=object, default=object) -_NOTIFICATION_ADAPTER: TypeAdapter[SessionNotificationUnion] = TypeAdapter( - SessionNotificationUnion -) _RESULT_TYPES = (RunSuccess, RunInterrupted, RunFailure) -_KNOWN_NOTIFICATION_TYPES = frozenset(item.value for item in SessionNotificationType) def _utc_from_timestamp(value: float) -> datetime: @@ -231,17 +217,6 @@ def _conversation_message( return None -def _usage(value: Any) -> Usage: - return Usage( - input_tokens=value.input_tokens, - output_tokens=value.output_tokens, - cache_creation_tokens=value.cache_creation_tokens, - cache_read_tokens=value.cache_read_tokens, - thinking_tokens=value.thinking_tokens, - factory_credits=value.factory_credits, - ) - - def _tool_progress_update(value: Any) -> ToolProgressUpdate: timestamp = ( None if value.timestamp is None else _utc_from_timestamp(value.timestamp) @@ -270,104 +245,6 @@ def _tool_progress_content(update: ToolProgressUpdate) -> str: return update.details or "" -def _settings(value: Any) -> SessionSettingsUpdate: - mode = None - if value.interaction_mode is not None and value.interaction_mode.value in { - "auto", - "spec", - }: - mode = Mode(value.interaction_mode.value) - elif value.autonomy_mode is not None: - mode = Mode.SPEC if value.autonomy_mode.value == "spec" else Mode.AUTO - autonomy = ( - None if value.autonomy_level is None else Autonomy(value.autonomy_level.value) - ) - if autonomy is None and value.autonomy_mode is not None: - autonomy = { - "normal": Autonomy.OFF, - "auto-low": Autonomy.LOW, - "auto-medium": Autonomy.MEDIUM, - "auto-high": Autonomy.HIGH, - }.get(value.autonomy_mode.value) - return SessionSettingsUpdate( - model=value.model_id, - reasoning_effort=( - None - if value.reasoning_effort is None - else ReasoningEffort(value.reasoning_effort.value) - ), - mode=mode, - autonomy=autonomy, - spec_model=value.spec_mode_model_id, - spec_reasoning_effort=( - None - if value.spec_mode_reasoning_effort is None - else ReasoningEffort(value.spec_mode_reasoning_effort.value) - ), - tags=( - None - if value.tags is None - else tuple( - SessionTag(name=tag.name, metadata=tag.metadata) for tag in value.tags - ) - ), - additional_tools=( - None - if value.additional_tool_ids is None - else set(value.additional_tool_ids) - ), - enabled_tools=( - None if value.enabled_tool_ids is None else set(value.enabled_tool_ids) - ), - disabled_tools=( - None if value.disabled_tool_ids is None else set(value.disabled_tool_ids) - ), - restrict_tools=( - None if value.restrict_tool_ids is None else set(value.restrict_tool_ids) - ), - compaction_threshold_check_enabled=value.compaction_threshold_check_enabled, - ) - - -def _mcp_status(notification: McpStatusChangedNotification) -> McpStatusChanged: - servers = tuple( - McpServerStatusInfo( - name=server.name, - status=McpServerStatus(server.status.value), - source=server.source.value, - is_managed=server.is_managed, - server_type=McpServerType(server.server_type.value), - error=server.error, - tool_count=server.tool_count, - has_auth_tokens=server.has_auth_tokens, - requires_auth=server.requires_auth, - pending_auth_url=server.pending_auth_url, - pending_auth_message=server.pending_auth_message, - pending_auth_state=server.pending_auth_state, - ) - for server in notification.servers - ) - summary = notification.summary - return McpStatusChanged( - servers=servers, - summary=McpStatusSummary( - total=summary.total, - connected=summary.connected, - connecting=summary.connecting, - failed=summary.failed, - disabled=summary.disabled, - config_error=( - None - if summary.config_error is None - else McpConfigError( - path=summary.config_error.path, - message=summary.config_error.message, - ) - ), - ), - ) - - def _json_value(value: object) -> object: if isinstance(value, BaseModel): return value.model_dump(mode="json", by_alias=True, exclude_none=True) @@ -412,50 +289,6 @@ def _javascript_string(value: object) -> str: return str(value) -def _notification_type(raw: object) -> str | None: - if not isinstance(raw, Mapping): - return None - payload = cast("Mapping[str, object]", raw) - params = payload.get("params") - if isinstance(params, Mapping): - params_mapping = cast("Mapping[str, object]", params) - notification = params_mapping.get("notification") - if isinstance(notification, Mapping): - payload = cast("Mapping[str, object]", notification) - value = payload.get("type") - return value if isinstance(value, str) else None - - -def _raise_for_invalid_known_notification(raw: object) -> None: - notification_type = _notification_type(raw) - if notification_type in _KNOWN_NOTIFICATION_TYPES: - raise DroidProtocolError( - f"Invalid {notification_type} notification payload" - ) from None - - -def _inner_notification(raw: object) -> SessionNotificationUnion | None: - raw_object: object = raw - if isinstance(raw, SessionNotification): - return raw.params.notification - if isinstance(raw, Mapping): - mapping = cast("Mapping[str, object]", raw) - params = mapping.get("params") - if isinstance(params, Mapping) and "notification" in params: - try: - return SessionNotification.model_validate( - raw_object - ).params.notification - except ValidationError: - _raise_for_invalid_known_notification(raw_object) - return None - try: - return _NOTIFICATION_ADAPTER.validate_python(raw_object) - except ValidationError: - _raise_for_invalid_known_notification(raw_object) - return None - - def _reject_json_constant(value: str) -> NoReturn: raise ValueError(f"invalid JSON constant: {value}") @@ -520,7 +353,7 @@ def queue_error_event(self, event: ErrorEvent) -> ErrorEvent: def process(self, raw: object) -> tuple[StreamEvent[T], ...]: if self._completed: return () - notification = _inner_notification(raw) + notification = inner_notification(raw) if notification is None: return () @@ -654,7 +487,7 @@ def _convert( WorkingStateChanged(state=WorkingState(notification.new_state.value)) ] if isinstance(notification, SessionTokenUsageChangedNotification): - usage = _usage(notification.token_usage) + usage = usage_from_wire(notification.token_usage) return [ TokenUsageUpdate( input_tokens=usage.input_tokens, @@ -699,13 +532,17 @@ def _convert( ) ] if isinstance(notification, SettingsUpdatedNotification): - return [SettingsUpdated(settings=_settings(notification.settings))] + return [ + SettingsUpdated( + settings=settings_update_from_wire(notification.settings) + ) + ] if isinstance(notification, SessionTitleUpdatedNotification): return [SessionTitleUpdated(title=notification.title)] if isinstance(notification, SessionWorkingDirectoryChangedNotification): return [SessionWorkingDirectoryChanged(cwd=notification.cwd)] if isinstance(notification, McpStatusChangedNotification): - return [_mcp_status(notification)] + return [mcp_status_from_wire(notification)] if isinstance(notification, McpAuthRequiredNotification): return [ McpAuthRequired( @@ -799,7 +636,11 @@ def _complete( if adapted.structured_output is not None: raw = adapted.structured_output - usage = _usage(notification.token_usage) if notification.token_usage else None + usage = ( + usage_from_wire(notification.token_usage) + if notification.token_usage + else None + ) if usage is None: usage = self._last_usage elapsed = max(0.0, self._monotonic() - self._started_at) @@ -1107,10 +948,10 @@ async def _release(self, *, interrupt: bool) -> None: ) except asyncio.TimeoutError: if task is not None: - task.add_done_callback(_consume_task_result) + task.add_done_callback(consume_task_result) except asyncio.CancelledError: if task is not None: - task.add_done_callback(_consume_task_result) + task.add_done_callback(consume_task_result) raise except Exception: # Cleanup and best-effort interruption never mask the primary @@ -1122,9 +963,4 @@ async def aclose(self) -> None: await self._release(interrupt=not self._done) -def _consume_task_result(task: asyncio.Future[object]) -> None: - with contextlib.suppress(BaseException): - task.result() - - __all__ = ["RunStream", "StreamStateTracker"] diff --git a/src/droid_sdk/_util.py b/src/droid_sdk/_util.py new file mode 100644 index 0000000..f4e512b --- /dev/null +++ b/src/droid_sdk/_util.py @@ -0,0 +1,15 @@ +"""Small dependency-free asyncio helpers shared across layers.""" + +from __future__ import annotations + +import contextlib +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + import asyncio + + +def consume_task_result(task: asyncio.Future[Any]) -> None: + """Retrieve a background task's outcome so it never warns as unretrieved.""" + with contextlib.suppress(BaseException): + task.result() diff --git a/src/droid_sdk/transport.py b/src/droid_sdk/transport.py index cbe3458..c2ef1d6 100644 --- a/src/droid_sdk/transport.py +++ b/src/droid_sdk/transport.py @@ -18,6 +18,7 @@ from collections.abc import AsyncIterator # noqa: TC003 from typing import Any +from droid_sdk._util import consume_task_result from droid_sdk.errors import DroidConnectionError, DroidProcessError logger = logging.getLogger(__name__) @@ -440,7 +441,7 @@ async def _finish_stderr_task(self, *, cancel: bool = False) -> None: await asyncio.shield(task) except asyncio.CancelledError: if not task.done(): - task.add_done_callback(_consume_task_result) + task.add_done_callback(consume_task_result) raise with contextlib.suppress(asyncio.CancelledError): task.result() @@ -454,11 +455,6 @@ def _with_stderr_diagnostic(self, message: str) -> str: return f"{message}; stderr: {diagnostic}" -def _consume_task_result(task: asyncio.Task[None]) -> None: - with contextlib.suppress(BaseException): - task.result() - - __all__ = [ "ProcessTransport", ] diff --git a/tests/test_v5_session.py b/tests/test_v5_session.py index 1846819..60c29ea 100644 --- a/tests/test_v5_session.py +++ b/tests/test_v5_session.py @@ -32,6 +32,7 @@ ) from droid_sdk.mcp import create_sdk_mcp_server from droid_sdk.observability import LogEvent, MetricEvent, Observability +from droid_sdk.schemas.client import SessionSettings as WireSessionSettings from droid_sdk.schemas.enums import ( ReasoningEffort as WireReasoningEffort, ) @@ -42,20 +43,13 @@ from droid_sdk.types import DroidClientTransport -def wire_settings() -> SimpleNamespace: - return SimpleNamespace( +def wire_settings() -> WireSessionSettings: + return WireSessionSettings( model_id="model", reasoning_effort=WireReasoningEffort.Medium, - interaction_mode=None, - autonomy_level=None, spec_mode_model_id="spec-model", spec_mode_reasoning_effort=WireReasoningEffort.High, tags=[], - sandbox=None, - additional_tool_ids=None, - enabled_tool_ids=None, - disabled_tool_ids=None, - restrict_tool_ids=None, ) From 77fc0864220e9e04e0736d020cef6aef389fc4f5 Mon Sep 17 00:00:00 2001 From: User Date: Tue, 11 Aug 2026 18:08:43 -0700 Subject: [PATCH 05/30] refactor: share lifecycle cancellation idioms and drop the module test hook The open, close, and replacement paths each hand-rolled the same cancellation-safety idiom: shield-await a shared task, run compensation when the caller is cancelled, and cancel-then-drain tasks that must not outlive their operation. Those idioms now live once in droid_sdk._util (wait_shielded, cancel_and_drain), and the replacement path's inline compensation becomes the named _abandon_cancelled_replacement method. The module-global _replacement_handoff_checkpoint existed only so tests could monkeypatch it. The cancellation delivery point is now an instance seam (Session._replacement_checkpoint, defaulting to _util.cancellation_checkpoint) that tests gate per session without touching module state. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- src/droid_sdk/_high_level/session.py | 53 ++++++++++++++-------------- src/droid_sdk/_util.py | 37 +++++++++++++++++-- tests/test_v5_session.py | 34 +++++++----------- 3 files changed, 75 insertions(+), 49 deletions(-) diff --git a/src/droid_sdk/_high_level/session.py b/src/droid_sdk/_high_level/session.py index 825c125..223681c 100644 --- a/src/droid_sdk/_high_level/session.py +++ b/src/droid_sdk/_high_level/session.py @@ -81,7 +81,12 @@ from droid_sdk._high_level.output import prepare_output_adapter from droid_sdk._high_level.runtime import Runtime from droid_sdk._high_level.streaming import RunStream -from droid_sdk._util import consume_task_result +from droid_sdk._util import ( + cancel_and_drain, + cancellation_checkpoint, + consume_task_result, + wait_shielded, +) from droid_sdk.client import DroidClient from droid_sdk.errors import ( DroidConnectionError, @@ -109,7 +114,7 @@ from droid_sdk.transport import ProcessTransport if TYPE_CHECKING: - from collections.abc import Callable, Mapping, Sequence + from collections.abc import Awaitable, Callable, Mapping, Sequence ModelT = TypeVar("ModelT", bound=BaseModel) @@ -175,6 +180,11 @@ def __init__( self._close_requested = False self._replacement_task: asyncio.Task[tuple[Any, Session]] | None = None self._replacement_close_requested = False + # Cancellation delivery point between successor attach and source + # retirement; tests inject a gated coroutine to widen the window. + self._replacement_checkpoint: Callable[[], Awaitable[None]] = ( + cancellation_checkpoint + ) self._load_mcp_configs: list[dict[str, Any]] = [] self._load_options: dict[str, object] = { "additional_tools": self._config.additional_tools, @@ -286,14 +296,12 @@ async def open(self) -> None: assert task is not None cancelled = False try: - await asyncio.shield(task) + await wait_shielded(task, self._cancel_open_waiter) except asyncio.CancelledError: cancelled = True raise finally: - if cancelled: - await self._cancel_open_waiter(task) - else: + if not cancelled: self._open_waiters -= 1 async def _cancel_open_waiter(self, task: asyncio.Task[None]) -> None: @@ -306,9 +314,7 @@ async def _cancel_open_waiter(self, task: asyncio.Task[None]) -> None: async def _finish_cancelled_open(self, task: asyncio.Task[None]) -> None: cleanup_task: asyncio.Task[None] | None = None - if not task.done(): - task.cancel() - await asyncio.gather(task, return_exceptions=True) + await cancel_and_drain(task) async with self._lifecycle_lock: if self._state is _State.OPEN: self._state = _State.CLOSING @@ -1352,17 +1358,17 @@ async def _replacement_operation( self._replacement_close_requested = False task = asyncio.create_task(self._replacement_impl(operation)) self._replacement_task = task - try: - return await asyncio.shield(task) - except asyncio.CancelledError: - if not task.done(): - task.cancel() - await asyncio.gather(task, return_exceptions=True) - if task.done() and not task.cancelled(): - with contextlib.suppress(BaseException): - _, successor = task.result() - await self._restore_after_cancelled_replacement(successor) - raise + return await wait_shielded(task, self._abandon_cancelled_replacement) + + async def _abandon_cancelled_replacement( + self, + task: asyncio.Task[tuple[Any, Session]], + ) -> None: + await cancel_and_drain(task) + if not task.cancelled(): + with contextlib.suppress(BaseException): + _, successor = task.result() + await self._restore_after_cancelled_replacement(successor) async def _replacement_impl( self, @@ -1373,7 +1379,7 @@ async def _replacement_impl( result = await operation() successor = await self._attach_replacement(result.new_session_id) self._replacement_successor = successor - await _replacement_handoff_checkpoint() + await self._replacement_checkpoint() self._retire_after_replacement(successor) return result, successor except asyncio.CancelledError: @@ -1647,9 +1653,4 @@ async def run( raise -async def _replacement_handoff_checkpoint() -> None: - """Give cancellation a deterministic handoff point after replacement.""" - await asyncio.sleep(0) - - __all__ = ["Session", "run"] diff --git a/src/droid_sdk/_util.py b/src/droid_sdk/_util.py index f4e512b..0d721d2 100644 --- a/src/droid_sdk/_util.py +++ b/src/droid_sdk/_util.py @@ -2,14 +2,47 @@ from __future__ import annotations +import asyncio import contextlib -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, TypeVar if TYPE_CHECKING: - import asyncio + from collections.abc import Awaitable, Callable + +T = TypeVar("T") def consume_task_result(task: asyncio.Future[Any]) -> None: """Retrieve a background task's outcome so it never warns as unretrieved.""" with contextlib.suppress(BaseException): task.result() + + +async def wait_shielded( + task: asyncio.Task[T], + on_cancelled: Callable[[asyncio.Task[T]], Awaitable[None]] | None = None, +) -> T: + """Await a shared task without letting the caller's cancellation cancel it. + + When the caller is cancelled, ``on_cancelled`` runs to completion before + the cancellation propagates, so compensation cannot itself be skipped by + the cancellation that triggered it. + """ + try: + return await asyncio.shield(task) + except asyncio.CancelledError: + if on_cancelled is not None: + await on_cancelled(task) + raise + + +async def cancel_and_drain(task: asyncio.Task[Any]) -> None: + """Cancel a task and wait until it settles, swallowing its outcome.""" + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +async def cancellation_checkpoint() -> None: + """Yield once so a pending cancellation is delivered at this point.""" + await asyncio.sleep(0) diff --git a/tests/test_v5_session.py b/tests/test_v5_session.py index 60c29ea..b5f8a73 100644 --- a/tests/test_v5_session.py +++ b/tests/test_v5_session.py @@ -30,6 +30,7 @@ SessionReplacementError, TextDocumentSource, ) +from droid_sdk._util import cancellation_checkpoint from droid_sdk.mcp import create_sdk_mcp_server from droid_sdk.observability import LogEvent, MetricEvent, Observability from droid_sdk.schemas.client import SessionSettings as WireSessionSettings @@ -744,7 +745,6 @@ async def test_cancelled_replacement_rpc_restores_open_source(operation: str) -> @pytest.mark.parametrize("operation", ["fork", "compact", "rewind"]) async def test_cancelled_replacement_after_successor_creation_restores_source( operation: str, - monkeypatch: pytest.MonkeyPatch, ) -> None: config = SessionConfig( additional_tools={"Custom"}, @@ -763,11 +763,7 @@ async def gated_handoff() -> None: entered.set() await gate.wait() - monkeypatch.setattr( - session_module, - "_replacement_handoff_checkpoint", - gated_handoff, - ) + session._replacement_checkpoint = gated_handoff if operation == "fork": replacement = asyncio.create_task(session.fork()) elif operation == "compact": @@ -803,26 +799,22 @@ async def test_cancelled_replacement_racing_close_cleans_successor() -> None: await session.open() entered = asyncio.Event() gate = asyncio.Event() - original = session_module._replacement_handoff_checkpoint async def gated_handoff() -> None: entered.set() await gate.wait() - await original() + await cancellation_checkpoint() - session_module._replacement_handoff_checkpoint = gated_handoff - try: - replacement = asyncio.create_task(session.fork()) - await entered.wait() - closing = asyncio.create_task(session.close()) - while not session._replacement_close_requested: - await asyncio.sleep(0) - replacement.cancel() - with pytest.raises(asyncio.CancelledError): - await replacement - await closing - finally: - session_module._replacement_handoff_checkpoint = original + session._replacement_checkpoint = gated_handoff + replacement = asyncio.create_task(session.fork()) + await entered.wait() + closing = asyncio.create_task(session.close()) + while not session._replacement_close_requested: + await asyncio.sleep(0) + replacement.cancel() + with pytest.raises(asyncio.CancelledError): + await replacement + await closing client = FakeClient.instances[0] assert client.close_session_calls == 1 From b13d365937c54448f5ba82f2949c36726a933ff1 Mon Sep 17 00:00:00 2001 From: User Date: Tue, 11 Aug 2026 18:10:26 -0700 Subject: [PATCH 06/30] refactor: construct replacement successors explicitly Successor sessions were cloned with object.__new__ plus a __dict__ copy and a trailing list of field resets, so every new Session attribute silently leaked into successors unless someone remembered to reset it here. The successor is now built through Session's real constructor, and _create_successor names exactly which state carries over: load policies, and the live wiring (client, dispatcher, in-process MCP servers) the successor adopts. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- src/droid_sdk/_high_level/session.py | 37 +++++++++++++++++----------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/src/droid_sdk/_high_level/session.py b/src/droid_sdk/_high_level/session.py index 223681c..5b6a89d 100644 --- a/src/droid_sdk/_high_level/session.py +++ b/src/droid_sdk/_high_level/session.py @@ -1453,24 +1453,33 @@ async def _attach_replacement(self, replacement_id: str) -> Session: rollback_error=rollback, ) from cause raise SessionReplacementError(self.id, replacement_id) from cause - - successor = object.__new__(Session) - successor.__dict__ = self.__dict__.copy() + return self._create_successor(replacement_id, loaded) + + def _create_successor(self, replacement_id: str, loaded: Any) -> Session: + """Build the open session that takes over this session's connection.""" + successor = Session( + model=self._model, + reasoning_effort=self._reasoning_effort, + config=self._config, + interactions=self._interactions, + runtime=self._runtime_config, + api_key=self._api_key, + ) + successor._requested_cwd = self._requested_cwd + successor._resume_id = self._resume_id + successor._resume_options = self._resume_options + successor._load_options = self._load_options + successor._load_mcp_configs = self._load_mcp_configs + # The successor adopts the live wiring: the same client, the + # dispatcher whose handlers that client dispatches to, and the + # in-process MCP servers. + successor._dispatcher = self._dispatcher + successor._client = self._client + successor._sdk_servers = self._sdk_servers successor._id = replacement_id successor._settings = full_settings_from_wire(loaded.settings) successor._cwd = load_cwd(loaded, self._cwd or Path.cwd()) successor._state = _State.OPEN - successor._active_stream = None - successor._subscriptions = set() - successor._replacement_successor = None - successor._lifecycle_lock = asyncio.Lock() - successor._open_task = None - successor._open_cleanup_task = None - successor._open_waiters = 0 - successor._close_task = None - successor._close_requested = False - successor._replacement_task = None - successor._replacement_close_requested = False successor._bind_metadata() return successor From bd15e8e32a93b589019e5faa4e7d562613a50870 Mon Sep 17 00:00:00 2001 From: User Date: Tue, 11 Aug 2026 18:14:40 -0700 Subject: [PATCH 07/30] refactor: split request/response operations out of session.py session.py fused the lifecycle state machine with every request/response operation the session exposes. The plain one-call-one-request methods (settings, tools, skills, MCP management, context, spec mode) and the replacement-producing operations (fork, compact, rewind) now live in SessionOperationsMixin in _session_operations.py, with the state and helpers they rely on declared explicitly at the top of the mixin. session.py keeps the cohesive open/close/replacement state machine, streaming turn management, and run(), dropping from 1,998 lines at review time to 1,166. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- .../_high_level/_session_operations.py | 559 ++++++++++++++++++ src/droid_sdk/_high_level/session.py | 504 +--------------- 2 files changed, 561 insertions(+), 502 deletions(-) create mode 100644 src/droid_sdk/_high_level/_session_operations.py diff --git a/src/droid_sdk/_high_level/_session_operations.py b/src/droid_sdk/_high_level/_session_operations.py new file mode 100644 index 0000000..9285922 --- /dev/null +++ b/src/droid_sdk/_high_level/_session_operations.py @@ -0,0 +1,559 @@ +"""Request/response session operations layered on the lifecycle core. + +:class:`SessionOperationsMixin` holds every session method that is a plain +request/response call on the low-level client (settings, tools, skills, MCP +management, context, spec mode) plus the replacement-producing operations +(fork, compact, rewind). The lifecycle state machine that these methods rely +on lives in :mod:`droid_sdk._high_level.session`. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any, Literal, cast + +from droid_sdk._high_level._convert import ( + header_mapping, + list_or_none, + mcp_config_to_wire, + mcp_server_from_wire, + mcp_summary_from_wire, + tool_category, + wire_reasoning, + wire_tags, +) +from droid_sdk._high_level.config import SessionSettings, UpdateSettingsResult +from droid_sdk._high_level.enums import ContextAccuracy, Mode +from droid_sdk._high_level.extensions import ( + CompactOutcome, + McpMutationResult, + McpServersResult, + McpToolInfo, + McpToolInputSchema, + RewindEvictedFile, + RewindFileCreation, + RewindFileSnapshot, + RewindInfo, + RewindOutcome, + SkillInfo, + SkillMutationResult, + SkillResource, + SkillsResult, + ToolInfo, +) +from droid_sdk._high_level.messages import ContextUsage +from droid_sdk.schemas.enums import ( + AutonomyLevel as WireAutonomy, +) +from droid_sdk.schemas.enums import ( + DroidInteractionMode, + SettingsLevel, +) +from droid_sdk.schemas.enums import ( + McpServerType as WireMcpServerType, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from droid_sdk._high_level.config import SessionTag + from droid_sdk._high_level.enums import Autonomy, ReasoningEffort + from droid_sdk._high_level.extensions import ( + HttpMcpServerConfig, + SseMcpServerConfig, + StdioMcpServerConfig, + ) + from droid_sdk._high_level.session import Session + from droid_sdk.client import DroidClient + + +class _Unset: + pass + + +_UNSET = _Unset() + + +class SessionOperationsMixin: + """Session operations that translate one call into one client request.""" + + if TYPE_CHECKING: + _settings: SessionSettings | None + _load_options: dict[str, object] + + @property + def settings(self) -> SessionSettings: ... + + def _ensure_active(self) -> None: ... + + def _require_client(self) -> DroidClient: ... + + async def _replacement_operation( + self, + operation: Callable[[], Any], + ) -> tuple[Any, Session]: ... + + async def update_settings( + self, + *, + model: str | None = None, + reasoning_effort: ReasoningEffort | None = None, + mode: Mode | None = None, + autonomy: Autonomy | None = None, + spec_model: str | None | _Unset = _UNSET, + spec_reasoning_effort: ReasoningEffort | None | _Unset = _UNSET, + tags: Sequence[SessionTag] | None = None, + compaction_token_limit: int | None = None, + compaction_threshold_check_enabled: bool | None = None, + additional_tools: set[str] | frozenset[str] | None = None, + enabled_tools: set[str] | frozenset[str] | None = None, + disabled_tools: set[str] | frozenset[str] | None = None, + restrict_tools: set[str] | frozenset[str] | None = None, + ) -> UpdateSettingsResult: + self._ensure_active() + spec_model_value = None if isinstance(spec_model, _Unset) else spec_model + spec_reasoning_value = ( + None if isinstance(spec_reasoning_effort, _Unset) else spec_reasoning_effort + ) + explicit_null_fields: list[ + Literal["specModeModelId", "specModeReasoningEffort"] + ] = [] + if spec_model is None: + explicit_null_fields.append("specModeModelId") + if spec_reasoning_effort is None: + explicit_null_fields.append("specModeReasoningEffort") + await self._require_client().update_session_settings( + model_id=model, + reasoning_effort=wire_reasoning(reasoning_effort), + interaction_mode=( + None if mode is None else DroidInteractionMode(mode.value) + ), + autonomy_level=(None if autonomy is None else WireAutonomy(autonomy.value)), + spec_mode_model_id=spec_model_value, + spec_mode_reasoning_effort=wire_reasoning(spec_reasoning_value), + tags=cast("Any", None if tags is None else wire_tags(tags)), + compaction_token_limit=compaction_token_limit, + compaction_threshold_check_enabled=(compaction_threshold_check_enabled), + additional_tool_ids=list_or_none(additional_tools), + enabled_tool_ids=list_or_none(enabled_tools), + disabled_tool_ids=list_or_none(disabled_tools), + restrict_tool_ids=list_or_none(restrict_tools), + explicit_null_fields=explicit_null_fields, + ) + for key, value in ( + ("additional_tools", additional_tools), + ("enabled_tools", enabled_tools), + ("disabled_tools", disabled_tools), + ("restrict_tools", restrict_tools), + ): + if value is not None: + self._load_options[key] = frozenset(value) + current = self.settings + self._settings = SessionSettings( + model=current.model if model is None else model, + reasoning_effort=( + current.reasoning_effort + if reasoning_effort is None + else reasoning_effort + ), + mode=current.mode if mode is None else mode, + autonomy=current.autonomy if autonomy is None else autonomy, + spec_model=( + current.spec_model if isinstance(spec_model, _Unset) else spec_model + ), + spec_reasoning_effort=( + current.spec_reasoning_effort + if isinstance(spec_reasoning_effort, _Unset) + else spec_reasoning_effort + ), + tags=current.tags if tags is None else tags, + sandbox=current.sandbox, + additional_tools=( + current.additional_tools + if additional_tools is None + else additional_tools + ), + enabled_tools=( + current.enabled_tools if enabled_tools is None else enabled_tools + ), + disabled_tools=( + current.disabled_tools if disabled_tools is None else disabled_tools + ), + restrict_tools=( + current.restrict_tools if restrict_tools is None else restrict_tools + ), + ) + return UpdateSettingsResult() + + async def rename(self, title: str) -> None: + self._ensure_active() + await self._require_client().rename_session(title=title) + + async def list_tools( + self, + *, + model: str | None = None, + mode: Mode | None = None, + autonomy: Autonomy | None = None, + spec_model: str | None = None, + additional_tools: set[str] | frozenset[str] | None = None, + enabled_tools: set[str] | frozenset[str] | None = None, + disabled_tools: set[str] | frozenset[str] | None = None, + restrict_tools: set[str] | frozenset[str] | None = None, + skip_permissions_unsafe: bool | None = None, + ) -> list[ToolInfo]: + self._ensure_active() + result = await self._require_client().list_tools( + model_id=model, + interaction_mode=( + None if mode is None else DroidInteractionMode(mode.value) + ), + autonomy_level=(None if autonomy is None else WireAutonomy(autonomy.value)), + spec_mode_model_id=spec_model, + additional_tool_ids=list_or_none(additional_tools), + enabled_tool_ids=list_or_none(enabled_tools), + disabled_tool_ids=list_or_none(disabled_tools), + restrict_tool_ids=list_or_none(restrict_tools), + skip_permissions_unsafe=skip_permissions_unsafe, + ) + return [ + ToolInfo( + id=item.llm_id or item.id, + display_name=item.display_name or item.llm_id or item.id, + description=item.description or "", + category=tool_category(item.category), + default_allowed=item.default_allowed, + allowed=item.currently_allowed, + ) + for item in result.tools + ] + + async def list_skills(self) -> SkillsResult: + self._ensure_active() + result = await self._require_client().list_skills() + return SkillsResult( + skills=[ + SkillInfo( + name=item.name, + description=item.description, + location=cast("Any", item.location.value), + file_path=item.file_path, + enabled=item.enabled, + user_invocable=item.user_invocable, + version=item.version, + content=item.content, + resources=tuple( + SkillResource( + name=resource.name, + path=resource.path, + type=resource.type, + ) + for resource in (item.resources or ()) + ), + disabled_by=item.disabled_by, + ) + for item in result.skills + ], + project_available=result.project_available, + ) + + async def enable_skill( + self, + name: str, + *, + scope: Literal["user", "project"] = "user", + ) -> SkillMutationResult: + return await self._set_skill(name, False, scope) + + async def disable_skill( + self, + name: str, + *, + scope: Literal["user", "project"] = "user", + ) -> SkillMutationResult: + return await self._set_skill(name, True, scope) + + async def _set_skill( + self, + name: str, + disabled: bool, + scope: Literal["user", "project"], + ) -> SkillMutationResult: + self._ensure_active() + result = await self._require_client().set_skill_disabled( + skill_name=name, + disabled=disabled, + settings_level=SettingsLevel(scope), + ) + return SkillMutationResult(result.success) + + async def list_mcp_servers(self) -> McpServersResult: + self._ensure_active() + result = await self._require_client().list_mcp_servers() + return McpServersResult( + servers=tuple(mcp_server_from_wire(item) for item in result.servers), + summary=mcp_summary_from_wire(result.summary), + ) + + async def list_mcp_tools(self) -> list[McpToolInfo]: + self._ensure_active() + result = await self._require_client().list_mcp_tools() + return [ + McpToolInfo( + server_name=item.server_name, + name=item.name, + description=item.description, + is_enabled=item.is_enabled, + is_read_only=item.is_read_only, + input_schema=( + None + if item.input_schema is None + else McpToolInputSchema( + type=item.input_schema.type, + properties=item.input_schema.properties, + required=item.input_schema.required, + ) + ), + ) + for item in result.tools + ] + + async def add_mcp_server( + self, + config: StdioMcpServerConfig | HttpMcpServerConfig | SseMcpServerConfig, + ) -> McpMutationResult: + self._ensure_active() + raw = mcp_config_to_wire(config) + headers = cast("object", raw.get("headers")) + result = await self._require_client().add_mcp_server( + name=config.name, + type=WireMcpServerType(raw.get("type", "stdio")), + url=cast("str | None", raw.get("url")), + headers=( + None + if not isinstance(headers, list) + else header_mapping(cast("list[object]", headers)) + ), + command=cast("str | None", raw.get("command")), + args=cast("list[str] | None", raw.get("args")), + env=cast("dict[str, str] | None", raw.get("env")), + oauth=cast("Any", raw.get("oauth")), + ) + return McpMutationResult(result.success) + + async def remove_mcp_server( + self, + name: str, + ) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().remove_mcp_server( + server_name=name, + settings_level=SettingsLevel.User, + ) + return McpMutationResult(result.success) + + async def enable_mcp_server( + self, + name: str, + ) -> McpMutationResult: + return await self._toggle_mcp_server(name, True) + + async def disable_mcp_server( + self, + name: str, + ) -> McpMutationResult: + return await self._toggle_mcp_server(name, False) + + async def _toggle_mcp_server( + self, + name: str, + enabled: bool, + ) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().toggle_mcp_server( + server_name=name, + enabled=enabled, + settings_level=SettingsLevel.User, + ) + return McpMutationResult(result.success) + + async def enable_mcp_tool( + self, server_name: str, tool_name: str + ) -> McpMutationResult: + return await self._toggle_mcp_tool(server_name, tool_name, True) + + async def disable_mcp_tool( + self, server_name: str, tool_name: str + ) -> McpMutationResult: + return await self._toggle_mcp_tool(server_name, tool_name, False) + + async def _toggle_mcp_tool( + self, + server_name: str, + tool_name: str, + enabled: bool, + ) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().toggle_mcp_tool( + server_name=server_name, + tool_name=tool_name, + enabled=enabled, + ) + return McpMutationResult(result.success) + + async def authenticate_mcp_server(self, name: str) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().authenticate_mcp_server(server_name=name) + return McpMutationResult(result.success) + + async def cancel_mcp_auth(self, name: str) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().cancel_mcp_auth(server_name=name) + return McpMutationResult(result.success) + + async def clear_mcp_auth(self, name: str) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().clear_mcp_auth(server_name=name) + return McpMutationResult(result.success) + + async def submit_mcp_auth_code( + self, name: str, *, code: str, state: str + ) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().submit_mcp_auth_code( + server_name=name, code=code, state=state + ) + return McpMutationResult(result.success) + + async def submit_mcp_auth_error( + self, + name: str, + *, + error: str, + state: str, + error_description: str | None = None, + ) -> McpMutationResult: + self._ensure_active() + result = await self._require_client().submit_mcp_auth_error( + server_name=name, + error=error, + state=state, + error_description=error_description, + ) + return McpMutationResult(result.success) + + async def context(self) -> ContextUsage: + self._ensure_active() + result = await self._require_client().get_context_stats() + timestamp = datetime.fromisoformat(result.updated_at.replace("Z", "+00:00")) + return ContextUsage( + used=result.used, + remaining=result.remaining, + limit=result.limit, + accuracy=ContextAccuracy(result.accuracy.value), + updated_at=timestamp, + ) + + async def enter_spec( + self, + *, + model: str | None = None, + reasoning_effort: ReasoningEffort | None = None, + ) -> UpdateSettingsResult: + if model is None and reasoning_effort is None: + return await self.update_settings(mode=Mode.SPEC) + if model is None: + return await self.update_settings( + mode=Mode.SPEC, + spec_reasoning_effort=reasoning_effort, + ) + if reasoning_effort is None: + return await self.update_settings( + mode=Mode.SPEC, + spec_model=model, + ) + return await self.update_settings( + mode=Mode.SPEC, + spec_model=model, + spec_reasoning_effort=reasoning_effort, + ) + + async def leave_spec(self) -> UpdateSettingsResult: + return await self.update_settings(mode=Mode.AUTO) + + async def fork( + self, + *, + title: str | None = None, + tags: Sequence[SessionTag] | None = None, + ) -> Session: + _, successor = await self._replacement_operation( + lambda: self._require_client().fork_session( + title=title, + tags=cast("Any", None if tags is None else wire_tags(tags)), + ) + ) + return successor + + async def compact( + self, + *, + instructions: str | None = None, + ) -> CompactOutcome: + result, successor = await self._replacement_operation( + lambda: self._require_client().compact_session( + custom_instructions=instructions + ) + ) + return CompactOutcome(successor, result.removed_count) + + async def rewind_info(self, message_id: str) -> RewindInfo: + self._ensure_active() + result = await self._require_client().get_rewind_info(message_id=message_id) + return RewindInfo( + available_files=tuple( + RewindFileSnapshot(item.file_path, item.content_hash, item.size) + for item in result.available_files + ), + created_files=tuple( + RewindFileCreation(item.file_path) for item in result.created_files + ), + evicted_files=tuple( + RewindEvictedFile(item.file_path, item.reason) + for item in result.evicted_files + ), + ) + + async def rewind( + self, + message_id: str, + *, + restore: Sequence[RewindFileSnapshot] = (), + delete: Sequence[RewindFileCreation] = (), + title: str, + ) -> RewindOutcome: + result, successor = await self._replacement_operation( + lambda: self._require_client().execute_rewind( + message_id=message_id, + files_to_restore=[ + { + "filePath": item.file_path, + "contentHash": item.content_hash, + "size": item.size, + } + for item in restore + ], + files_to_delete=[{"filePath": item.file_path} for item in delete], + fork_title=title, + ) + ) + return RewindOutcome( + successor, + result.restored_count, + result.deleted_count, + result.failed_restore_count, + result.failed_delete_count, + ) + + +__all__ = ["SessionOperationsMixin"] diff --git a/src/droid_sdk/_high_level/session.py b/src/droid_sdk/_high_level/session.py index 5b6a89d..9e7935e 100644 --- a/src/droid_sdk/_high_level/session.py +++ b/src/droid_sdk/_high_level/session.py @@ -9,7 +9,6 @@ import importlib.metadata import os import uuid -from datetime import datetime from enum import Enum from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast, overload @@ -19,20 +18,17 @@ from droid_sdk._high_level._convert import ( document_to_wire, full_settings_from_wire, - header_mapping, list_or_none, load_cwd, mcp_config_to_wire, - mcp_server_from_wire, - mcp_summary_from_wire, merged_settings, raw_inner_notification, - tool_category, wire_reasoning, wire_source, wire_tags, ) from droid_sdk._high_level._immutable import JsonObject +from droid_sdk._high_level._session_operations import SessionOperationsMixin from droid_sdk._high_level.attachments import Document, Image from droid_sdk._high_level.config import ( JsonSchema, @@ -40,40 +36,17 @@ SessionSettings, SessionSource, SessionTag, - UpdateSettingsResult, ) from droid_sdk._high_level.enums import ( - Autonomy, - ContextAccuracy, - Mode, ReasoningEffort, ) from droid_sdk._high_level.extensions import ( - CompactOutcome, - HttpMcpServerConfig, - McpMutationResult, McpServerConfig, - McpServersResult, - McpToolInfo, - McpToolInputSchema, - RewindEvictedFile, - RewindFileCreation, - RewindFileSnapshot, - RewindInfo, - RewindOutcome, SdkMcpServer, - SkillInfo, - SkillMutationResult, - SkillResource, - SkillsResult, - SseMcpServerConfig, - StdioMcpServerConfig, - ToolInfo, ) from droid_sdk._high_level.interaction_adapter import InteractionDispatcher from droid_sdk._high_level.interactions import InteractionHandlers from droid_sdk._high_level.messages import ( - ContextUsage, RunResult, StreamEvent, StreamMessage, @@ -106,10 +79,6 @@ ) from droid_sdk.schemas.enums import ( DroidInteractionMode, - SettingsLevel, -) -from droid_sdk.schemas.enums import ( - McpServerType as WireMcpServerType, ) from droid_sdk.transport import ProcessTransport @@ -119,13 +88,6 @@ ModelT = TypeVar("ModelT", bound=BaseModel) -class _Unset: - pass - - -_UNSET = _Unset() - - class _State(Enum): LAZY = "lazy" OPENING = "opening" @@ -137,7 +99,7 @@ class _State(Enum): CLOSED = "closed" -class Session: +class Session(SessionOperationsMixin): """A lazy, single-turn-at-a-time Droid session.""" def __init__( @@ -857,102 +819,6 @@ async def interrupt(self) -> None: self._ensure_active() await self._require_client().interrupt_session() - async def update_settings( - self, - *, - model: str | None = None, - reasoning_effort: ReasoningEffort | None = None, - mode: Mode | None = None, - autonomy: Autonomy | None = None, - spec_model: str | None | _Unset = _UNSET, - spec_reasoning_effort: ReasoningEffort | None | _Unset = _UNSET, - tags: Sequence[SessionTag] | None = None, - compaction_token_limit: int | None = None, - compaction_threshold_check_enabled: bool | None = None, - additional_tools: set[str] | frozenset[str] | None = None, - enabled_tools: set[str] | frozenset[str] | None = None, - disabled_tools: set[str] | frozenset[str] | None = None, - restrict_tools: set[str] | frozenset[str] | None = None, - ) -> UpdateSettingsResult: - self._ensure_active() - spec_model_value = None if isinstance(spec_model, _Unset) else spec_model - spec_reasoning_value = ( - None if isinstance(spec_reasoning_effort, _Unset) else spec_reasoning_effort - ) - explicit_null_fields: list[ - Literal["specModeModelId", "specModeReasoningEffort"] - ] = [] - if spec_model is None: - explicit_null_fields.append("specModeModelId") - if spec_reasoning_effort is None: - explicit_null_fields.append("specModeReasoningEffort") - await self._require_client().update_session_settings( - model_id=model, - reasoning_effort=wire_reasoning(reasoning_effort), - interaction_mode=( - None if mode is None else DroidInteractionMode(mode.value) - ), - autonomy_level=(None if autonomy is None else WireAutonomy(autonomy.value)), - spec_mode_model_id=spec_model_value, - spec_mode_reasoning_effort=wire_reasoning(spec_reasoning_value), - tags=cast("Any", None if tags is None else wire_tags(tags)), - compaction_token_limit=compaction_token_limit, - compaction_threshold_check_enabled=(compaction_threshold_check_enabled), - additional_tool_ids=list_or_none(additional_tools), - enabled_tool_ids=list_or_none(enabled_tools), - disabled_tool_ids=list_or_none(disabled_tools), - restrict_tool_ids=list_or_none(restrict_tools), - explicit_null_fields=explicit_null_fields, - ) - for key, value in ( - ("additional_tools", additional_tools), - ("enabled_tools", enabled_tools), - ("disabled_tools", disabled_tools), - ("restrict_tools", restrict_tools), - ): - if value is not None: - self._load_options[key] = frozenset(value) - current = self.settings - self._settings = SessionSettings( - model=current.model if model is None else model, - reasoning_effort=( - current.reasoning_effort - if reasoning_effort is None - else reasoning_effort - ), - mode=current.mode if mode is None else mode, - autonomy=current.autonomy if autonomy is None else autonomy, - spec_model=( - current.spec_model if isinstance(spec_model, _Unset) else spec_model - ), - spec_reasoning_effort=( - current.spec_reasoning_effort - if isinstance(spec_reasoning_effort, _Unset) - else spec_reasoning_effort - ), - tags=current.tags if tags is None else tags, - sandbox=current.sandbox, - additional_tools=( - current.additional_tools - if additional_tools is None - else additional_tools - ), - enabled_tools=( - current.enabled_tools if enabled_tools is None else enabled_tools - ), - disabled_tools=( - current.disabled_tools if disabled_tools is None else disabled_tools - ), - restrict_tools=( - current.restrict_tools if restrict_tools is None else restrict_tools - ), - ) - return UpdateSettingsResult() - - async def rename(self, title: str) -> None: - self._ensure_active() - await self._require_client().rename_session(title=title) - def on_notification( self, callback: Callable[[Mapping[str, object]], None], @@ -977,372 +843,6 @@ def unsubscribe() -> None: self._subscriptions.add(unsubscribe) return unsubscribe - async def list_tools( - self, - *, - model: str | None = None, - mode: Mode | None = None, - autonomy: Autonomy | None = None, - spec_model: str | None = None, - additional_tools: set[str] | frozenset[str] | None = None, - enabled_tools: set[str] | frozenset[str] | None = None, - disabled_tools: set[str] | frozenset[str] | None = None, - restrict_tools: set[str] | frozenset[str] | None = None, - skip_permissions_unsafe: bool | None = None, - ) -> list[ToolInfo]: - self._ensure_active() - result = await self._require_client().list_tools( - model_id=model, - interaction_mode=( - None if mode is None else DroidInteractionMode(mode.value) - ), - autonomy_level=(None if autonomy is None else WireAutonomy(autonomy.value)), - spec_mode_model_id=spec_model, - additional_tool_ids=list_or_none(additional_tools), - enabled_tool_ids=list_or_none(enabled_tools), - disabled_tool_ids=list_or_none(disabled_tools), - restrict_tool_ids=list_or_none(restrict_tools), - skip_permissions_unsafe=skip_permissions_unsafe, - ) - return [ - ToolInfo( - id=item.llm_id or item.id, - display_name=item.display_name or item.llm_id or item.id, - description=item.description or "", - category=tool_category(item.category), - default_allowed=item.default_allowed, - allowed=item.currently_allowed, - ) - for item in result.tools - ] - - async def list_skills(self) -> SkillsResult: - self._ensure_active() - result = await self._require_client().list_skills() - return SkillsResult( - skills=[ - SkillInfo( - name=item.name, - description=item.description, - location=cast("Any", item.location.value), - file_path=item.file_path, - enabled=item.enabled, - user_invocable=item.user_invocable, - version=item.version, - content=item.content, - resources=tuple( - SkillResource( - name=resource.name, - path=resource.path, - type=resource.type, - ) - for resource in (item.resources or ()) - ), - disabled_by=item.disabled_by, - ) - for item in result.skills - ], - project_available=result.project_available, - ) - - async def enable_skill( - self, - name: str, - *, - scope: Literal["user", "project"] = "user", - ) -> SkillMutationResult: - return await self._set_skill(name, False, scope) - - async def disable_skill( - self, - name: str, - *, - scope: Literal["user", "project"] = "user", - ) -> SkillMutationResult: - return await self._set_skill(name, True, scope) - - async def _set_skill( - self, - name: str, - disabled: bool, - scope: Literal["user", "project"], - ) -> SkillMutationResult: - self._ensure_active() - result = await self._require_client().set_skill_disabled( - skill_name=name, - disabled=disabled, - settings_level=SettingsLevel(scope), - ) - return SkillMutationResult(result.success) - - async def list_mcp_servers(self) -> McpServersResult: - self._ensure_active() - result = await self._require_client().list_mcp_servers() - return McpServersResult( - servers=tuple(mcp_server_from_wire(item) for item in result.servers), - summary=mcp_summary_from_wire(result.summary), - ) - - async def list_mcp_tools(self) -> list[McpToolInfo]: - self._ensure_active() - result = await self._require_client().list_mcp_tools() - return [ - McpToolInfo( - server_name=item.server_name, - name=item.name, - description=item.description, - is_enabled=item.is_enabled, - is_read_only=item.is_read_only, - input_schema=( - None - if item.input_schema is None - else McpToolInputSchema( - type=item.input_schema.type, - properties=item.input_schema.properties, - required=item.input_schema.required, - ) - ), - ) - for item in result.tools - ] - - async def add_mcp_server( - self, - config: StdioMcpServerConfig | HttpMcpServerConfig | SseMcpServerConfig, - ) -> McpMutationResult: - self._ensure_active() - raw = mcp_config_to_wire(config) - headers = cast("object", raw.get("headers")) - result = await self._require_client().add_mcp_server( - name=config.name, - type=WireMcpServerType(raw.get("type", "stdio")), - url=cast("str | None", raw.get("url")), - headers=( - None - if not isinstance(headers, list) - else header_mapping(cast("list[object]", headers)) - ), - command=cast("str | None", raw.get("command")), - args=cast("list[str] | None", raw.get("args")), - env=cast("dict[str, str] | None", raw.get("env")), - oauth=cast("Any", raw.get("oauth")), - ) - return McpMutationResult(result.success) - - async def remove_mcp_server( - self, - name: str, - ) -> McpMutationResult: - self._ensure_active() - result = await self._require_client().remove_mcp_server( - server_name=name, - settings_level=SettingsLevel.User, - ) - return McpMutationResult(result.success) - - async def enable_mcp_server( - self, - name: str, - ) -> McpMutationResult: - return await self._toggle_mcp_server(name, True) - - async def disable_mcp_server( - self, - name: str, - ) -> McpMutationResult: - return await self._toggle_mcp_server(name, False) - - async def _toggle_mcp_server( - self, - name: str, - enabled: bool, - ) -> McpMutationResult: - self._ensure_active() - result = await self._require_client().toggle_mcp_server( - server_name=name, - enabled=enabled, - settings_level=SettingsLevel.User, - ) - return McpMutationResult(result.success) - - async def enable_mcp_tool( - self, server_name: str, tool_name: str - ) -> McpMutationResult: - return await self._toggle_mcp_tool(server_name, tool_name, True) - - async def disable_mcp_tool( - self, server_name: str, tool_name: str - ) -> McpMutationResult: - return await self._toggle_mcp_tool(server_name, tool_name, False) - - async def _toggle_mcp_tool( - self, - server_name: str, - tool_name: str, - enabled: bool, - ) -> McpMutationResult: - self._ensure_active() - result = await self._require_client().toggle_mcp_tool( - server_name=server_name, - tool_name=tool_name, - enabled=enabled, - ) - return McpMutationResult(result.success) - - async def authenticate_mcp_server(self, name: str) -> McpMutationResult: - self._ensure_active() - result = await self._require_client().authenticate_mcp_server(server_name=name) - return McpMutationResult(result.success) - - async def cancel_mcp_auth(self, name: str) -> McpMutationResult: - self._ensure_active() - result = await self._require_client().cancel_mcp_auth(server_name=name) - return McpMutationResult(result.success) - - async def clear_mcp_auth(self, name: str) -> McpMutationResult: - self._ensure_active() - result = await self._require_client().clear_mcp_auth(server_name=name) - return McpMutationResult(result.success) - - async def submit_mcp_auth_code( - self, name: str, *, code: str, state: str - ) -> McpMutationResult: - self._ensure_active() - result = await self._require_client().submit_mcp_auth_code( - server_name=name, code=code, state=state - ) - return McpMutationResult(result.success) - - async def submit_mcp_auth_error( - self, - name: str, - *, - error: str, - state: str, - error_description: str | None = None, - ) -> McpMutationResult: - self._ensure_active() - result = await self._require_client().submit_mcp_auth_error( - server_name=name, - error=error, - state=state, - error_description=error_description, - ) - return McpMutationResult(result.success) - - async def context(self) -> ContextUsage: - self._ensure_active() - result = await self._require_client().get_context_stats() - timestamp = datetime.fromisoformat(result.updated_at.replace("Z", "+00:00")) - return ContextUsage( - used=result.used, - remaining=result.remaining, - limit=result.limit, - accuracy=ContextAccuracy(result.accuracy.value), - updated_at=timestamp, - ) - - async def enter_spec( - self, - *, - model: str | None = None, - reasoning_effort: ReasoningEffort | None = None, - ) -> UpdateSettingsResult: - if model is None and reasoning_effort is None: - return await self.update_settings(mode=Mode.SPEC) - if model is None: - return await self.update_settings( - mode=Mode.SPEC, - spec_reasoning_effort=reasoning_effort, - ) - if reasoning_effort is None: - return await self.update_settings( - mode=Mode.SPEC, - spec_model=model, - ) - return await self.update_settings( - mode=Mode.SPEC, - spec_model=model, - spec_reasoning_effort=reasoning_effort, - ) - - async def leave_spec(self) -> UpdateSettingsResult: - return await self.update_settings(mode=Mode.AUTO) - - async def fork( - self, - *, - title: str | None = None, - tags: Sequence[SessionTag] | None = None, - ) -> Session: - _, successor = await self._replacement_operation( - lambda: self._require_client().fork_session( - title=title, - tags=cast("Any", None if tags is None else wire_tags(tags)), - ) - ) - return successor - - async def compact( - self, - *, - instructions: str | None = None, - ) -> CompactOutcome: - result, successor = await self._replacement_operation( - lambda: self._require_client().compact_session( - custom_instructions=instructions - ) - ) - return CompactOutcome(successor, result.removed_count) - - async def rewind_info(self, message_id: str) -> RewindInfo: - self._ensure_active() - result = await self._require_client().get_rewind_info(message_id=message_id) - return RewindInfo( - available_files=tuple( - RewindFileSnapshot(item.file_path, item.content_hash, item.size) - for item in result.available_files - ), - created_files=tuple( - RewindFileCreation(item.file_path) for item in result.created_files - ), - evicted_files=tuple( - RewindEvictedFile(item.file_path, item.reason) - for item in result.evicted_files - ), - ) - - async def rewind( - self, - message_id: str, - *, - restore: Sequence[RewindFileSnapshot] = (), - delete: Sequence[RewindFileCreation] = (), - title: str, - ) -> RewindOutcome: - result, successor = await self._replacement_operation( - lambda: self._require_client().execute_rewind( - message_id=message_id, - files_to_restore=[ - { - "filePath": item.file_path, - "contentHash": item.content_hash, - "size": item.size, - } - for item in restore - ], - files_to_delete=[{"filePath": item.file_path} for item in delete], - fork_title=title, - ) - ) - return RewindOutcome( - successor, - result.restored_count, - result.deleted_count, - result.failed_restore_count, - result.failed_delete_count, - ) - async def _replacement_operation( self, operation: Callable[[], Any], From 5dadc3953b56d315f6e9a7aea0a332f1ce2a7c42 Mon Sep 17 00:00:00 2001 From: User Date: Tue, 11 Aug 2026 18:16:31 -0700 Subject: [PATCH 08/30] refactor: narrow the pyright suppression in client.py client.py disabled reportCallIssue, reportUnknownMemberType, and reportUnknownVariableType for the whole file. The unknown-type escapes were four real gaps in _dispatch_notification's payload probing, fixed with explicit narrowing. What remains is only reportCallIssue, which pyright raises because its dataclass_transform view of the request-param models sees the camelCase wire aliases instead of the snake_case names that populate_by_name accepts; mypy's pydantic plugin validates those calls. The header now documents exactly that. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- src/droid_sdk/client.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/droid_sdk/client.py b/src/droid_sdk/client.py index 560af72..de60376 100644 --- a/src/droid_sdk/client.py +++ b/src/droid_sdk/client.py @@ -1,4 +1,9 @@ -# pyright: reportCallIssue=false, reportUnknownMemberType=false, reportUnknownVariableType=false +# The request-param pydantic models declare camelCase wire aliases with +# populate_by_name=True. Pyright's dataclass_transform support only sees the +# aliases, so it rejects the snake_case keywords these constructors accept at +# runtime; mypy's pydantic plugin validates those same calls. Only +# call-signature checking is disabled here. +# pyright: reportCallIssue=false """DroidClient — high-level async API for the Factory Droid SDK. @@ -15,7 +20,7 @@ import logging from collections.abc import AsyncIterator, Callable, Sequence from types import TracebackType # noqa: TC003 -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING, Any, Literal, cast from droid_sdk.errors import ( ConnectionError as DroidConnectionError, @@ -1834,11 +1839,13 @@ def _dispatch_notification(self, notification: dict[str, Any]) -> None: """ # Extract the notification type from the payload notif_type: str | None = None - params = notification.get("params") + params = cast("object", notification.get("params")) if isinstance(params, dict): - inner = params.get("notification") + inner = cast("dict[str, object]", params).get("notification") if isinstance(inner, dict): - notif_type = inner.get("type") + raw_type = cast("dict[str, object]", inner).get("type") + if isinstance(raw_type, str): + notif_type = raw_type for callback, type_filter in list(self._notification_listeners): if type_filter is not None and notif_type != type_filter.value: From beb21f0744fd7e31bb22c80398377437a46b7a57 Mon Sep 17 00:00:00 2001 From: User Date: Tue, 11 Aug 2026 23:22:36 -0700 Subject: [PATCH 09/30] refactor: hold SDK MCP server runtime state in a weak-keyed registry SdkMcpServer smuggled mutable runtime state through object-typed fields on a frozen dataclass, forcing droid_sdk.mcp to read and write them via object.__getattribute__/__setattr__ plus casts. The handle is now honestly frozen: droid_sdk.mcp keeps a WeakKeyDictionary of typed per-server state, so the attribute smuggling and its casts are gone. The handle drops slots (weak references need __weakref__) and field equality (registry keys need an identity hash; the field-based hash was already unusable on unhashable tool schemas). Also port the server start/close single-flight to the shared wait_shielded/cancel_and_drain helpers, and name RunStream's finish grace period (_FINISH_GRACE_SECONDS) instead of an inline 0.1. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- src/droid_sdk/_high_level/extensions.py | 18 +--- src/droid_sdk/_high_level/streaming.py | 6 +- src/droid_sdk/mcp.py | 128 ++++++++++++------------ tests/test_v5_mcp.py | 18 ++-- 4 files changed, 82 insertions(+), 88 deletions(-) diff --git a/src/droid_sdk/_high_level/extensions.py b/src/droid_sdk/_high_level/extensions.py index 203ee7a..a855ce6 100644 --- a/src/droid_sdk/_high_level/extensions.py +++ b/src/droid_sdk/_high_level/extensions.py @@ -187,23 +187,15 @@ def __post_init__(self) -> None: ) -@dataclass(frozen=True, slots=True) +# No slots and identity equality: droid_sdk.mcp keys its per-server runtime +# state on weak references to this handle, which needs __weakref__ and an +# identity hash (the field-based hash would also choke on the unhashable +# tool schemas). +@dataclass(frozen=True, eq=False) class SdkMcpServer: name: str version: str tools: Sequence[DroidTool] - _runtime: object | None = field( - default=None, - init=False, - repr=False, - compare=False, - ) - _lifecycle: object | None = field( - default=None, - init=False, - repr=False, - compare=False, - ) def __post_init__(self) -> None: object.__setattr__(self, "tools", tuple(self.tools)) diff --git a/src/droid_sdk/_high_level/streaming.py b/src/droid_sdk/_high_level/streaming.py index cd88340..6644615 100644 --- a/src/droid_sdk/_high_level/streaming.py +++ b/src/droid_sdk/_high_level/streaming.py @@ -110,6 +110,10 @@ E = TypeVar("E", bound=object, default=object) _RESULT_TYPES = (RunSuccess, RunInterrupted, RunFailure) +# How long RunStream._release waits for the finish callback (typically an +# interrupt request) before detaching it to complete in the background. +_FINISH_GRACE_SECONDS = 0.1 + def _utc_from_timestamp(value: float) -> datetime: """Convert the protocol's epoch-millisecond timestamps to aware UTC.""" @@ -944,7 +948,7 @@ async def _release(self, *, interrupt: bool) -> None: task = finish_task await asyncio.wait_for( asyncio.shield(finish_task), - timeout=0.1, + timeout=_FINISH_GRACE_SECONDS, ) except asyncio.TimeoutError: if task is not None: diff --git a/src/droid_sdk/mcp.py b/src/droid_sdk/mcp.py index b368da2..1e791e3 100644 --- a/src/droid_sdk/mcp.py +++ b/src/droid_sdk/mcp.py @@ -13,6 +13,7 @@ from contextlib import asynccontextmanager, suppress from dataclasses import dataclass, field from typing import Any, ParamSpec, cast, get_type_hints, overload +from weakref import WeakKeyDictionary try: import uvicorn @@ -44,6 +45,7 @@ StdioMcpServerConfig, ToolResponse, ) +from droid_sdk._util import cancel_and_drain, wait_shielded P = ParamSpec("P") @@ -188,22 +190,26 @@ class _ServerRuntime: @dataclass(slots=True) -class _ServerLifecycle: +class _ServerState: lock: asyncio.Lock = field(default_factory=asyncio.Lock) + runtime: _ServerRuntime | None = None start_task: asyncio.Task[HttpMcpServerConfig] | None = None close_task: asyncio.Task[None] | None = None start_waiters: int = 0 -def _server_lifecycle(server: SdkMcpServer) -> _ServerLifecycle: - lifecycle = cast( - "_ServerLifecycle | None", - object.__getattribute__(server, "_lifecycle"), - ) - if lifecycle is None: - lifecycle = _ServerLifecycle() - object.__setattr__(server, "_lifecycle", lifecycle) - return lifecycle +# Keeps the public SdkMcpServer handle honestly frozen: all mutable +# runtime state lives here, keyed by server identity, and disappears +# with the handle. +_SERVER_STATES: WeakKeyDictionary[SdkMcpServer, _ServerState] = WeakKeyDictionary() + + +def _server_state(server: SdkMcpServer) -> _ServerState: + state = _SERVER_STATES.get(server) + if state is None: + state = _ServerState() + _SERVER_STATES[server] = state + return state class _BearerEndpoint: @@ -326,44 +332,45 @@ async def lifespan(_app: Starlette) -> AsyncGenerator[None, None]: def sdk_server_config(server: SdkMcpServer) -> HttpMcpServerConfig | None: - runtime = cast( - "_ServerRuntime | None", - object.__getattribute__(server, "_runtime"), - ) - return None if runtime is None else runtime.config + state = _SERVER_STATES.get(server) + return None if state is None or state.runtime is None else state.runtime.config async def start_sdk_server(server: SdkMcpServer) -> HttpMcpServerConfig: - lifecycle = _server_lifecycle(server) - async with lifecycle.lock: - current = cast( - "_ServerRuntime | None", - object.__getattribute__(server, "_runtime"), - ) - if current is not None and ( - lifecycle.close_task is None or lifecycle.close_task.done() + state = _server_state(server) + async with state.lock: + if state.runtime is not None and ( + state.close_task is None or state.close_task.done() ): - return current.config - if lifecycle.start_task is not None and not lifecycle.start_task.done(): - task = lifecycle.start_task - elif lifecycle.close_task is not None and not lifecycle.close_task.done(): - task = asyncio.create_task(_start_after_close(server, lifecycle.close_task)) - lifecycle.start_task = task + return state.runtime.config + if state.start_task is not None and not state.start_task.done(): + task = state.start_task + elif state.close_task is not None and not state.close_task.done(): + task = asyncio.create_task(_start_after_close(server, state.close_task)) + state.start_task = task else: task = asyncio.create_task(_start_sdk_server_impl(server)) - lifecycle.start_task = task - lifecycle.start_waiters += 1 + state.start_task = task + state.start_waiters += 1 + + async def abandon(start_task: asyncio.Task[HttpMcpServerConfig]) -> None: + # The last cancelled waiter tears down whatever the start produced. + state.start_waiters -= 1 + if state.start_waiters == 0 and state.start_task is start_task: + state.start_task = None + state.close_task = asyncio.create_task( + _close_after_start(server, start_task) + ) + cancelled = False try: - return await asyncio.shield(task) + return await wait_shielded(task, abandon) except asyncio.CancelledError: cancelled = True raise finally: - lifecycle.start_waiters -= 1 - if cancelled and lifecycle.start_waiters == 0 and lifecycle.start_task is task: - lifecycle.start_task = None - lifecycle.close_task = asyncio.create_task(_close_after_start(server, task)) + if not cancelled: + state.start_waiters -= 1 async def _start_after_close( @@ -414,38 +421,32 @@ async def _start_sdk_server_impl(server: SdkMcpServer) -> HttpMcpServerConfig: oauth=False, ) runtime = _ServerRuntime(config, token, uvicorn_server, task, listener) - object.__setattr__(server, "_runtime", runtime) + _server_state(server).runtime = runtime return config except BaseException: if uvicorn_server is not None: uvicorn_server.should_exit = True listener.close() if task is not None: - if not task.done(): - task.cancel() - await asyncio.gather(task, return_exceptions=True) + await cancel_and_drain(task) raise async def close_sdk_server(server: SdkMcpServer) -> None: - lifecycle = _server_lifecycle(server) - async with lifecycle.lock: - if lifecycle.start_task is not None and not lifecycle.start_task.done(): - task = asyncio.create_task(_close_after_start(server, lifecycle.start_task)) - lifecycle.start_task = None - lifecycle.close_task = task - elif lifecycle.close_task is not None and not lifecycle.close_task.done(): - task = lifecycle.close_task + state = _server_state(server) + async with state.lock: + if state.start_task is not None and not state.start_task.done(): + task = asyncio.create_task(_close_after_start(server, state.start_task)) + state.start_task = None + state.close_task = task + elif state.close_task is not None and not state.close_task.done(): + task = state.close_task + elif state.runtime is None: + return else: - runtime = cast( - "_ServerRuntime | None", - object.__getattribute__(server, "_runtime"), - ) - if runtime is None: - return - task = asyncio.create_task(_close_sdk_server_impl(server, runtime)) - lifecycle.close_task = task - await asyncio.shield(task) + task = asyncio.create_task(_close_sdk_server_impl(server, state.runtime)) + state.close_task = task + await wait_shielded(task) async def _close_after_start( @@ -456,10 +457,7 @@ async def _close_after_start( await start_task except BaseException: return - runtime = cast( - "_ServerRuntime | None", - object.__getattribute__(server, "_runtime"), - ) + runtime = _server_state(server).runtime if runtime is not None: await _close_sdk_server_impl(server, runtime) @@ -472,12 +470,12 @@ async def _close_sdk_server_impl( try: await asyncio.wait_for(runtime.task, timeout=5) except asyncio.TimeoutError: - runtime.task.cancel() - await asyncio.gather(runtime.task, return_exceptions=True) + await cancel_and_drain(runtime.task) finally: runtime.listener.close() - if object.__getattribute__(server, "_runtime") is runtime: - object.__setattr__(server, "_runtime", None) + state = _server_state(server) + if state.runtime is runtime: + state.runtime = None __all__ = [ diff --git a/tests/test_v5_mcp.py b/tests/test_v5_mcp.py index eaea2d5..afd2146 100644 --- a/tests/test_v5_mcp.py +++ b/tests/test_v5_mcp.py @@ -205,10 +205,10 @@ async def gated_start(server_value: object) -> object: try: assert calls == 1 assert server.config is config - runtime = server._runtime + runtime = mcp_module._server_state(server).runtime assert runtime is not None - assert not runtime.task.done() # type: ignore[attr-defined] - assert runtime.listener.fileno() >= 0 # type: ignore[attr-defined] + assert not runtime.task.done() + assert runtime.listener.fileno() >= 0 finally: await server.close() @@ -237,9 +237,9 @@ async def gated_start(server_value: object) -> object: release.set() await server.close() assert server.config is None - lifecycle = server._lifecycle - assert lifecycle is not None - assert lifecycle.close_task.done() # type: ignore[attr-defined] + state = mcp_module._server_state(server) + assert state.close_task is not None + assert state.close_task.done() restarted = await server.start() try: @@ -254,7 +254,7 @@ async def test_sdk_mcp_cancelled_close_finishes_once_and_restarts( ) -> None: server = create_sdk_mcp_server("calculator", [add]) await server.start() - runtime = server._runtime + runtime = mcp_module._server_state(server).runtime assert runtime is not None entered = asyncio.Event() release = asyncio.Event() @@ -281,8 +281,8 @@ async def gated_close(server_value: object, runtime_value: object) -> None: await second assert calls == 1 assert server.config is None - assert runtime.task.done() # type: ignore[attr-defined] - assert runtime.listener.fileno() == -1 # type: ignore[attr-defined] + assert runtime.task.done() + assert runtime.listener.fileno() == -1 restarted = await server.start() try: From fc3905c749dcc92f2b7bfab743f35209e321d34b Mon Sep 17 00:00:00 2001 From: User Date: Tue, 11 Aug 2026 23:41:16 -0700 Subject: [PATCH 10/30] refactor: deduplicate the aware-datetime check and terminal-result seal Full-branch simplify pass. The timezone-awareness validator was copied verbatim in config.py and messages.py; it now lives once in _immutable as ensure_aware. The three terminal result dataclasses repeated the same messages/structured_output freezing in their __post_init__, now shared as _seal_terminal_result. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- src/droid_sdk/_high_level/_immutable.py | 11 +++++- src/droid_sdk/_high_level/config.py | 15 ++++---- src/droid_sdk/_high_level/messages.py | 50 +++++++++++-------------- 3 files changed, 38 insertions(+), 38 deletions(-) diff --git a/src/droid_sdk/_high_level/_immutable.py b/src/droid_sdk/_high_level/_immutable.py index 29720bd..e83d039 100644 --- a/src/droid_sdk/_high_level/_immutable.py +++ b/src/droid_sdk/_high_level/_immutable.py @@ -5,7 +5,10 @@ import math from collections.abc import Iterator, Mapping, Sequence from types import MappingProxyType -from typing import TypeAlias, cast +from typing import TYPE_CHECKING, TypeAlias, cast + +if TYPE_CHECKING: + from datetime import datetime JsonValue: TypeAlias = ( bool | int | float | str | None | list["JsonValue"] | dict[str, "JsonValue"] @@ -51,6 +54,12 @@ def __eq__(self, other: object) -> bool: return self._values == other +def ensure_aware(value: datetime, name: str) -> None: + """Reject naive datetimes so the public models stay timezone-aware.""" + if value.tzinfo is None or value.utcoffset() is None: + raise ValueError(f"{name} must be timezone-aware") + + def freeze_json(value: object, *, where: str = "value") -> FrozenJsonValue: """Validate a JSON value and recursively replace mutable containers.""" if value is None or isinstance(value, (str, bool)): diff --git a/src/droid_sdk/_high_level/config.py b/src/droid_sdk/_high_level/config.py index c208caf..76f2c0f 100644 --- a/src/droid_sdk/_high_level/config.py +++ b/src/droid_sdk/_high_level/config.py @@ -11,7 +11,11 @@ from types import MappingProxyType from typing import TYPE_CHECKING -from droid_sdk._high_level._immutable import FrozenJsonObject, freeze_json_object +from droid_sdk._high_level._immutable import ( + FrozenJsonObject, + ensure_aware, + freeze_json_object, +) from droid_sdk._high_level.enums import ( Autonomy, Mode, @@ -30,11 +34,6 @@ ) -def _aware(value: datetime, name: str) -> None: - if value.tzinfo is None or value.utcoffset() is None: - raise ValueError(f"{name} must be timezone-aware") - - def _freeze_tool_sets(value: object) -> None: for name in _TOOL_SET_FIELDS: items = getattr(value, name) @@ -180,8 +179,8 @@ class SavedSession: is_favorite: bool = False def __post_init__(self) -> None: - _aware(self.modified_at, "modified_at") - _aware(self.created_at, "created_at") + ensure_aware(self.modified_at, "modified_at") + ensure_aware(self.created_at, "created_at") if self.cwd is not None: object.__setattr__(self, "cwd", Path(self.cwd)) diff --git a/src/droid_sdk/_high_level/messages.py b/src/droid_sdk/_high_level/messages.py index 1804fcf..a6c13c0 100644 --- a/src/droid_sdk/_high_level/messages.py +++ b/src/droid_sdk/_high_level/messages.py @@ -7,7 +7,7 @@ from collections.abc import Mapping, Sequence from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone -from typing import Generic, Literal, TypeAlias, TypeVar +from typing import Any, Generic, Literal, TypeAlias, TypeVar from pydantic import ValidationError @@ -15,6 +15,7 @@ FrozenJsonObject, FrozenJsonValue, JsonValue, + ensure_aware, freeze_json, freeze_json_object, ) @@ -35,11 +36,6 @@ T = TypeVar("T") -def _aware(value: datetime, name: str) -> None: - if value.tzinfo is None or value.utcoffset() is None: - raise ValueError(f"{name} must be timezone-aware") - - @dataclass(frozen=True, slots=True) class TextBlock: id: str | None = field(default=None, kw_only=True) @@ -145,8 +141,8 @@ class ConversationMessage: def __post_init__(self) -> None: object.__setattr__(self, "content", tuple(self.content)) - _aware(self.created_at, "created_at") - _aware(self.updated_at, "updated_at") + ensure_aware(self.created_at, "created_at") + ensure_aware(self.updated_at, "updated_at") @dataclass(frozen=True, slots=True) @@ -219,7 +215,7 @@ class ErrorEvent: timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) def __post_init__(self) -> None: - _aware(self.timestamp, "timestamp") + ensure_aware(self.timestamp, "timestamp") Message: TypeAlias = ( @@ -276,7 +272,7 @@ class ToolProgressUpdate: def __post_init__(self) -> None: if self.timestamp is not None: - _aware(self.timestamp, "timestamp") + ensure_aware(self.timestamp, "timestamp") if self.parameters is not None: object.__setattr__( self, @@ -317,7 +313,7 @@ class ContextUsage: updated_at: datetime def __post_init__(self) -> None: - _aware(self.updated_at, "updated_at") + ensure_aware(self.updated_at, "updated_at") @dataclass(frozen=True, slots=True) @@ -403,6 +399,17 @@ def _freeze_structured_output( return freeze_json_object(value, where="structured_output") +def _seal_terminal_result( + result: RunSuccess[Any] | RunInterrupted[Any] | RunFailure[Any], +) -> None: + object.__setattr__(result, "messages", tuple(result.messages)) + object.__setattr__( + result, + "structured_output", + _freeze_structured_output(result.structured_output), + ) + + @dataclass(frozen=True, slots=True) class RunResult(Generic[T]): """Runtime base class shared by all terminal result dataclasses.""" @@ -449,12 +456,7 @@ class RunSuccess(RunResult[T]): interrupted: Literal[False] = field(default=False, init=False) def __post_init__(self) -> None: - object.__setattr__(self, "messages", tuple(self.messages)) - object.__setattr__( - self, - "structured_output", - _freeze_structured_output(self.structured_output), - ) + _seal_terminal_result(self) @dataclass(frozen=True, slots=True) @@ -475,12 +477,7 @@ class RunInterrupted(RunResult[T]): interrupted: Literal[True] = field(default=True, init=False) def __post_init__(self) -> None: - object.__setattr__(self, "messages", tuple(self.messages)) - object.__setattr__( - self, - "structured_output", - _freeze_structured_output(self.structured_output), - ) + _seal_terminal_result(self) @dataclass(frozen=True, slots=True) @@ -506,12 +503,7 @@ def __post_init__(self) -> None: "error_structured_output", }: raise ValueError(f"invalid failure subtype: {self.subtype!r}") - object.__setattr__(self, "messages", tuple(self.messages)) - object.__setattr__( - self, - "structured_output", - _freeze_structured_output(self.structured_output), - ) + _seal_terminal_result(self) StreamMessage: TypeAlias = Message | RunSuccess[T] | RunInterrupted[T] | RunFailure[T] From 2d656398d06d31174aa898ec04c475ec50aea5a6 Mon Sep 17 00:00:00 2001 From: User Date: Tue, 11 Aug 2026 23:48:48 -0700 Subject: [PATCH 11/30] docs: tighten the Python SDK reference Collapse the repeated-type continuation rows in the field and enum tables into one row per type, remove the duplicated SessionSettingsUpdate and MCP method tables, fold the two attachment examples into one, and trim prose that restated adjacent tables. No factual changes; claims re-verified against the source. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 158 ++++++++++------------------------- 1 file changed, 43 insertions(+), 115 deletions(-) diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index 3a1e82a..86af1bb 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -338,9 +338,8 @@ await session.update_settings( ) ``` -Only supplied fields change. The method also accepts interaction mode, -mode-specific model settings, tags, compaction settings, and all native-tool -override fields. Set nullable Spec-model fields to `None` to clear them. +Only supplied fields change. Set nullable Spec-model fields to `None` to +clear them. `update_settings()` accepts: @@ -452,33 +451,14 @@ first. Timestamps are timezone-aware. | Type | Fields | | --- | --- | -| `SessionSettings` | `model`, `reasoning_effort`, `mode`, `autonomy` | -| `SessionSettings` | `spec_model`, `spec_reasoning_effort`, `tags`, `sandbox` | -| `SessionSettings` | `additional_tools`, `enabled_tools`, `disabled_tools` | -| `SessionSettings` | `restrict_tools` | -| `SessionSettingsUpdate` | `model`, `reasoning_effort`, `mode`, `autonomy` | -| `SessionSettingsUpdate` | `spec_model`, `spec_reasoning_effort`, `tags` | -| `SessionSettingsUpdate` | `additional_tools`, `enabled_tools`, `disabled_tools` | -| `SessionSettingsUpdate` | `restrict_tools`, `compaction_threshold_check_enabled` | +| `SessionSettings` | `model`, `reasoning_effort`, `mode`, `autonomy`, `spec_model`, `spec_reasoning_effort`, `tags`, `sandbox`, `additional_tools`, `enabled_tools`, `disabled_tools`, `restrict_tools` | +| `SessionSettingsUpdate` | `model`, `reasoning_effort`, `mode`, `autonomy`, `spec_model`, `spec_reasoning_effort`, `tags`, `additional_tools`, `enabled_tools`, `disabled_tools`, `restrict_tools`, `compaction_threshold_check_enabled` | | `SandboxSettings` | `enabled: bool`, `mode: str \| None = None` | | `SessionTag` | `name`, `metadata` | -| `SavedSession` | `id`, `title`, `owner`, `message_count` | -| `SavedSession` | `modified_at`, `created_at`, `cwd`, `is_favorite` | +| `SavedSession` | `id`, `title`, `owner`, `message_count`, `modified_at`, `created_at`, `cwd`, `is_favorite` | -Every `SessionSettingsUpdate` field defaults to `None`: - -| Field | Type | -| --- | --- | -| `model` | `str \| None` | -| `reasoning_effort` | `ReasoningEffort \| None` | -| `mode` | `Mode \| None` | -| `autonomy` | `Autonomy \| None` | -| `spec_model` | `str \| None` | -| `spec_reasoning_effort` | `ReasoningEffort \| None` | -| `tags` | `Sequence[SessionTag] \| None` | -| `additional_tools`, `enabled_tools` | `set[str] \| frozenset[str] \| None` | -| `disabled_tools`, `restrict_tools` | `set[str] \| frozenset[str] \| None` | -| `compaction_threshold_check_enabled` | `bool \| None` | +Every `SessionSettingsUpdate` field defaults to `None`. Its field types +match the `update_settings()` table above. `list_sessions()` returns `list[SavedSession]`. Its filters are `cwd`, `all_workspaces`, and `limit`. @@ -554,9 +534,7 @@ StreamMessage[T] = ( | `AssistantMessage` | Conversation-message fields | | `ToolCall` | `name`, `tool_use_id`, `input` | | `ToolResult` | `tool_use_id`, `tool_name`, `content`, `is_error` | -| `HookExecution` | `hook_id`, `event_name`, `matcher`, `tool_call_id` | -| `HookExecution` | `command`, `timeout`, `status`, `exit_code` | -| `HookExecution` | `stdout`, `stderr`, `suppress_output` | +| `HookExecution` | `hook_id`, `event_name`, `matcher`, `tool_call_id`, `command`, `timeout`, `status`, `exit_code`, `stdout`, `stderr`, `suppress_output` | | `ErrorEvent` | `message`, `error_type`, `timestamp` | | `RunResult[T]` | Terminal result described below | @@ -669,8 +647,7 @@ ContentBlock = ( | Type | Fields | | --- | --- | | `TextBlock` | `id`, `text` | -| `ThinkingBlock` | `id`, `thinking`, `signature`, `signature_provider` | -| `ThinkingBlock` | `duration` | +| `ThinkingBlock` | `id`, `thinking`, `signature`, `signature_provider`, `duration` | | `RedactedThinkingBlock` | `id`, `data` | | `ToolUseBlock` | `id`, `name`, `input`, `thought_signature` | | `ToolResultBlock` | `id`, `tool_use_id`, `content`, `is_error` | @@ -770,12 +747,9 @@ print(context.used, context.remaining, context.limit, context.accuracy) | Type | Fields | | --- | --- | -| `Usage` | `input_tokens`, `output_tokens`, `cache_creation_tokens` | -| `Usage` | `cache_read_tokens`, `thinking_tokens`, `factory_credits` | +| `Usage` | `input_tokens`, `output_tokens`, `cache_creation_tokens`, `cache_read_tokens`, `thinking_tokens`, `factory_credits` | | `ContextUsage` | `used`, `remaining`, `limit`, `accuracy`, `updated_at` | -| `ToolProgressUpdate` | `type`, `tool_name`, `status`, `details`, `text` | -| `ToolProgressUpdate` | `error`, `timestamp`, `parameters`, `value_snippet` | -| `ToolProgressUpdate` | `terminal_id`, `full_output`, `subagent_session_id` | +| `ToolProgressUpdate` | `type`, `tool_name`, `status`, `details`, `text`, `error`, `timestamp`, `parameters`, `value_snippet`, `terminal_id`, `full_output`, `subagent_session_id` | `ToolProgressUpdate.type` is `"tool_call"`, `"tool_result"`, `"error"`, `"status"`, or `"message"`. @@ -853,9 +827,14 @@ stream; it is idempotent after release. Message options mirror TypeScript's `images` and `files` fields: ```python +from droid_sdk import Document, Image, run + result = await run( "Compare these files.", - images=[Image.from_path("screenshot.png")], + images=[ + Image.from_path("screenshot.png"), + Image.from_bytes(image_bytes, media_type="image/png"), + ], files=[ Document.from_path("report.pdf"), Document.from_text(source, name="auth.py"), @@ -863,23 +842,11 @@ result = await run( ) ``` -```python -from droid_sdk import Document, Image - -result = await run( - "Review these inputs.", - images=[Image.from_bytes(image_bytes, media_type="image/png")], - files=[Document.from_text(report, name="report.md")], -) -``` - -Path constructors are Python conveniences that produce the same base64 image, -text-document, or base64-document sources accepted by TypeScript. Supported -image types are PNG, JPEG, GIF, and WebP. Invalid local input raises -`InvalidAttachmentError` before the turn starts. Image URLs are unsupported. -`MAX_ATTACHMENT_BYTES` is `5 * 1024 * 1024`; `MAX_PDF_ATTACHMENT_BYTES` is -`3 * 1024 * 1024`. `ImageMediaType` is the literal union `"image/jpeg"`, -`"image/png"`, `"image/gif"`, and `"image/webp"`. +The constructors produce the same base64 sources the TypeScript SDK accepts. +Supported image types are PNG, JPEG, GIF, and WebP; image URLs are +unsupported. Invalid local input raises `InvalidAttachmentError` before the +turn starts. Attachments are limited to `MAX_ATTACHMENT_BYTES` (5 MiB), and +PDFs to `MAX_PDF_ATTACHMENT_BYTES` (3 MiB). ### Input schemas @@ -1111,8 +1078,7 @@ QuestionHandler = Callable[ | Type | Fields | | --- | --- | | `InteractionHandlers` | `on_permission`, `on_question` | -| `PermissionRequest` | `actions`, `options` | -| `PermissionRequest` | `associated_session_ids` | +| `PermissionRequest` | `actions`, `options`, `associated_session_ids` | | `PermissionOption` | `label`, `value` | | `PermissionResponse` | `selected_option`, `comment`, `edited_spec_content` | | `QuestionRequest` | `tool_call_id`, `questions` | @@ -1141,20 +1107,14 @@ Every action includes its `tool_use`, confirmation type, and typed details: | Type | Detail fields | | --- | --- | | `EditAction` | `file_path`, `file_name`, `old_content`, `new_content` | -| `ExecuteAction` | `full_command`, `command`, `extracted_commands` | -| `ExecuteAction` | `impact_level`, `risk_level_reason` | +| `ExecuteAction` | `full_command`, `command`, `extracted_commands`, `impact_level`, `risk_level_reason` | | `CreateFile` | `file_path`, `file_name`, `content` | | `AskUserAction` | `questionnaire`, `questions`, `parse_error` | | `ExitSpecModeAction` | `plan`, `title` | -| `ApplyPatchAction` | `file_path`, `file_name`, `patch_content` | -| `ApplyPatchAction` | `old_content`, `new_content`, `files` | -| `ApplyPatchFile` | `file_path`, `file_name`, `operation`, `move_to` | -| `ApplyPatchFile` | `old_content`, `new_content` | -| `McpToolAction` | `tool_name`, `server_name`, `actual_tool_name` | -| `McpToolAction` | `impact_level` | -| `SandboxViolationAction` | `violating_tool_name`, `target`, `operation` | -| `SandboxViolationAction` | `violation_type`, `reason`, `violation_reason` | -| `SandboxViolationAction` | `is_org_deny` | +| `ApplyPatchAction` | `file_path`, `file_name`, `patch_content`, `old_content`, `new_content`, `files` | +| `ApplyPatchFile` | `file_path`, `file_name`, `operation`, `move_to`, `old_content`, `new_content` | +| `McpToolAction` | `tool_name`, `server_name`, `actual_tool_name`, `impact_level` | +| `SandboxViolationAction` | `violating_tool_name`, `target`, `operation`, `violation_type`, `reason`, `violation_reason`, `is_org_deny` | | `DroidShieldViolationAction` | `command`, `reason` | `AskUserParseError(message: str, line: int | None = None)` records malformed @@ -1214,11 +1174,8 @@ The four override parameters accept `set[str]`, `frozenset[str]`, or `None`. | Type | Fields | | --- | --- | -| `ToolInfo` | `id`, `display_name`, `description`, `category` | -| `ToolInfo` | `default_allowed`, `allowed` | -| `ListToolsOptions` | `model`, `mode`, `autonomy`, `spec_model` | -| `ListToolsOptions` | `additional_tools`, `enabled_tools`, `disabled_tools` | -| `ListToolsOptions` | `restrict_tools`, `skip_permissions_unsafe` | +| `ToolInfo` | `id`, `display_name`, `description`, `category`, `default_allowed`, `allowed` | +| `ListToolsOptions` | `model`, `mode`, `autonomy`, `spec_model`, `additional_tools`, `enabled_tools`, `disabled_tools`, `restrict_tools`, `skip_permissions_unsafe` | ## Tools and extensions @@ -1253,9 +1210,7 @@ Skills may come from project, personal, built-in, or automation settings. | Type | Fields | | --- | --- | | `SkillsResult` | `skills`, `project_available` | -| `SkillInfo` | `name`, `description`, `location`, `file_path`, `enabled` | -| `SkillInfo` | `user_invocable`, `version`, `content`, `resources` | -| `SkillInfo` | `disabled_by` | +| `SkillInfo` | `name`, `description`, `location`, `file_path`, `enabled`, `user_invocable`, `version`, `content`, `resources`, `disabled_by` | | `SkillResource` | `name`, `path`, `type` | | `SkillMutationResult` | `success` | @@ -1354,6 +1309,8 @@ passed through `SessionConfig` are session-scoped. | Session MCP method | Signature | | --- | --- | +| `list_mcp_servers` | `() -> McpServersResult` | +| `list_mcp_tools` | `() -> list[McpToolInfo]` | | `add_mcp_server` | `(config) -> McpMutationResult` | | `remove_mcp_server` | `(name: str) -> McpMutationResult` | | `enable_mcp_server` / `disable_mcp_server` | `(name: str) -> McpMutationResult` | @@ -1380,35 +1337,17 @@ McpServerConfig = ( | `HttpMcpServerConfig` | `name`, `url`, `headers`, `oauth` | | `SseMcpServerConfig` | `name`, `url`, `headers`, `oauth` | | `HttpHeader` | `name`, `value` | -| `McpOAuthOptions` | `scopes`, `resource`, `authorization_server_issuer` | -| `McpOAuthOptions` | `client_metadata_url`, `client_id`, `client_secret` | -| `McpOAuthOptions` | `callback_port`, `token_endpoint_auth_method` | +| `McpOAuthOptions` | `scopes`, `resource`, `authorization_server_issuer`, `client_metadata_url`, `client_id`, `client_secret`, `callback_port`, `token_endpoint_auth_method` | | `McpServersResult` | `servers`, `summary` | -| `McpServerStatusInfo` | `name`, `status`, `source`, `is_managed`, `error` | -| `McpServerStatusInfo` | `tool_count`, `server_type`, `has_auth_tokens` | -| `McpServerStatusInfo` | `requires_auth`, `pending_auth_url` | -| `McpServerStatusInfo` | `pending_auth_message`, `pending_auth_state` | -| `McpStatusSummary` | `total`, `connected`, `connecting` | -| `McpStatusSummary` | `failed`, `disabled` | -| `McpStatusSummary` | `config_error` | +| `McpServerStatusInfo` | `name`, `status`, `source`, `is_managed`, `error`, `tool_count`, `server_type`, `has_auth_tokens`, `requires_auth`, `pending_auth_url`, `pending_auth_message`, `pending_auth_state` | +| `McpStatusSummary` | `total`, `connected`, `connecting`, `failed`, `disabled`, `config_error` | | `McpConfigError` | `path`, `message` | -| `McpToolInfo` | `server_name`, `name`, `description`, `is_enabled` | -| `McpToolInfo` | `is_read_only`, `input_schema` | +| `McpToolInfo` | `server_name`, `name`, `description`, `is_enabled`, `is_read_only`, `input_schema` | | `McpToolInputSchema` | `type`, `properties`, `required` | | `McpMutationResult` | `success` | `oauth` accepts `McpOAuthOptions` or `False`. -| Method | Returns | -| --- | --- | -| `list_mcp_servers()` | `McpServersResult` | -| `list_mcp_tools()` | `list[McpToolInfo]` | -| `add_mcp_server(...)` | `McpMutationResult` | -| `remove_mcp_server(...)` | `McpMutationResult` | -| `enable_mcp_server(...)` | `McpMutationResult` | -| `disable_mcp_server(...)` | `McpMutationResult` | -| `authenticate_mcp_server(...)` | `McpMutationResult` | - Remove, enable, and disable mutate user-scoped MCP configuration only. These methods do not accept a project-scope argument. @@ -1487,8 +1426,7 @@ async with outcome.session as rewound: | `RewindFileSnapshot` | `file_path`, `content_hash`, `size` | | `RewindFileCreation` | `file_path` | | `RewindEvictedFile` | `file_path`, `reason` | -| `RewindOutcome` | `session`, `restored_count`, `deleted_count` | -| `RewindOutcome` | `failed_restore_count`, `failed_delete_count` | +| `RewindOutcome` | `session`, `restored_count`, `deleted_count`, `failed_restore_count`, `failed_delete_count` | ### Successor ownership @@ -1749,29 +1687,19 @@ root. | `Autonomy` | `OFF`, `LOW`, `MEDIUM`, `HIGH` | | `ReasoningEffort` | See supported values below | | `ToolCategory` | `READ`, `EDIT`, `EXECUTE`, `OTHER` | -| `ToolConfirmationType` | `EDIT`, `EXECUTE`, `CREATE`, `ASK_USER` | -| `ToolConfirmationType` | `EXIT_SPEC_MODE`, `APPLY_PATCH`, `MCP_TOOL` | -| `ToolConfirmationType` | `SANDBOX_VIOLATION`, `DROID_SHIELD_VIOLATION` | +| `ToolConfirmationType` | `EDIT`, `EXECUTE`, `CREATE`, `ASK_USER`, `EXIT_SPEC_MODE`, `APPLY_PATCH`, `MCP_TOOL`, `SANDBOX_VIOLATION`, `DROID_SHIELD_VIOLATION` | | `ToolConfirmationOutcome` | Permission outcomes offered by Droid | -| `WorkingState` | `IDLE`, `THINKING`, `STREAMING_ASSISTANT_MESSAGE` | -| `WorkingState` | `WAITING_FOR_TOOL_CONFIRMATION`, `EXECUTING_TOOL` | -| `WorkingState` | `COMPACTING_CONVERSATION` | +| `WorkingState` | `IDLE`, `THINKING`, `STREAMING_ASSISTANT_MESSAGE`, `WAITING_FOR_TOOL_CONFIRMATION`, `EXECUTING_TOOL`, `COMPACTING_CONVERSATION` | | `ContextAccuracy` | `EXACT`, `ESTIMATED` | | `McpServerType` | `STDIO`, `HTTP`, `SSE` | -| `McpServerStatus` | `CONNECTING`, `CONNECTED`, `DISCONNECTED` | -| `McpServerStatus` | `FAILED`, `DISABLED` | +| `McpServerStatus` | `CONNECTING`, `CONNECTED`, `DISCONNECTED`, `FAILED`, `DISABLED` | | `McpAuthOutcome` | `SUCCESS`, `CANCELLED`, `FAILED` | | `OAuthTokenEndpointAuthMethod` | `NONE`, `CLIENT_SECRET_BASIC`, `CLIENT_SECRET_POST` | -| `SessionPlatform` | `SLACK`, `WEB`, `API`, `SESSIONS_API`, `JIRA`, `LINEAR` | -| `SessionPlatform` | `MICROSOFT_TEAMS`, `READINESS_REMEDIATION`, `READINESS_EVALUATION` | -| `SessionPlatform` | `AUTOMATION`, `WIKI_GENERATION`, `WIKI_CI_SETUP`, `TUI` | -| `SessionPlatform` | `DESKTOP`, `ACP`, `UNKNOWN` | +| `SessionPlatform` | `SLACK`, `WEB`, `API`, `SESSIONS_API`, `JIRA`, `LINEAR`, `MICROSOFT_TEAMS`, `READINESS_REMEDIATION`, `READINESS_EVALUATION`, `AUTOMATION`, `WIKI_GENERATION`, `WIKI_CI_SETUP`, `TUI`, `DESKTOP`, `ACP`, `UNKNOWN` | | `SandboxOperation` | `READ`, `WRITE`, `NETWORK`, `TOOL` | | `SandboxViolationType` | `FILESYSTEM_READ`, `FILESYSTEM_WRITE`, `NETWORK`, `TOOL` | | `SandboxViolationReason` | `DENY_LIST`, `NOT_ALLOWED` | -| `ErrorType` | `CONNECTION_ERROR`, `PROTOCOL_ERROR`, `SESSION_ERROR` | -| `ErrorType` | `TIMEOUT_ERROR`, `DROID_CLIENT_ERROR`, `PROCESS_EXIT_ERROR` | -| `ErrorType` | `ERROR` | +| `ErrorType` | `CONNECTION_ERROR`, `PROTOCOL_ERROR`, `SESSION_ERROR`, `TIMEOUT_ERROR`, `DROID_CLIENT_ERROR`, `PROCESS_EXIT_ERROR`, `ERROR` | `ReasoningEffort` defines `NONE`, `DYNAMIC`, `OFF`, `MINIMAL`, `LOW`, `MEDIUM`, `HIGH`, `EXTRA_HIGH`, and `MAX`. Model and tool IDs remain strings. From 12cb8a1619253e524af99a14ae246635beae3b5c Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 10:39:47 -0700 Subject: [PATCH 12/30] docs: streamline the SDK reference intro and core contract Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 51 ++++++++++++------------------------ 1 file changed, 17 insertions(+), 34 deletions(-) diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index 86af1bb..c27ba25 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -1,16 +1,10 @@ -# Factory Droid SDK for Python, v5 API - -> Implemented public API for the Python SDK v5 line. - -The Python SDK follows the concepts and behavior of the Droid TypeScript SDK. -Python differences are limited to naming, typing, and async resource ownership. +# Droid SDK for Python Install the package as `droid-sdk` and import it as `droid_sdk`. ## Overview -The first release starts a local `droid` subprocess and exposes two ways to -run a turn: +The SDK runs a local `droid` subprocess and exposes two ways to run a turn: | Goal | API | | --- | --- | @@ -18,7 +12,8 @@ run a turn: | Run turns in an existing session | `session.stream(...)` | Use `Session` when prompts need shared history or session operations such as -interruption, compaction, or rewind. `Session` does not have a `run()` method. +interruption, compaction, or rewind. There is no `session.run()`; every +session turn goes through `stream()`. ## Install and authenticate @@ -26,12 +21,6 @@ interruption, compaction, or rewind. `Session` does not have a `run()` method. pip install droid-sdk ``` -In-process MCP tool servers (`droid_sdk.mcp`) need the `mcp` extra: - -```bash -pip install "droid-sdk[mcp]" -``` - Requirements: - Python 3.10 or later @@ -64,9 +53,9 @@ async def main() -> None: asyncio.run(main()) ``` -`run()` creates a persisted session, consumes one default stream, and closes -the process and resources it owns. The saved session remains resumable. -See [Result types](#result-types) for every terminal outcome. +`run()` starts a session, runs one turn, and closes everything it created. +The saved session remains resumable. See [Result types](#result-types) for +every terminal outcome. ### Continue a conversation @@ -137,15 +126,11 @@ A turn begins with `session.stream(prompt)` and ends when the stream yields a ### Results and exceptions -Droid outcomes are results: - -- `RunSuccess` -- `RunInterrupted` -- `RunFailure` - -Interrupted turns, execution failures, and structured-output failures do not -raise. Setup, transport, process, protocol, timeout, and cancellation failures -raise exceptions. +A turn's outcome is a value, not an exception: `RunSuccess`, +`RunInterrupted`, or `RunFailure`. Interrupted turns, execution failures, and +structured-output failures do not raise. Failures in the machinery around a +turn (setup, transport, process, protocol, timeout, and cancellation) raise +exceptions. ### Ownership @@ -159,9 +144,9 @@ raise exceptions. ### Typing -The package includes `py.typed`. Public unions narrow with `isinstance()`. -High-level value models are immutable dataclasses. `TraceContext` is a mutable -carrier so tracing providers can inject values. +The package includes `py.typed`, and the public API type-checks under strict +Pyright and mypy. Public unions narrow with `isinstance()`. High-level value +models are immutable dataclasses. | Call | Static return type | | --- | --- | @@ -172,9 +157,6 @@ carrier so tracing providers can inject values. | Partial `session.stream(...)` | `RunStream[T, StreamEvent[T]]` | | `stream.result` | `RunResult[T]` | -Pydantic provides typed structured-output adapters. JSON-RPC boundaries use -the protocol models. Strict Pyright, mypy, and type tests are release gates. - ## Models Model IDs are strings because availability depends on account and @@ -1542,7 +1524,8 @@ contents, raw process output, stack traces, and credentials. `attributes` is `Mapping[str, str | int | float | bool | None]`. Log levels are `"debug"`, `"info"`, `"warn"`, and `"error"`. Metric kinds are `"counter"` -and `"histogram"`. +and `"histogram"`. `TraceContext` is deliberately mutable so tracing providers +can inject values into it. ### Custom runtime From 78e33a860d4df1edef4917049cd38fd37d0fe868 Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 11:41:35 -0700 Subject: [PATCH 13/30] docs: tighten the models and sessions reference sections Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 48 ++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index c27ba25..40a1662 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -185,10 +185,13 @@ await session.update_settings( ) ``` +See [Update settings](#update-settings) for the full `update_settings()` +contract. + ### Configure mode-specific models ```python -from droid_sdk import Mode, Session, SessionConfig +from droid_sdk import Mode, ReasoningEffort, Session, SessionConfig config = SessionConfig( mode=Mode.SPEC, @@ -213,8 +216,8 @@ The primary model handles Auto turns. `spec_model` handles Spec turns. | `spec_model` | `str \| None` | `SessionConfig`, `update_settings()` | | `spec_reasoning_effort` | `ReasoningEffort \| None` | Same | -Model IDs are opaque strings. `None` uses the configured default. Setting a -nullable Spec field to `None` through `update_settings()` clears it. +`None` uses the configured default. Setting a Spec field to `None` through +`update_settings()` clears it. ## Sessions @@ -234,6 +237,9 @@ async with Session( handle(message) ``` +Configure behavior and attach handlers with `SessionConfig` and +`InteractionHandlers`: + ```python from droid_sdk import Autonomy, InteractionHandlers, SessionConfig @@ -267,11 +273,18 @@ async with Session.resume( pass ``` -Resume restores conversation history, working directory, title, and settings. -It can reattach interaction handlers, MCP servers, observability, transport, -the disabled-tool policy, built-in-skill policy, automatic permission -rejection, and source attribution. It does not accept a new working directory -or model. +Resume restores conversation history, working directory, title, and settings; +runtime concerns such as handlers and MCP servers must be attached again (see +the table below). It does not accept a new working directory or model. + +### What persists + +| Restored | Attach again | +| --- | --- | +| Conversation history | Interaction handlers | +| Working directory | Session-scoped MCP servers | +| Title | Observability sinks | +| Session settings | Custom transport | ### Open and close manually @@ -306,8 +319,8 @@ print(session.settings.model) print(session.settings.mode) ``` -These properties are read-only. The immutable settings snapshot updates when -Droid reports a settings change. +These properties are read-only. `settings` is an immutable snapshot, replaced +when Droid reports a settings change. ### Update settings @@ -373,11 +386,7 @@ for saved in await list_sessions(limit=10): print(saved.id, saved.title, saved.modified_at) ``` -List sessions across working directories: - -```python -sessions = await list_sessions(all_workspaces=True, limit=20) -``` +Pass `all_workspaces=True` to list sessions across working directories. `list_sessions()` reads local files without starting Droid. Results are newest first. Timestamps are timezone-aware. @@ -458,15 +467,6 @@ fields default to `None`: `delegation_session_id`, `team_id`, `channel`, `computer_id`. Required combinations are validated when converted to the wire protocol. -### What persists - -| Restored | Attach again | -| --- | --- | -| Conversation history | Interaction handlers | -| Working directory | Session-scoped MCP servers | -| Title | Observability sinks | -| Session settings | Custom transport | - ## Streaming and results Use top-level `run()` when only the result matters. Session turns always use From 2a3d349b8bcfcf4f107edf81897bb6a00cdfc9c7 Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 12:52:10 -0700 Subject: [PATCH 14/30] docs: clarify session handlers, resume, and source schemas Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 41 ++++++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index 40a1662..2f8cc5b 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -241,11 +241,23 @@ Configure behavior and attach handlers with `SessionConfig` and `InteractionHandlers`: ```python -from droid_sdk import Autonomy, InteractionHandlers, SessionConfig +from droid_sdk import ( + Autonomy, + InteractionHandlers, + PermissionRequest, + PermissionResponse, + SessionConfig, + ToolConfirmationOutcome, +) + + +def approve(request: PermissionRequest) -> PermissionResponse: + return request.respond(ToolConfirmationOutcome.PROCEED_ONCE) + config = SessionConfig( autonomy=Autonomy.LOW, - disabled_tools={"Execute"}, + disabled_tools={"Execute"}, # tool overrides are sets of tool IDs disable_builtin_skills=True, ) @@ -256,6 +268,10 @@ async with Session( ... ``` +Handlers are plain callables that inspect the request and choose an offered +outcome; see [Permissions and user input](#permissions-and-user-input) for +the full contract. + `SessionConfig` also accepts mode-specific models, MCP servers, tags, source attribution, `machine_id`, automatic permission rejection, and native-tool overrides. It does not expose a system-prompt API. @@ -273,6 +289,9 @@ async with Session.resume( pass ``` +Get a session ID from `session.id`, `result.session_id`, or +[`list_sessions()`](#list-saved-sessions). + Resume restores conversation history, working directory, title, and settings; runtime concerns such as handlers and MCP servers must be attached again (see the table below). It does not accept a new working directory or model. @@ -300,9 +319,9 @@ finally: await session.close() ``` -Repeated `open()` while open and repeated `close()` after closing are safe. -A closed session cannot be reopened. Calling an active method before `open()` -raises `SessionNotOpenError`. +`open()` and `close()` are idempotent, but a closed session cannot be +reopened. Calling an active method before `open()` raises +`SessionNotOpenError`. Concurrent `open()` calls share one startup attempt. If one waiter is cancelled, startup continues for the others. Cancelling the final waiter @@ -457,15 +476,9 @@ match the `update_settings()` table above. `on_notification(callback, type=None)` passes `Mapping[str, object]` to the callback and returns an unsubscribe function. -`SessionSource` requires `platform: SessionPlatform`; all remaining attribution -fields default to `None`: `delegation_session_id`, `team_id`, `channel`, -`thread_ts`, `user_id`, `automation_id`, `agent_session_id`, `issue_id`, -`issue_url`, `issue_identifier`, `organization_id`, `cloud_id`, `issue_key`, -`site_id`, `project_id`, `comment_id`, `task_id`, `tenant_id`, -`conversation_id`, `service_url`, `conversation_type`, `root_message_id`, -`channel_id`, `aad_object_id`, `report_id`, `repo_url`, `criterion_id`, and -`computer_id`. Required combinations are validated when converted to the -wire protocol. +`SessionSource` requires `platform: SessionPlatform`; every other attribution +field is optional and defaults to `None`. Required combinations are validated +when converted to the wire protocol. ## Streaming and results From 6ba05f2f147e458e843b759a28e5d0b84aefd1e0 Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 13:20:40 -0700 Subject: [PATCH 15/30] docs: clarify the streaming and results reference section Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index 2f8cc5b..990c7cb 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -595,6 +595,15 @@ With `include_partial_messages=True`, the stream yields every | `McpAuthRequired` | `server_name`, `auth_url`, `message`, `state` | | `McpAuthCompleted` | `server_name`, `outcome`, `message` | +`ToolProgress.update` is a `ToolProgressUpdate`: + +| Type | Fields | +| --- | --- | +| `ToolProgressUpdate` | `type`, `tool_name`, `status`, `details`, `text`, `error`, `timestamp`, `parameters`, `value_snippet`, `terminal_id`, `full_output`, `subagent_session_id` | + +`ToolProgressUpdate.type` is `"tool_call"`, `"tool_result"`, `"error"`, +`"status"`, or `"message"`. + Unknown high-level events are ignored. Use `session.on_notification()` when the application needs raw notifications. @@ -684,7 +693,7 @@ Reading `stream.result` before completion raises `StreamIncompleteError`. ### Result types -`RunResult[T]` has the same terminal states as the TypeScript SDK: +`RunResult[T]` is a union of three terminal states: ```python RunResult[T] = RunSuccess[T] | RunInterrupted[T] | RunFailure[T] @@ -700,7 +709,7 @@ RunResult[T] = RunSuccess[T] | RunInterrupted[T] | RunFailure[T] | Field | Type | Meaning | | --- | --- | --- | | `subtype` | `str` | Terminal state | -| `text` | `str` | Final committed assistant text, with delta fallback | +| `text` | `str` | Final assistant text; reconstructed from deltas if no complete message arrived | | `messages` | `tuple[Message, ...]` | Complete messages from the turn | | `usage` | `Usage \| None` | Per-turn token and credit usage | | `duration` | `timedelta` | Wall-clock duration | @@ -744,10 +753,6 @@ print(context.used, context.remaining, context.limit, context.accuracy) | --- | --- | | `Usage` | `input_tokens`, `output_tokens`, `cache_creation_tokens`, `cache_read_tokens`, `thinking_tokens`, `factory_credits` | | `ContextUsage` | `used`, `remaining`, `limit`, `accuracy`, `updated_at` | -| `ToolProgressUpdate` | `type`, `tool_name`, `status`, `details`, `text`, `error`, `timestamp`, `parameters`, `value_snippet`, `terminal_id`, `full_output`, `subagent_session_id` | - -`ToolProgressUpdate.type` is `"tool_call"`, `"tool_result"`, `"error"`, -`"status"`, or `"message"`. ### Failures and exceptions @@ -782,8 +787,7 @@ async with session.stream("Perform a long review.", timeout=60) as stream: handle(event) ``` -`timeout` is a Python spelling for the TypeScript per-turn abort signal. On -expiry, the SDK interrupts the turn and raises `RunTimeoutError`. +On expiry, the SDK interrupts the turn and raises `RunTimeoutError`. ### Interrupt a turn @@ -813,7 +817,7 @@ async with session.stream("Inspect every test.") as stream: Context exit interrupts unfinished work. A bare async iterator cannot guarantee immediate cleanup on `break`. `await stream.aclose()` explicitly interrupts and detaches an unfinished -stream; it is idempotent after release. +stream; it is idempotent. ## Inputs and outputs From f43eabbb83e157db5155908cd822159bcfa2ba44 Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 13:37:26 -0700 Subject: [PATCH 16/30] docs: clarify the inputs and outputs reference section Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index 990c7cb..9ed5386 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -823,7 +823,7 @@ stream; it is idempotent. ### Images and files -Message options mirror TypeScript's `images` and `files` fields: +Attach images and files to a turn with the `images` and `files` options: ```python from droid_sdk import Document, Image, run @@ -841,7 +841,7 @@ result = await run( ) ``` -The constructors produce the same base64 sources the TypeScript SDK accepts. +The constructors read local data and encode it for the turn. Supported image types are PNG, JPEG, GIF, and WebP; image URLs are unsupported. Invalid local input raises `InvalidAttachmentError` before the turn starts. Attachments are limited to `MAX_ATTACHMENT_BYTES` (5 MiB), and @@ -904,8 +904,8 @@ elif result.output_validation_error is not None: types raise `TypeError` before the turn starts. With `output=Review`, the return type is `RunResult[Review]`. -The adapter validates raw structured output when present. Missing or -Pydantic-invalid output leaves `output` as `None` and populates +When structured output arrives, the SDK validates it against the model. +Missing or invalid output leaves `output` as `None` and populates `output_validation_error`; it does not change Droid's terminal subtype. A successful turn can therefore have `output is None`. @@ -932,8 +932,7 @@ if result.output is not None: ``` `JsonSchema` accepts an object-shaped schema. Droid reports unsupported or -invalid schemas through the normal result subtype; the SDK does not invent a -separate local terminal state. +invalid schemas through the normal result subtype. ### Output contract @@ -943,8 +942,9 @@ separate local terminal state. | `type[BaseModel]` | `RunResult[Model]` | | `JsonSchema` | `RunResult[JsonObject]` | -`JsonSchema.schema` is `FrozenJsonObject`. Input mappings are validated as -finite JSON and recursively frozen. Raw schema output remains `JsonObject`. +`JsonSchema.schema` is `FrozenJsonObject`. Schema mappings must contain only +JSON-compatible values; the SDK validates this and freezes them recursively. +Raw schema output remains `JsonObject`. ```python JsonValue = ( From 5fe0732933b307f597ba7ad822b8d7a2077fd598 Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 15:10:00 -0700 Subject: [PATCH 17/30] docs: clarify the permissions and user input reference section Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index 9ed5386..c3f2cba 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -1020,10 +1020,9 @@ session = Session( ) ``` -`request.options` is authoritative. `respond()` accepts only an offered -`ToolConfirmationOutcome` and optional `comment` or `edited_spec_content`. -This preserves every TypeScript outcome, including exact-path persistence, -auto-run levels, MCP persistence, edited plans, and new-session handoff. +Droid decides which outcomes are on offer. `respond()` accepts only an +outcome listed in `request.options`, plus optional `comment` or +`edited_spec_content`. An absent handler, an invalid response, or a handler exception cancels the request. Handler failures appear as `ErrorEvent` values; they do not raise @@ -1049,8 +1048,7 @@ Cancel the questionnaire: return request.cancel() ``` -Question helpers copy the required question index and text. Answers remain -strings, matching the TypeScript wire contract. Without a handler, or when a +Answers are always strings on the wire. Without a handler, or when a handler fails or returns an invalid shape, the questionnaire is cancelled and the stream receives an `ErrorEvent`. @@ -1154,7 +1152,7 @@ config = SessionConfig( ) ``` -The four sets preserve TypeScript semantics: +Each of the four sets has a distinct role: - `additional_tools` adds IDs to the catalog. - `enabled_tools` enables otherwise available tools. From 6938009a42b6af7f46aadd3bcffea709f8667a2f Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 15:58:00 -0700 Subject: [PATCH 18/30] docs: clarify the tools and extensions reference section Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index c3f2cba..c690b99 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -1191,7 +1191,8 @@ for skill in skills.skills: print(skill.name, skill.enabled) ``` -`skills.project_available` preserves the TypeScript result metadata. +`skills.project_available` reports whether a project skill scope is +available; it is `None` when Droid does not report it. Enable or disable a skill: @@ -1255,12 +1256,10 @@ session. Attach in-process servers again when resuming. | `SdkMcpServer` | `name`, `version`, `tools` | | `ToolResponse` | `content`, `is_error`, `structured_content` | -`tool(name, description)` is a decorator. -`tool(name, description, function)` is the equivalent direct-call overload. -It accepts synchronous or asynchronous functions. Parameters and return -annotations form the input and output schemas. Object-shaped typed returns -are validated at invocation time, returned as structured content, and -advertised through the MCP `outputSchema` field. +`tool(name, description)` is a decorator; +`tool(name, description, function)` is the equivalent direct call. A return +annotation that describes an object is validated at call time, returned as +structured content, and advertised through the MCP `outputSchema` field. `create_sdk_mcp_server(name, tools, version="1.0.0")` returns `SdkMcpServer`. `SdkMcpServer.config` is the active `HttpMcpServerConfig` or `None`; @@ -1350,13 +1349,10 @@ methods do not accept a project-scope argument. ### Hooks -Hooks remain configured in `.factory/hooks.json`. Hook execution appears as -`HookExecution` values in the run stream. - -The Python SDK does not define a second programmatic hook system. -`HookExecution.status` is `"started"`, `"completed"`, or `"error"`. -An empty or missing `hookResults` list does not synthesize a phantom terminal -hook event. +There is no Python API for defining hooks; configure them in +`.factory/hooks.json`. Hook execution appears as `HookExecution` values in +the run stream. `HookExecution.status` is `"started"`, `"completed"`, or +`"error"`. ## Session lifecycle From 9611d7c6706b70456d7ab10284762daed71e1b78 Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 16:50:25 -0700 Subject: [PATCH 19/30] examples: drop the offline dry-run flag from runnable examples Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 19 ++++++------- examples/attachments.py | 43 ++++++++--------------------- examples/interactions.py | 11 ++------ examples/interactive_session.py | 15 ++-------- examples/one_shot.py | 11 ++------ examples/sdk_mcp.py | 14 ++-------- examples/session_operations.py | 15 ++-------- examples/structured_output_model.py | 11 ++------ 8 files changed, 33 insertions(+), 106 deletions(-) diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index c690b99..6b510d4 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -1754,22 +1754,21 @@ Run commands from the repository root: | Example | Command | Expected result | | --- | --- | --- | -| Attachments | `uv run python examples/attachments.py --run` | Live image, text, and PDF turn | +| Attachments | `uv run python examples/attachments.py` | Live image, text, and PDF turn | | Interaction helpers | `uv run python examples/interaction_helpers.py` | Offline typed responses | -| Interactions | `uv run python examples/interactions.py --run` | Live permission/question turn | -| Interactive session | `uv run python examples/interactive_session.py --run` | Two live turns sharing history | +| Interactions | `uv run python examples/interactions.py` | Live permission/question turn | +| Interactive session | `uv run python examples/interactive_session.py` | Two live turns sharing history | | Saved sessions | `uv run python examples/list_saved_sessions.py` | Local saved-session count | | Low-level session | `uv run python examples/low_level_session.py [--droid PATH] [--cwd PATH]` | Initialize and list tools | | Observability | `uv run python examples/observability.py` | Offline isolated sink counts | -| One-shot run | `uv run python examples/one_shot.py --run` | Live one-turn result | +| One-shot run | `uv run python examples/one_shot.py` | Live one-turn result | | Resume | `uv run python examples/resume_session.py --session-id ID` | Live resumed turn | -| SDK MCP | `uv run python examples/sdk_mcp.py --run` | Live in-process MCP result | -| Session operations | `uv run python examples/session_operations.py --run` | Live settings, discovery, fork, and compact | -| Structured output | `uv run python examples/structured_output_model.py --run` | Live validated model output | +| SDK MCP | `uv run python examples/sdk_mcp.py` | Live in-process MCP result | +| Session operations | `uv run python examples/session_operations.py` | Live settings, discovery, fork, and compact | +| Structured output | `uv run python examples/structured_output_model.py` | Live validated model output | -Omitting `--run` from the seven flagged examples performs their offline -self-test instead of a model call. Live examples require an authenticated -local Droid CLI or `FACTORY_API_KEY`; every model call uses a finite timeout. +Live examples require an authenticated local Droid CLI or `FACTORY_API_KEY`; +every model call uses a finite timeout. ## Known limitations diff --git a/examples/attachments.py b/examples/attachments.py index 319a7a0..73a065e 100644 --- a/examples/attachments.py +++ b/examples/attachments.py @@ -1,20 +1,13 @@ -"""Load local attachments without starting Droid.""" +"""Send local image and document attachments in one turn.""" from __future__ import annotations -import argparse import asyncio import base64 import tempfile from pathlib import Path -from droid_sdk import ( - Document, - Image, - PdfDocumentSource, - TextDocumentSource, - run, -) +from droid_sdk import Document, Image, run def minimal_pdf() -> bytes: @@ -54,7 +47,7 @@ def minimal_pdf() -> bytes: return bytes(data) -async def main(run_turn: bool = False) -> None: +async def main() -> None: png = base64.b64decode( "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAQ0lEQVR4AcXB" "AQEAAAiDMKR/5xuD7QYjJDGJSUxiEpOYxCQmMYlJTGISk5jEJCYxiUlMYhKT" @@ -69,28 +62,14 @@ async def main(run_turn: bool = False) -> None: pdf_path.write_bytes(minimal_pdf()) image_path.write_bytes(png) - image = Image.from_path(image_path) - text = Document.from_path(text_path) - pdf = Document.from_path(pdf_path) - - assert isinstance(text.source, TextDocumentSource) - assert isinstance(pdf.source, PdfDocumentSource) - if run_turn: - result = await run( - "Describe the attached red square and summarize both files.", - images=[image], - files=[text, pdf], - timeout=60, - ) - assert result.success, result.error - assert result.text - print(result.text) - print(f"image: {image.source.media_type}") - print(f"text: {text.source.name} ({text.source.mime})") - print(f"pdf: {pdf.source.name} ({len(pdf.source.data)} base64 chars)") + result = await run( + "Describe the attached red square and summarize both files.", + images=[Image.from_path(image_path)], + files=[Document.from_path(text_path), Document.from_path(pdf_path)], + timeout=60, + ) + print(result.text) if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--run", action="store_true") - asyncio.run(main(parser.parse_args().run)) + asyncio.run(main()) diff --git a/examples/interactions.py b/examples/interactions.py index 78be06e..f08a786 100644 --- a/examples/interactions.py +++ b/examples/interactions.py @@ -2,7 +2,6 @@ from __future__ import annotations -import argparse import asyncio from droid_sdk import ( @@ -28,15 +27,11 @@ async def question(request: QuestionRequest) -> QuestionResponse: return request.submit(answers) -async def main(run_turn: bool = False) -> None: +async def main() -> None: handlers = InteractionHandlers( on_permission=permission, on_question=question, ) - if not run_turn: - assert handlers.on_permission is permission - print("self-test: interaction handlers ready") - return async with Session(interactions=handlers) as session: async with session.stream( "Ask one multiple-choice question, then stop.", @@ -48,6 +43,4 @@ async def main(run_turn: bool = False) -> None: if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--run", action="store_true") - asyncio.run(main(parser.parse_args().run)) + asyncio.run(main()) diff --git a/examples/interactive_session.py b/examples/interactive_session.py index ef39ac6..eb0319a 100644 --- a/examples/interactive_session.py +++ b/examples/interactive_session.py @@ -2,19 +2,12 @@ from __future__ import annotations -import argparse import asyncio from droid_sdk import AssistantMessage, Session, TextDelta -async def main(run_turns: bool = False) -> None: - if not run_turns: - session = Session() - assert session.cwd is not None - print("self-test: lazy session configured") - return - +async def main() -> None: async with Session() as session: async with session.stream( "Reply with one short sentence.", timeout=60 @@ -22,7 +15,6 @@ async def main(run_turns: bool = False) -> None: async for event in first: if isinstance(event, AssistantMessage): print(event.text) - assert first.result.session_id == session.id async with session.stream( "Reply with three words.", @@ -33,10 +25,7 @@ async def main(run_turns: bool = False) -> None: if isinstance(event, TextDelta): print(event.text, end="", flush=True) print() - assert second.result.turn_count == 1 if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--run", action="store_true") - asyncio.run(main(parser.parse_args().run)) + asyncio.run(main()) diff --git a/examples/one_shot.py b/examples/one_shot.py index 454c559..291c5a7 100644 --- a/examples/one_shot.py +++ b/examples/one_shot.py @@ -2,22 +2,15 @@ from __future__ import annotations -import argparse import asyncio from droid_sdk import run -async def main(run_turn: bool = False) -> None: - if not run_turn: - print("self-test: import and event loop ready") - return +async def main() -> None: result = await run("Reply with exactly: SDK ready", timeout=60) print(result.text) - assert result.session_id if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--run", action="store_true") - asyncio.run(main(parser.parse_args().run)) + asyncio.run(main()) diff --git a/examples/sdk_mcp.py b/examples/sdk_mcp.py index 209e2c0..367b691 100644 --- a/examples/sdk_mcp.py +++ b/examples/sdk_mcp.py @@ -2,7 +2,6 @@ from __future__ import annotations -import argparse import asyncio from droid_sdk import ( @@ -28,15 +27,8 @@ def allow_example_tool(request: PermissionRequest) -> PermissionResponse: return request.respond(ToolConfirmationOutcome.PROCEED_ONCE) -async def main(run_turn: bool = False) -> None: +async def main() -> None: server = create_sdk_mcp_server("example-tools", [lookup_owner]) - if not run_turn: - config = await server.start() - assert config.url.startswith("http://127.0.0.1:") - await server.close() - assert server.config is None - print("self-test: MCP started and stopped") - return async with Session( config=SessionConfig(mcp_servers=[server]), interactions=InteractionHandlers(on_permission=allow_example_tool), @@ -51,6 +43,4 @@ async def main(run_turn: bool = False) -> None: if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--run", action="store_true") - asyncio.run(main(parser.parse_args().run)) + asyncio.run(main()) diff --git a/examples/session_operations.py b/examples/session_operations.py index c569ab7..58d3054 100644 --- a/examples/session_operations.py +++ b/examples/session_operations.py @@ -2,20 +2,13 @@ from __future__ import annotations -import argparse import asyncio import contextlib -from droid_sdk import Autonomy, Mode, Session, SessionReplacedError +from droid_sdk import Autonomy, Session, SessionReplacedError -async def main(run_operations: bool = False) -> None: - if not run_operations: - assert Mode.AUTO.value == "auto" - assert Autonomy.LOW.value == "low" - print("self-test: operation types ready") - return - +async def main() -> None: session = Session() await session.open() try: @@ -45,6 +38,4 @@ async def main(run_operations: bool = False) -> None: if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--run", action="store_true") - asyncio.run(main(parser.parse_args().run)) + asyncio.run(main()) diff --git a/examples/structured_output_model.py b/examples/structured_output_model.py index d5aa697..a066fff 100644 --- a/examples/structured_output_model.py +++ b/examples/structured_output_model.py @@ -2,7 +2,6 @@ from __future__ import annotations -import argparse import asyncio from typing import Literal @@ -21,11 +20,7 @@ class Review(BaseModel): findings: list[Finding] -async def main(run_turn: bool = False) -> None: - if not run_turn: - assert Review.model_json_schema()["type"] == "object" - print("self-test: output schema ready") - return +async def main() -> None: result = await run( "Return a short repository summary and zero or more findings.", output=Review, @@ -36,6 +31,4 @@ async def main(run_turn: bool = False) -> None: if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--run", action="store_true") - asyncio.run(main(parser.parse_args().run)) + asyncio.run(main()) From dfe6aab8101773a8195ea3013a9a21a46aa72824 Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 16:50:43 -0700 Subject: [PATCH 20/30] examples: add a live tour of every stream event type Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 1 + examples/stream_events.py | 79 ++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 examples/stream_events.py diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index 6b510d4..e7b9ce8 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -1765,6 +1765,7 @@ Run commands from the repository root: | Resume | `uv run python examples/resume_session.py --session-id ID` | Live resumed turn | | SDK MCP | `uv run python examples/sdk_mcp.py` | Live in-process MCP result | | Session operations | `uv run python examples/session_operations.py` | Live settings, discovery, fork, and compact | +| Stream events | `uv run python examples/stream_events.py` | Live tour of every stream event type | | Structured output | `uv run python examples/structured_output_model.py` | Live validated model output | Live examples require an authenticated local Droid CLI or `FACTORY_API_KEY`; diff --git a/examples/stream_events.py b/examples/stream_events.py new file mode 100644 index 0000000..2c11846 --- /dev/null +++ b/examples/stream_events.py @@ -0,0 +1,79 @@ +"""Stream every kind of turn activity: text, thinking, tools, permissions, hooks.""" + +from __future__ import annotations + +import asyncio + +from droid_sdk import ( + Autonomy, + HookExecution, + InteractionHandlers, + PermissionRequest, + PermissionResolved, + PermissionResponse, + Session, + SessionConfig, + TextComplete, + TextDelta, + ThinkingComplete, + ThinkingDelta, + TokenUsageUpdate, + ToolCall, + ToolCallDelta, + ToolConfirmationOutcome, + ToolProgress, + ToolResult, + WorkingStateChanged, +) + + +def approve_once(request: PermissionRequest) -> PermissionResponse: + actions = ", ".join(type(action).__name__ for action in request.actions) + print(f"\n[permission requested] {actions}") + return request.respond(ToolConfirmationOutcome.PROCEED_ONCE) + + +async def main() -> None: + session = Session( + config=SessionConfig(autonomy=Autonomy.LOW), # every tool call asks first + interactions=InteractionHandlers(on_permission=approve_once), + ) + async with session: + async with session.stream( + "Run `touch /tmp/droid-stream-demo.txt`, then summarize what you did.", + include_partial_messages=True, + timeout=120, + ) as stream: + async for event in stream: + match event: + case TextDelta(text=text) | ThinkingDelta(text=text): + print(text, end="", flush=True) + case TextComplete(): + print() + case ThinkingComplete(): + print("\n[thinking done]") + case ToolCallDelta(tool_use=tool_use): + print(f"[tool call delta] {tool_use.name}") + case ToolCall(name=name, input=arguments): + print(f"[tool call] {name} {dict(arguments)}") + case ToolProgress(tool_name=name, update=update): + print(f"[tool progress] {name}: {update.type}") + case ToolResult(tool_name=name, is_error=is_error): + print(f"[tool result] {name} error={is_error}") + case PermissionResolved(selected_option=option): + print(f"[permission resolved] {option.value}") + case HookExecution(hook_id=hook_id, status=status): + print(f"[hook] {hook_id}: {status}") + case WorkingStateChanged(state=state): + print(f"[state] {state.value}") + case TokenUsageUpdate(output_tokens=output_tokens): + print(f"[usage] {output_tokens} output tokens") + case _: + print(f"[{type(event).__name__}]") + + result = stream.result + print(f"[done] {result.subtype} in {result.duration.total_seconds():.1f}s") + + +if __name__ == "__main__": + asyncio.run(main()) From 79ca034f741a1c70c8ff75d3318f8453eab274a9 Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 16:51:26 -0700 Subject: [PATCH 21/30] docs: clarify the session lifecycle and modes reference sections Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index e7b9ce8..6e6af33 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -206,6 +206,8 @@ async with Session(model="auto", config=config) as session: ``` The primary model handles Auto turns. `spec_model` handles Spec turns. +Switch modes on a live session with `enter_spec()` and `leave_spec()`; see +[Modes](#modes). ### Model configuration contract @@ -1075,8 +1077,9 @@ QuestionHandler = Callable[ | Type | Fields | | --- | --- | | `InteractionHandlers` | `on_permission`, `on_question` | -| `PermissionRequest` | `actions`, `options`, `associated_session_ids` | +| `PermissionRequest` | `actions`, `options`, `associated_session_ids`, `plan` | | `PermissionOption` | `label`, `value` | +| `Plan` | `text`, `title` | | `PermissionResponse` | `selected_option`, `comment`, `edited_spec_content` | | `QuestionRequest` | `tool_call_id`, `questions` | | `Question` | `index`, `topic`, `question`, `options`, `multi_select` | @@ -1356,11 +1359,15 @@ the run stream. `HookExecution.status` is `"started"`, `"completed"`, or ## Session lifecycle -Fork, compact, and rewind create successor sessions. They return an opened -`Session` that owns the existing Droid connection. +Fork, compact, and rewind create successor sessions. The successor is an +opened `Session` that takes over the existing Droid connection; `fork()` +returns it directly, while `compact()` and `rewind()` return it on their +outcome objects. ### Fork +Fork copies the conversation into a new session and continues there. + ```python fork = await session.fork( title="Alternative approach", @@ -1375,6 +1382,9 @@ async with fork: ### Compact +Compaction summarizes older conversation history to free context-window +space. + ```python outcome = await session.compact( instructions="Keep decisions and unresolved failures." @@ -1386,6 +1396,9 @@ async with outcome.session as compacted: ### Rewind +Rewind returns the conversation to an earlier message and can restore or +delete files changed since. + ```python info = await session.rewind_info(message_id) @@ -1431,7 +1444,7 @@ After a successful replacement: - active methods on the source raise `SessionReplacedError` - closing the source is a no-op -Do not replace a session while it has an active turn. +Replacing a session with an active turn raises `SessionBusyError`. Only one replacement may run at a time. `open()` and another replacement raise `SessionBusyError` while replacement is active. `close()` racing a From cd2a80d7faf7221587a9bb7d9a97daf7d1fb3a84 Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 16:58:12 -0700 Subject: [PATCH 22/30] docs: clarify the operations section and drop Mission mentions Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- README.md | 4 +--- docs/python-sdk-reference.md | 22 ++++++++++++---------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 2aeb9ae..8ffb2c3 100644 --- a/README.md +++ b/README.md @@ -171,9 +171,7 @@ See the complete contract in Applications that own JSON-RPC lifecycle can import `DroidClient`, `ProcessTransport`, transport protocols, and wire schemas from `droid_sdk.low_level`. Legacy query/client/transport/event aliases are not -exported at package root. Mission and daemon APIs are excluded from the -package root; Mission wire schemas remain available through -`droid_sdk.low_level`. +exported at package root. ## Limitations diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index 6e6af33..c116ab4 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -1517,12 +1517,16 @@ Entering or leaving Spec mode only changes settings. Plan approval is an ### Observability ```python -from droid_sdk import Runtime -from droid_sdk.observability import Observability +from droid_sdk import Runtime, run +from droid_sdk.observability import LogEvent, Observability -runtime = Runtime( - observability=Observability(logger=logger, metrics=metrics), -) + +class PrintLogger: + def log(self, event: LogEvent) -> None: + print(event.level, event.name, event.message) + + +runtime = Runtime(observability=Observability(logger=PrintLogger())) result = await run("Check repository status.", runtime=runtime) ``` @@ -1581,7 +1585,8 @@ extend the current process environment when the SDK starts Droid. ### Low-level API -Applications that own JSON-RPC or transport lifecycle may import: +Applications that manage the JSON-RPC protocol or the transport themselves +may import: ```python from droid_sdk.low_level import DroidClient, ProcessTransport @@ -1605,10 +1610,7 @@ high-level types documented above provide Python naming and lifecycle guarantees. `droid_sdk.low_level.__all__` is the authoritative machine-readable API -index. It consists of the constants and runtime types shown above plus every -name in `droid_sdk.schemas.__all__`. This includes Mission wire schemas for -protocol compatibility; Mission and daemon APIs are not exposed at package -root. +index: the types above plus every name in `droid_sdk.schemas.__all__`. ## API index From ee8d3899935d6ebe4ff7ce5ba72b7a985ce1d887 Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 17:02:36 -0700 Subject: [PATCH 23/30] docs: remove the low-level API from the public documentation Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- README.md | 7 ------- docs/python-sdk-reference.md | 30 ------------------------------ 2 files changed, 37 deletions(-) diff --git a/README.md b/README.md index 8ffb2c3..ed930a5 100644 --- a/README.md +++ b/README.md @@ -166,13 +166,6 @@ The complete command matrix is in See the complete contract in [`docs/python-sdk-reference.md`](docs/python-sdk-reference.md). -## Low-level escape hatch - -Applications that own JSON-RPC lifecycle can import `DroidClient`, -`ProcessTransport`, transport protocols, and wire schemas from -`droid_sdk.low_level`. Legacy query/client/transport/event aliases are not -exported at package root. - ## Limitations - Local `droid` subprocesses only diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index c116ab4..6420c0a 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -1583,35 +1583,6 @@ extend the current process environment when the SDK starts Droid. `Runtime.uses_supplied_transport` is `True` when `transport` is not `None`. -### Low-level API - -Applications that manage the JSON-RPC protocol or the transport themselves -may import: - -```python -from droid_sdk.low_level import DroidClient, ProcessTransport -``` - -The low-level package exposes protocol models and request methods. It does not -provide high-level ordering or cleanup guarantees. Prefer -`session.on_notification()` when an existing session needs raw notifications. - -| Type | Purpose | -| --- | --- | -| `DroidClient` | Typed JSON-RPC requests, callbacks, and notifications | -| `ProcessTransport` | Start and connect to a local Droid process | -| `Transport` | Async framed-message transport protocol | -| Protocol request models | Typed request parameters | -| Protocol response models | Success and failure envelopes | -| Protocol notification models | Raw session notifications | - -Low-level request and response models preserve protocol field names. The -high-level types documented above provide Python naming and lifecycle -guarantees. - -`droid_sdk.low_level.__all__` is the authoritative machine-readable API -index: the types above plus every name in `droid_sdk.schemas.__all__`. - ## API index ### Root constants and supporting types @@ -1774,7 +1745,6 @@ Run commands from the repository root: | Interactions | `uv run python examples/interactions.py` | Live permission/question turn | | Interactive session | `uv run python examples/interactive_session.py` | Two live turns sharing history | | Saved sessions | `uv run python examples/list_saved_sessions.py` | Local saved-session count | -| Low-level session | `uv run python examples/low_level_session.py [--droid PATH] [--cwd PATH]` | Initialize and list tools | | Observability | `uv run python examples/observability.py` | Offline isolated sink counts | | One-shot run | `uv run python examples/one_shot.py` | Live one-turn result | | Resume | `uv run python examples/resume_session.py --session-id ID` | Live resumed turn | From fc9af1ecd95bb71ff4f2238286107817ac8e0c96 Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 17:08:07 -0700 Subject: [PATCH 24/30] docs: remove custom transport from the public surface Drop transport mentions from the docs and delete the low-level session example with its test. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- README.md | 5 +- docs/python-sdk-reference.md | 15 ++--- examples/low_level_session.py | 47 --------------- tests/test_low_level_example.py | 100 -------------------------------- 4 files changed, 7 insertions(+), 160 deletions(-) delete mode 100644 examples/low_level_session.py delete mode 100644 tests/test_low_level_example.py diff --git a/README.md b/README.md index ed930a5..31019c9 100644 --- a/README.md +++ b/README.md @@ -150,9 +150,8 @@ config = SessionConfig(mcp_servers=[server]) The session starts and stops SDK MCP servers. Every start uses an ephemeral port and fresh bearer token. -`Runtime` configures executable, extra args, environment, transport, and -privacy-safe observability. A caller transport must already be connected, -takes precedence over process options, and is closed by the session. +`Runtime` configures the executable, extra args, environment, and +privacy-safe observability. ## Saved sessions and examples diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index 6420c0a..d6fa908 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -129,7 +129,7 @@ A turn begins with `session.stream(prompt)` and ends when the stream yields a A turn's outcome is a value, not an exception: `RunSuccess`, `RunInterrupted`, or `RunFailure`. Interrupted turns, execution failures, and structured-output failures do not raise. Failures in the machinery around a -turn (setup, transport, process, protocol, timeout, and cancellation) raise +turn (setup, connection, process, protocol, timeout, and cancellation) raise exceptions. ### Ownership @@ -140,7 +140,6 @@ exceptions. | `Session` used with `async with` | The context manager | | Manually opened `Session` | The caller | | In-process MCP servers | The session | -| Caller-provided transport | The session | ### Typing @@ -305,7 +304,7 @@ the table below). It does not accept a new working directory or model. | Conversation history | Interaction handlers | | Working directory | Session-scoped MCP servers | | Title | Observability sinks | -| Session settings | Custom transport | +| Session settings | | ### Open and close manually @@ -1557,7 +1556,7 @@ can inject values into it. ### Custom runtime -`Runtime` holds process and transport configuration: +`Runtime` holds process configuration: ```python runtime = Runtime( @@ -1567,9 +1566,8 @@ runtime = Runtime( ) ``` -A supplied transport must already be connected. It takes precedence over -process and API-key options, and the session closes it. Environment entries -extend the current process environment when the SDK starts Droid. +Environment entries extend the current process environment when the SDK +starts Droid. #### Runtime schema @@ -1578,11 +1576,8 @@ extend the current process environment when the SDK starts Droid. | `executable` | `str \| Path \| None` | | `args` | `Sequence[str]` | | `env` | `Mapping[str, str]` | -| `transport` | `Transport \| None` | | `observability` | `Observability \| None` | -`Runtime.uses_supplied_transport` is `True` when `transport` is not `None`. - ## API index ### Root constants and supporting types diff --git a/examples/low_level_session.py b/examples/low_level_session.py deleted file mode 100644 index af07e80..0000000 --- a/examples/low_level_session.py +++ /dev/null @@ -1,47 +0,0 @@ -"""Initialize a local Droid session and list its available tools.""" - -from __future__ import annotations - -import argparse -import asyncio -import os -import socket -from pathlib import Path - -from droid_sdk.low_level import DroidClient, ListToolsResult - - -async def run_session( - client: DroidClient, - *, - cwd: str, - machine_id: str, -) -> ListToolsResult: - """Run the example flow with a caller-provided low-level client.""" - await client.connect() - try: - initialized = await client.initialize_session( - machine_id=machine_id, - cwd=cwd, - ) - tools = await client.list_tools() - print(f"Session: {initialized.session_id}") - print(f"Available tools: {len(tools.tools)}") - return tools - finally: - await client.close() - - -async def main() -> None: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--droid", default="droid", help="Path to the Droid CLI") - parser.add_argument("--cwd", default=os.getcwd(), help="Session working directory") - args = parser.parse_args() - - cwd = str(Path(args.cwd).resolve()) - client = DroidClient(exec_path=args.droid, cwd=cwd) - await run_session(client, cwd=cwd, machine_id=socket.gethostname()) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/tests/test_low_level_example.py b/tests/test_low_level_example.py deleted file mode 100644 index d569a5e..0000000 --- a/tests/test_low_level_example.py +++ /dev/null @@ -1,100 +0,0 @@ -"""Offline test for the public low-level example.""" - -from __future__ import annotations - -import asyncio -import json -from typing import TYPE_CHECKING, Any - -import pytest -from examples.low_level_session import run_session - -from droid_sdk.low_level import DroidClient, ListToolsResult - -if TYPE_CHECKING: - from collections.abc import AsyncIterator - - -_STOP = object() - - -class ExampleTransport: - """Deterministic in-memory responder for the example flow.""" - - def __init__(self) -> None: - self._connected = False - self._queue: asyncio.Queue[dict[str, Any] | object] = asyncio.Queue() - self.methods: list[str] = [] - - @property - def is_connected(self) -> bool: - return self._connected - - async def connect(self) -> None: - self._connected = True - - async def send(self, message: str) -> None: - request = json.loads(message) - method = request["method"] - self.methods.append(method) - if method == "droid.initialize_session": - result: dict[str, Any] = { - "sessionId": "example-session", - "session": {"messages": []}, - "settings": { - "modelId": "example-model", - "reasoningEffort": "medium", - }, - } - elif method == "droid.list_tools": - result = { - "tools": [ - { - "id": "read", - "displayName": "Read", - "defaultAllowed": True, - "currentlyAllowed": True, - } - ] - } - else: - raise AssertionError(f"Unexpected method: {method}") - self._queue.put_nowait( - { - "jsonrpc": "2.0", - "factoryApiVersion": "1.0.0", - "factoryProtocolVersion": "1.1.0", - "type": "response", - "id": request["id"], - "result": result, - } - ) - - async def read_messages(self) -> AsyncIterator[dict[str, Any]]: - while True: - message = await self._queue.get() - if message is _STOP: - return - assert isinstance(message, dict) - yield message - - async def close(self) -> None: - self._connected = False - self._queue.put_nowait(_STOP) - - -@pytest.mark.asyncio -async def test_low_level_example_flow(capsys: pytest.CaptureFixture[str]) -> None: - transport = ExampleTransport() - result = await run_session( - DroidClient(transport=transport), - cwd="/tmp/example", - machine_id="test-machine", - ) - - assert isinstance(result, ListToolsResult) - assert result.tools[0].id == "read" - assert transport.methods == ["droid.initialize_session", "droid.list_tools"] - output = capsys.readouterr().out - assert "Session: example-session" in output - assert "Available tools: 1" in output From f84105333b2453ccd59830efead2c20ed66ccc88 Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 17:20:05 -0700 Subject: [PATCH 25/30] docs: tighten the API index and limitations sections Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index d6fa908..0064d77 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -1677,9 +1677,10 @@ starts Droid. | `ErrorType` | `CONNECTION_ERROR`, `PROTOCOL_ERROR`, `SESSION_ERROR`, `TIMEOUT_ERROR`, `DROID_CLIENT_ERROR`, `PROCESS_EXIT_ERROR`, `ERROR` | `ReasoningEffort` defines `NONE`, `DYNAMIC`, `OFF`, `MINIMAL`, `LOW`, -`MEDIUM`, `HIGH`, `EXTRA_HIGH`, and `MAX`. Model and tool IDs remain strings. +`MEDIUM`, `HIGH`, `EXTRA_HIGH`, and `MAX`. Model and tool IDs are plain +strings, not enums. -Additional root enum wire values are: +On the wire, these enums use the following values: ```text ToolCategory: read, edit, execute, other @@ -1705,7 +1706,7 @@ All SDK-defined exceptions derive from `DroidError`. Python built-ins and | `StreamIncompleteError` | A stream result was read before completion | | `InvalidAttachmentError` | A local attachment was invalid | | `SessionNotOpenError` | An operation required an opened session | -| `SessionBusyError` | The session already had an active turn | +| `SessionBusyError` | The session already had an active turn or replacement in progress | | `SessionClosedError` | The session was closed | | `SessionReplacedError` | A successor retired the source session | | `SessionReplacementError` | Successor load or source restore failed | @@ -1715,8 +1716,7 @@ All SDK-defined exceptions derive from `DroidError`. Python built-ins and | `DroidProcessError` | The Droid process exited unexpectedly | | `DroidProtocolError` | Protocol negotiation or validation failed | -`SessionError` is the compatibility base exported by `droid_sdk.errors`; it -is intentionally absent from the package root. Exception metadata is public: +Exception constructor metadata is public: | Exception | Additional constructor fields | | --- | --- | @@ -1753,7 +1753,7 @@ every model call uses a finite timeout. ## Known limitations -- The high-level API runs local Droid subprocess sessions only. +- The SDK runs local Droid subprocess sessions only. - The API is asyncio-only. - Hooks are configured through Droid files, not Python callbacks. - Image URLs are not supported by the local runtime. From 7870f0486ca2bb00ad4a29b96722ecd9579bde91 Mon Sep 17 00:00:00 2001 From: User Date: Wed, 12 Aug 2026 23:50:57 -0700 Subject: [PATCH 26/30] examples: raise live-turn timeouts to 180 seconds Multi-step turns can exceed 60 seconds locally when the model makes several tool calls. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- examples/attachments.py | 2 +- examples/session_operations.py | 2 +- examples/structured_output_model.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/attachments.py b/examples/attachments.py index 73a065e..c0967f7 100644 --- a/examples/attachments.py +++ b/examples/attachments.py @@ -66,7 +66,7 @@ async def main() -> None: "Describe the attached red square and summarize both files.", images=[Image.from_path(image_path)], files=[Document.from_path(text_path), Document.from_path(pdf_path)], - timeout=60, + timeout=180, ) print(result.text) diff --git a/examples/session_operations.py b/examples/session_operations.py index 58d3054..ef07393 100644 --- a/examples/session_operations.py +++ b/examples/session_operations.py @@ -25,7 +25,7 @@ async def main() -> None: async with successor: async with successor.stream( "Reply with exactly: ready to compact", - timeout=60, + timeout=180, ) as stream: async for _ in stream: pass diff --git a/examples/structured_output_model.py b/examples/structured_output_model.py index a066fff..10328df 100644 --- a/examples/structured_output_model.py +++ b/examples/structured_output_model.py @@ -24,7 +24,7 @@ async def main() -> None: result = await run( "Return a short repository summary and zero or more findings.", output=Review, - timeout=60, + timeout=180, ) assert result.output is not None, result.output_validation_error print(result.output.summary) From f7139bdfeb7af5b02155d5a0110adb964d0a4670 Mon Sep 17 00:00:00 2001 From: User Date: Thu, 13 Aug 2026 00:06:44 -0700 Subject: [PATCH 27/30] fix: accept any iterable for tool overrides and forward the mime hint Tool overrides (additional_tools, enabled_tools, disabled_tools, restrict_tools) now accept any Iterable[str] instead of requiring a set, and raise TypeError on a bare string before anything reaches the wire, since frozenset("Execute") would silently become single characters. The settings snapshots (SessionSettings, SessionSettingsUpdate) are now precisely typed as frozenset[str]. Document.from_text(mime=...) was stored but never sent; the wire schema has the field, so the converter now forwards it. Also gate the example-execution test behind DROID_LIVE_TESTS: since the offline dry-run flag was removed, it runs live turns and cannot finish inside a 30-second cap. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 27 ++++++------ src/droid_sdk/_high_level/_convert.py | 15 +++++-- .../_high_level/_session_operations.py | 34 ++++++++++----- src/droid_sdk/_high_level/config.py | 41 ++++++++++++------- src/droid_sdk/_high_level/extensions.py | 13 +++--- src/droid_sdk/_high_level/session.py | 6 ++- tests/test_v5_public_models.py | 30 +++++++++++++- tests/test_v5_session.py | 19 ++++++++- tests/typing/positive.py | 6 +++ 9 files changed, 138 insertions(+), 53 deletions(-) diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index 0064d77..3e8626a 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -258,7 +258,7 @@ def approve(request: PermissionRequest) -> PermissionResponse: config = SessionConfig( autonomy=Autonomy.LOW, - disabled_tools={"Execute"}, # tool overrides are sets of tool IDs + disabled_tools={"Execute"}, # any iterable of tool IDs works here disable_builtin_skills=True, ) @@ -369,10 +369,10 @@ clear them. | `tags` | `Sequence[SessionTag] \| None` | | `compaction_token_limit` | `int \| None` | | `compaction_threshold_check_enabled` | `bool \| None` | -| `additional_tools` | `set[str] \| frozenset[str] \| None` | -| `enabled_tools` | `set[str] \| frozenset[str] \| None` | -| `disabled_tools` | `set[str] \| frozenset[str] \| None` | -| `restrict_tools` | `set[str] \| frozenset[str] \| None` | +| `additional_tools` | `Iterable[str] \| None` | +| `enabled_tools` | `Iterable[str] \| None` | +| `disabled_tools` | `Iterable[str] \| None` | +| `restrict_tools` | `Iterable[str] \| None` | It returns `UpdateSettingsResult`. The result currently has no fields. @@ -439,10 +439,10 @@ first. Timestamps are timezone-aware. | `session_source` | `SessionSource \| None` | | `auto_reject_permission_requests` | `bool \| None` | | `disable_builtin_skills` | `bool \| None` | -| `additional_tools` | `set[str] \| frozenset[str] \| None` | -| `enabled_tools` | `set[str] \| frozenset[str] \| None` | -| `disabled_tools` | `set[str] \| frozenset[str] \| None` | -| `restrict_tools` | `set[str] \| frozenset[str] \| None` | +| `additional_tools` | `Iterable[str] \| None` | +| `enabled_tools` | `Iterable[str] \| None` | +| `disabled_tools` | `Iterable[str] \| None` | +| `restrict_tools` | `Iterable[str] \| None` | `Session.resume(session_id, ...)` accepts only values that can be reattached: @@ -453,7 +453,7 @@ first. Timestamps are timezone-aware. | `mcp_servers` | `Sequence[McpServerConfig]` | | `runtime` | `Runtime \| None` | | `api_key` | `str \| None` | -| `disabled_tools` | `set[str] \| frozenset[str] \| None` | +| `disabled_tools` | `Iterable[str] \| None` | | `auto_reject_permission_requests` | `bool \| None` | | `disable_builtin_skills` | `bool \| None` | | `session_source` | `SessionSource \| None` | @@ -867,8 +867,8 @@ PDFs to `MAX_PDF_ATTACHMENT_BYTES` (3 MiB). | `Document.from_bytes(data, name=...)` | `Document` | `images` accepts `Sequence[Image]`. `files` accepts `Sequence[Document]`. -Wire payloads use canonical `mediaType` fields. The high-level `mime` hint on -text documents is not forwarded as an extra protocol field. +Wire payloads use canonical `mediaType` fields. The optional `mime` hint on +text documents is forwarded with the document. ### Return a Pydantic model @@ -1167,7 +1167,8 @@ for tool in await session.list_tools(model="model-id", mode=Mode.AUTO): ``` `update_settings()` accepts the same override fields for later turns. -The four override parameters accept `set[str]`, `frozenset[str]`, or `None`. +The four override parameters accept any iterable of tool IDs, such as a set, +list, or tuple. Passing a bare string raises `TypeError`. `list_tools()` returns `list[ToolInfo]`. diff --git a/src/droid_sdk/_high_level/_convert.py b/src/droid_sdk/_high_level/_convert.py index 357937b..fa59613 100644 --- a/src/droid_sdk/_high_level/_convert.py +++ b/src/droid_sdk/_high_level/_convert.py @@ -163,6 +163,7 @@ def document_to_wire(document: Document) -> dict[str, Any]: "mediaType": "text/plain", "data": source.data, "name": source.name, + "mime": source.mime, } assert isinstance(source, PdfDocumentSource) return { @@ -315,16 +316,22 @@ def settings_update_from_wire( additional_tools=( None if value.additional_tool_ids is None - else set(value.additional_tool_ids) + else frozenset(value.additional_tool_ids) ), enabled_tools=( - None if value.enabled_tool_ids is None else set(value.enabled_tool_ids) + None + if value.enabled_tool_ids is None + else frozenset(value.enabled_tool_ids) ), disabled_tools=( - None if value.disabled_tool_ids is None else set(value.disabled_tool_ids) + None + if value.disabled_tool_ids is None + else frozenset(value.disabled_tool_ids) ), restrict_tools=( - None if value.restrict_tool_ids is None else set(value.restrict_tool_ids) + None + if value.restrict_tool_ids is None + else frozenset(value.restrict_tool_ids) ), compaction_threshold_check_enabled=value.compaction_threshold_check_enabled, ) diff --git a/src/droid_sdk/_high_level/_session_operations.py b/src/droid_sdk/_high_level/_session_operations.py index 9285922..372f9bb 100644 --- a/src/droid_sdk/_high_level/_session_operations.py +++ b/src/droid_sdk/_high_level/_session_operations.py @@ -22,7 +22,11 @@ wire_reasoning, wire_tags, ) -from droid_sdk._high_level.config import SessionSettings, UpdateSettingsResult +from droid_sdk._high_level.config import ( + SessionSettings, + UpdateSettingsResult, + freeze_tool_ids, +) from droid_sdk._high_level.enums import ContextAccuracy, Mode from droid_sdk._high_level.extensions import ( CompactOutcome, @@ -54,7 +58,7 @@ ) if TYPE_CHECKING: - from collections.abc import Callable, Sequence + from collections.abc import Callable, Iterable, Sequence from droid_sdk._high_level.config import SessionTag from droid_sdk._high_level.enums import Autonomy, ReasoningEffort @@ -105,12 +109,16 @@ async def update_settings( tags: Sequence[SessionTag] | None = None, compaction_token_limit: int | None = None, compaction_threshold_check_enabled: bool | None = None, - additional_tools: set[str] | frozenset[str] | None = None, - enabled_tools: set[str] | frozenset[str] | None = None, - disabled_tools: set[str] | frozenset[str] | None = None, - restrict_tools: set[str] | frozenset[str] | None = None, + additional_tools: Iterable[str] | None = None, + enabled_tools: Iterable[str] | None = None, + disabled_tools: Iterable[str] | None = None, + restrict_tools: Iterable[str] | None = None, ) -> UpdateSettingsResult: self._ensure_active() + additional_tools = freeze_tool_ids("additional_tools", additional_tools) + enabled_tools = freeze_tool_ids("enabled_tools", enabled_tools) + disabled_tools = freeze_tool_ids("disabled_tools", disabled_tools) + restrict_tools = freeze_tool_ids("restrict_tools", restrict_tools) spec_model_value = None if isinstance(spec_model, _Unset) else spec_model spec_reasoning_value = ( None if isinstance(spec_reasoning_effort, _Unset) else spec_reasoning_effort @@ -147,7 +155,7 @@ async def update_settings( ("restrict_tools", restrict_tools), ): if value is not None: - self._load_options[key] = frozenset(value) + self._load_options[key] = value current = self.settings self._settings = SessionSettings( model=current.model if model is None else model, @@ -196,13 +204,17 @@ async def list_tools( mode: Mode | None = None, autonomy: Autonomy | None = None, spec_model: str | None = None, - additional_tools: set[str] | frozenset[str] | None = None, - enabled_tools: set[str] | frozenset[str] | None = None, - disabled_tools: set[str] | frozenset[str] | None = None, - restrict_tools: set[str] | frozenset[str] | None = None, + additional_tools: Iterable[str] | None = None, + enabled_tools: Iterable[str] | None = None, + disabled_tools: Iterable[str] | None = None, + restrict_tools: Iterable[str] | None = None, skip_permissions_unsafe: bool | None = None, ) -> list[ToolInfo]: self._ensure_active() + additional_tools = freeze_tool_ids("additional_tools", additional_tools) + enabled_tools = freeze_tool_ids("enabled_tools", enabled_tools) + disabled_tools = freeze_tool_ids("disabled_tools", disabled_tools) + restrict_tools = freeze_tool_ids("restrict_tools", restrict_tools) result = await self._require_client().list_tools( model_id=model, interaction_mode=( diff --git a/src/droid_sdk/_high_level/config.py b/src/droid_sdk/_high_level/config.py index 76f2c0f..a5d042e 100644 --- a/src/droid_sdk/_high_level/config.py +++ b/src/droid_sdk/_high_level/config.py @@ -4,7 +4,7 @@ from __future__ import annotations -from collections.abc import Mapping, Sequence +from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass from datetime import datetime from pathlib import Path @@ -34,11 +34,24 @@ ) +def freeze_tool_ids(name: str, items: Iterable[str] | None) -> frozenset[str] | None: + """Freeze a tool-ID iterable, rejecting a bare string. + + A string is iterable, so ``frozenset("Execute")`` would silently become a + set of single characters. + """ + if items is None: + return None + if isinstance(items, str): + raise TypeError(f"{name} takes an iterable of tool IDs, not a string") + return frozenset(items) + + def _freeze_tool_sets(value: object) -> None: for name in _TOOL_SET_FIELDS: items = getattr(value, name) if items is not None: - object.__setattr__(value, name, frozenset(items)) + object.__setattr__(value, name, freeze_tool_ids(name, items)) @dataclass(frozen=True, slots=True) @@ -108,10 +121,10 @@ class SessionConfig: session_source: SessionSource | None = None auto_reject_permission_requests: bool | None = None disable_builtin_skills: bool | None = None - additional_tools: set[str] | frozenset[str] | None = None - enabled_tools: set[str] | frozenset[str] | None = None - disabled_tools: set[str] | frozenset[str] | None = None - restrict_tools: set[str] | frozenset[str] | None = None + additional_tools: Iterable[str] | None = None + enabled_tools: Iterable[str] | None = None + disabled_tools: Iterable[str] | None = None + restrict_tools: Iterable[str] | None = None def __post_init__(self) -> None: object.__setattr__(self, "mcp_servers", tuple(self.mcp_servers)) @@ -129,10 +142,10 @@ class SessionSettings: spec_reasoning_effort: ReasoningEffort | None = None tags: Sequence[SessionTag] = () sandbox: SandboxSettings | None = None - additional_tools: set[str] | frozenset[str] | None = None - enabled_tools: set[str] | frozenset[str] | None = None - disabled_tools: set[str] | frozenset[str] | None = None - restrict_tools: set[str] | frozenset[str] | None = None + additional_tools: frozenset[str] | None = None + enabled_tools: frozenset[str] | None = None + disabled_tools: frozenset[str] | None = None + restrict_tools: frozenset[str] | None = None def __post_init__(self) -> None: object.__setattr__(self, "tags", tuple(self.tags)) @@ -150,10 +163,10 @@ class SessionSettingsUpdate: spec_model: str | None = None spec_reasoning_effort: ReasoningEffort | None = None tags: Sequence[SessionTag] | None = None - additional_tools: set[str] | frozenset[str] | None = None - enabled_tools: set[str] | frozenset[str] | None = None - disabled_tools: set[str] | frozenset[str] | None = None - restrict_tools: set[str] | frozenset[str] | None = None + additional_tools: frozenset[str] | None = None + enabled_tools: frozenset[str] | None = None + disabled_tools: frozenset[str] | None = None + restrict_tools: frozenset[str] | None = None compaction_threshold_check_enabled: bool | None = None def __post_init__(self) -> None: diff --git a/src/droid_sdk/_high_level/extensions.py b/src/droid_sdk/_high_level/extensions.py index a855ce6..af0ab43 100644 --- a/src/droid_sdk/_high_level/extensions.py +++ b/src/droid_sdk/_high_level/extensions.py @@ -4,7 +4,7 @@ from __future__ import annotations -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass, field from typing import TYPE_CHECKING, Literal, TypeAlias @@ -12,6 +12,7 @@ freeze_json_object, freeze_secret_mapping, ) +from droid_sdk._high_level.config import freeze_tool_ids from droid_sdk._high_level.enums import ( Autonomy, McpServerStatus, @@ -45,10 +46,10 @@ class ListToolsOptions: mode: Mode | None = None autonomy: Autonomy | None = None spec_model: str | None = None - additional_tools: set[str] | frozenset[str] | None = None - enabled_tools: set[str] | frozenset[str] | None = None - disabled_tools: set[str] | frozenset[str] | None = None - restrict_tools: set[str] | frozenset[str] | None = None + additional_tools: Iterable[str] | None = None + enabled_tools: Iterable[str] | None = None + disabled_tools: Iterable[str] | None = None + restrict_tools: Iterable[str] | None = None skip_permissions_unsafe: bool | None = None def __post_init__(self) -> None: @@ -60,7 +61,7 @@ def __post_init__(self) -> None: ): value = getattr(self, name) if value is not None: - object.__setattr__(self, name, frozenset(value)) + object.__setattr__(self, name, freeze_tool_ids(name, value)) @dataclass(frozen=True, slots=True) diff --git a/src/droid_sdk/_high_level/session.py b/src/droid_sdk/_high_level/session.py index 9e7935e..d24355e 100644 --- a/src/droid_sdk/_high_level/session.py +++ b/src/droid_sdk/_high_level/session.py @@ -36,6 +36,7 @@ SessionSettings, SessionSource, SessionTag, + freeze_tool_ids, ) from droid_sdk._high_level.enums import ( ReasoningEffort, @@ -83,7 +84,7 @@ from droid_sdk.transport import ProcessTransport if TYPE_CHECKING: - from collections.abc import Awaitable, Callable, Mapping, Sequence + from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence ModelT = TypeVar("ModelT", bound=BaseModel) @@ -169,11 +170,12 @@ def resume( mcp_servers: Sequence[McpServerConfig] = (), runtime: Runtime | None = None, api_key: str | None = None, - disabled_tools: set[str] | frozenset[str] | None = None, + disabled_tools: Iterable[str] | None = None, auto_reject_permission_requests: bool | None = None, disable_builtin_skills: bool | None = None, session_source: SessionSource | None = None, ) -> Session: + disabled_tools = freeze_tool_ids("disabled_tools", disabled_tools) value = cls( interactions=interactions, runtime=runtime, diff --git a/tests/test_v5_public_models.py b/tests/test_v5_public_models.py index 85f2c93..91c0aca 100644 --- a/tests/test_v5_public_models.py +++ b/tests/test_v5_public_models.py @@ -37,6 +37,7 @@ ImageBlock, InvalidAttachmentError, JsonSchema, + ListToolsOptions, McpConfigError, McpOAuthOptions, McpServerStatus, @@ -314,6 +315,27 @@ def test_configuration_is_recursively_immutable() -> None: config.mode = Mode.AUTO # type: ignore[misc] +def test_tool_overrides_accept_any_iterable_and_reject_strings() -> None: + config = SessionConfig( + additional_tools=["CustomTool"], + enabled_tools=("Read",), + disabled_tools=iter(["Execute"]), + restrict_tools={"Read", "Grep"}, + ) + assert config.additional_tools == frozenset({"CustomTool"}) + assert config.enabled_tools == frozenset({"Read"}) + assert config.disabled_tools == frozenset({"Execute"}) + assert config.restrict_tools == frozenset({"Read", "Grep"}) + + options = ListToolsOptions(disabled_tools=["Execute"]) + assert options.disabled_tools == frozenset({"Execute"}) + + with pytest.raises(TypeError, match="disabled_tools"): + SessionConfig(disabled_tools="Execute") + with pytest.raises(TypeError, match="restrict_tools"): + ListToolsOptions(restrict_tools="Read") + + def test_json_schema_is_recursive_and_rejects_non_json() -> None: schema = {"type": "object", "required": ["name"]} value = JsonSchema(schema) @@ -892,6 +914,10 @@ def test_public_enum_values() -> None: ) +@pytest.mark.skipif( + os.environ.get("DROID_LIVE_TESTS") != "1", + reason="set DROID_LIVE_TESTS=1 to run examples against droid exec", +) @pytest.mark.parametrize( "example", [ @@ -900,14 +926,14 @@ def test_public_enum_values() -> None: "structured_output_model.py", ], ) -def test_offline_examples_execute(example: str) -> None: +def test_live_examples_execute(example: str) -> None: root = Path(__file__).parents[1] completed = subprocess.run( [sys.executable, str(root / "examples" / example)], check=False, capture_output=True, text=True, - timeout=30, + timeout=300, ) assert completed.returncode == 0, completed.stderr assert completed.stdout diff --git a/tests/test_v5_session.py b/tests/test_v5_session.py index b5f8a73..26c0ba0 100644 --- a/tests/test_v5_session.py +++ b/tests/test_v5_session.py @@ -308,6 +308,23 @@ async def test_session_updates_and_merges_settings_notifications() -> None: await session.close() +@pytest.mark.asyncio +async def test_update_settings_accepts_iterables_and_rejects_strings() -> None: + session = Session(runtime=runtime()) + await session.open() + client = FakeClient.instances[0] + + await session.update_settings(disabled_tools=["Execute", "Edit"]) + assert client.update_calls[-1]["disabled_tool_ids"] == ["Edit", "Execute"] + assert session.settings.disabled_tools == frozenset({"Execute", "Edit"}) + + calls_before = len(client.update_calls) + with pytest.raises(TypeError, match="disabled_tools"): + await session.update_settings(disabled_tools="Execute") + assert len(client.update_calls) == calls_before + await session.close() + + @pytest.mark.asyncio async def test_session_maps_missing_executable_and_cleans_up() -> None: FakeClient.fail_connect = True @@ -579,9 +596,9 @@ async def test_stream_serializes_text_and_pdf_through_wire_models() -> None: "mediaType": "text/plain", "data": "notes", "name": "notes.txt", + "mime": "application/x-high-level-only", } assert wire[1]["mediaType"] == "application/pdf" - assert "mime" not in wire[0] await session.close() diff --git a/tests/typing/positive.py b/tests/typing/positive.py index 9f56aa5..f153447 100644 --- a/tests/typing/positive.py +++ b/tests/typing/positive.py @@ -36,6 +36,7 @@ RunStream, RunSuccess, Session, + SessionConfig, SessionSettings, SessionSettingsUpdate, StreamEvent, @@ -84,6 +85,11 @@ class Review(BaseModel): ) assert_type(settings.model, str) assert_type(settings.reasoning_effort, ReasoningEffort) +assert_type(settings.disabled_tools, frozenset[str] | None) + +SessionConfig(disabled_tools={"Execute"}) +SessionConfig(disabled_tools=["Execute"]) +SessionConfig(disabled_tools=("Execute",)) settings_update = SessionSettingsUpdate(model="claude-sonnet") assert_type(settings_update.model, str | None) From 15a4824dc4d0671b04ff5637c0a80706c2a9d9aa Mon Sep 17 00:00:00 2001 From: User Date: Thu, 13 Aug 2026 00:21:33 -0700 Subject: [PATCH 28/30] fix: make success guarantee structured output when requested Previously a completed turn stayed RunSuccess even when requested output failed local validation (output=None, output_validation_error set), and the JsonSchema path could return success with no output and no error at all. Now, if output was requested and is absent, the result is RunFailure with subtype error_structured_output and a structured_output_error code of local_validation_failed or local_output_missing, so local and Droid-side failures share one verdict. All partial data is retained on the failure. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 21 +++++----- src/droid_sdk/_high_level/streaming.py | 34 ++++++++++++++++- tests/test_v5_streaming_core.py | 53 +++++++++++++++++++++++++- 3 files changed, 96 insertions(+), 12 deletions(-) diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index 3e8626a..dfd1318 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -877,7 +877,7 @@ from typing import Literal from pydantic import BaseModel -from droid_sdk import run +from droid_sdk import RunSuccess, run class Finding(BaseModel): @@ -895,8 +895,8 @@ result = await run( output=Review, ) -if result.output is not None: - print(result.output.summary) +if isinstance(result, RunSuccess) and result.output is not None: + print(result.output.summary) # success guarantees output when requested elif result.output_validation_error is not None: print(result.output_validation_error) ``` @@ -906,9 +906,10 @@ types raise `TypeError` before the turn starts. With `output=Review`, the return type is `RunResult[Review]`. When structured output arrives, the SDK validates it against the model. -Missing or invalid output leaves `output` as `None` and populates -`output_validation_error`; it does not change Droid's terminal subtype. -A successful turn can therefore have `output is None`. +If output was requested, `RunSuccess` guarantees `result.output` is set. +Missing or invalid output turns the result into `RunFailure` with subtype +`error_structured_output`; the failure keeps the text, messages, usage, raw +`structured_output`, and `output_validation_error` for inspection. ### Use raw JSON Schema @@ -970,9 +971,11 @@ FrozenJsonValue = ( FrozenJsonObject = Mapping[str, FrozenJsonValue] ``` -Pydantic adaptation errors use `output_validation_error`. Droid's own -structured-output errors use `structured_output_error`. Neither field changes -the terminal subtype chosen by Droid. +Both local and Droid-side output failures produce `RunFailure` with subtype +`error_structured_output`. To tell them apart, check +`structured_output_error.code`: local failures use `local_validation_failed` +(with the Pydantic error in `output_validation_error`) or +`local_output_missing`; Droid-side failures use Droid's own codes. ## Permissions and user input diff --git a/src/droid_sdk/_high_level/streaming.py b/src/droid_sdk/_high_level/streaming.py index 6644615..174e0b4 100644 --- a/src/droid_sdk/_high_level/streaming.py +++ b/src/droid_sdk/_high_level/streaming.py @@ -658,14 +658,44 @@ def _complete( AgentTurnCompletionReason.Completed, AgentTurnCompletionReason.SpecHandoff, }: - return RunSuccess( + if self.output_adapter is None or output is not None: + return RunSuccess( + text=text, + messages=tuple(self._messages), + usage=usage, + duration=duration, + turn_count=1, + session_id=self.session_id, + output=output, + structured_output=raw, + output_validation_error=validation_error, + ) + # Output was requested but is absent: success must guarantee + # output, so this maps to the same failure subtype Droid uses. + if validation_error is not None: + code = "local_validation_failed" + message = "Structured output failed local validation" + else: + code = "local_output_missing" + message = "The turn completed without usable structured output" + return RunFailure( + subtype="error_structured_output", + error=ErrorEvent( + message=message, + error_type=ErrorType.ERROR, + timestamp=self._now(), + ), + structured_output_error=StructuredOutputError( + code=code, + message=message, + ), text=text, messages=tuple(self._messages), usage=usage, duration=duration, turn_count=1, session_id=self.session_id, - output=output, + output=None, structured_output=raw, output_validation_error=validation_error, ) diff --git a/tests/test_v5_streaming_core.py b/tests/test_v5_streaming_core.py index c80ea4d..2d4e15d 100644 --- a/tests/test_v5_streaming_core.py +++ b/tests/test_v5_streaming_core.py @@ -813,6 +813,10 @@ async def test_structured_output_raw_adapted_fallback_and_validation_error() -> ) invalid.feed_notification(_complete()) await _collect(invalid) + assert isinstance(invalid.result, RunFailure) + assert invalid.result.subtype == "error_structured_output" + assert invalid.result.structured_output_error is not None + assert invalid.result.structured_output_error.code == "local_validation_failed" assert invalid.result.output is None assert invalid.result.output_validation_error is not None assert invalid.result.structured_output == { @@ -841,6 +845,52 @@ async def test_structured_output_raw_adapted_fallback_and_validation_error() -> assert raw.result.output == {"summary": "fallback"} +@pytest.mark.asyncio +async def test_requested_output_that_never_arrives_is_a_failure() -> None: + missing = RunStream[Mapping[str, object]]( + expected_turn_id="turn", + session_id="session", + output_adapter=cast( + "Any", + prepare_output_adapter(JsonSchema({"type": "object"})), + ), + ) + missing.feed_notification( + { + "type": "assistant_text_delta", + "messageId": "assistant", + "blockIndex": 0, + "textDelta": "no structured output here", + } + ) + missing.feed_notification(_complete()) + await _collect(missing) + assert isinstance(missing.result, RunFailure) + assert missing.result.subtype == "error_structured_output" + assert missing.result.structured_output_error is not None + assert missing.result.structured_output_error.code == "local_output_missing" + assert missing.result.output is None + assert missing.result.output_validation_error is None + assert missing.result.text == "no structured output here" + + plain = RunStream[None]( + expected_turn_id="turn", + session_id="session", + ) + plain.feed_notification( + { + "type": "assistant_text_delta", + "messageId": "assistant", + "blockIndex": 0, + "textDelta": "no output requested", + } + ) + plain.feed_notification(_complete()) + await _collect(plain) + assert isinstance(plain.result, RunSuccess) + assert plain.result.output is None + + @pytest.mark.asyncio @pytest.mark.parametrize( "raw_json", @@ -874,7 +924,8 @@ async def test_non_finite_structured_output_fallback_always_terminalizes( events = await _collect(stream) assert events[-1] is stream.result - assert isinstance(stream.result, RunSuccess) + assert isinstance(stream.result, RunFailure) + assert stream.result.subtype == "error_structured_output" assert stream.result.output is None assert stream.result.structured_output is None assert stream.result.output_validation_error is not None From e92b6c45a47325c14ed25b36f68aca09aa2aa558 Mon Sep 17 00:00:00 2001 From: User Date: Thu, 13 Aug 2026 00:30:01 -0700 Subject: [PATCH 29/30] fix: only enforce the output guarantee when output was requested Sessions always pass an adapter object, even for output=None, so checking the adapter for None made every plain live turn fail with local_output_missing. Gate on the adapter carrying a wire format instead. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- src/droid_sdk/_high_level/streaming.py | 8 +++++- tests/test_v5_streaming_core.py | 36 ++++++++++++++------------ 2 files changed, 27 insertions(+), 17 deletions(-) diff --git a/src/droid_sdk/_high_level/streaming.py b/src/droid_sdk/_high_level/streaming.py index 174e0b4..94b82d2 100644 --- a/src/droid_sdk/_high_level/streaming.py +++ b/src/droid_sdk/_high_level/streaming.py @@ -654,11 +654,17 @@ def _complete( else timedelta(milliseconds=notification.duration_ms) ) reason = notification.reason + # Sessions always pass an adapter object; output was only requested + # when it carries a wire format. + wants_output = ( + self.output_adapter is not None + and self.output_adapter.output_format is not None + ) if reason in { AgentTurnCompletionReason.Completed, AgentTurnCompletionReason.SpecHandoff, }: - if self.output_adapter is None or output is not None: + if not wants_output or output is not None: return RunSuccess( text=text, messages=tuple(self._messages), diff --git a/tests/test_v5_streaming_core.py b/tests/test_v5_streaming_core.py index 2d4e15d..f845628 100644 --- a/tests/test_v5_streaming_core.py +++ b/tests/test_v5_streaming_core.py @@ -873,22 +873,26 @@ async def test_requested_output_that_never_arrives_is_a_failure() -> None: assert missing.result.output_validation_error is None assert missing.result.text == "no structured output here" - plain = RunStream[None]( - expected_turn_id="turn", - session_id="session", - ) - plain.feed_notification( - { - "type": "assistant_text_delta", - "messageId": "assistant", - "blockIndex": 0, - "textDelta": "no output requested", - } - ) - plain.feed_notification(_complete()) - await _collect(plain) - assert isinstance(plain.result, RunSuccess) - assert plain.result.output is None + # Sessions always pass an adapter object; with output=None it carries no + # wire format and must not trigger the output guarantee. + for adapter in (None, prepare_output_adapter()): + plain = RunStream[None]( + expected_turn_id="turn", + session_id="session", + output_adapter=adapter, + ) + plain.feed_notification( + { + "type": "assistant_text_delta", + "messageId": "assistant", + "blockIndex": 0, + "textDelta": "no output requested", + } + ) + plain.feed_notification(_complete()) + await _collect(plain) + assert isinstance(plain.result, RunSuccess) + assert plain.result.output is None @pytest.mark.asyncio From 5187fdf71348925aa50126a3a589e2e7bbb81b19 Mon Sep 17 00:00:00 2001 From: User Date: Thu, 13 Aug 2026 00:42:52 -0700 Subject: [PATCH 30/30] docs: state where the default model lives and how bad IDs fail Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- docs/python-sdk-reference.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/python-sdk-reference.md b/docs/python-sdk-reference.md index dfd1318..4187368 100644 --- a/docs/python-sdk-reference.md +++ b/docs/python-sdk-reference.md @@ -159,7 +159,11 @@ models are immutable dataclasses. ## Models Model IDs are strings because availability depends on account and -organization policy. Omit `model` to use the configured default. +organization policy. Omit `model` to use the configured default, which +lives in `~/.factory/settings.json` under `sessionDefaultSettings`. +An unknown model ID is rejected by the backend: the turn returns +`RunFailure(subtype="error_during_execution")` with the rejection message +in `error.message`. ### Select a model