Metadata-Version: 2.5
Name: dory-run
Version: 0.2.0
Summary: Dory Python SDK
Project-URL: Homepage, https://dory.run
Project-URL: Documentation, https://dory.run/docs/
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: agents,cloud-computer,dory,mcp,sandbox
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Requires-Dist: jsonschema<5,>=4.23
Requires-Dist: mcp<1.27,>=1.26.0
Requires-Dist: pydantic<3,>=2.9
Requires-Dist: websockets<16,>=15
Description-Content-Type: text/markdown

# dory-run

Python 3.10+ SDK for Dory. Apache-2.0.

```
pip install dory-run
```

The import name is `dory`. Docs: https://dory.run/docs/

`Client(api_key=None, api_url=None)` and `AsyncClient` use explicit arguments or
`DORY_API_KEY` / `DORY_API_URL` (the older `CE_API_KEY` / `CE_API_URL` still work). They never load dotenv or credential files. The default
control endpoint is https://api.dory.run/v1. HTTP uses httpx;
WebSockets use websockets. Use `with Client()` or `async with AsyncClient()` to
close connections. Async calls have the same snake_case names; await calls and
use async iteration for streams/events.

Create/start/resume/restart wait for running and ready; pause/stop wait for their
final states. The default local waiter budget is 600 seconds (including retries),
configurable with `wait_timeout_seconds`. Timeout does not cancel the operation
or stop billing. Errors retain computer/operation IDs and the idempotency key.
Delete returns upon acceptance, not physical purge.

Cancellation re-raises the original `asyncio.CancelledError` with `computer_id`,
`operation_id` and `idempotency_key` attributes. When `asyncio.timeout()` converts
it to `TimeoutError` (including Python 3.11), recover those attributes from
`exc.__cause__`. The SDK's own deadline raises `WaitTimeout` with them directly.
A settled final-state mismatch raises `ApiError` immediately rather than timing out.

The handle's `c.desktop` and `c.network` are resources. Its documented `c.model`
property exposes the current wire `Computer` model: `c.model.desktop` and
`c.model.network` hold the wire values, and refresh/lifecycle calls update it.

`computer.exec(command)` returns ExecResult even for nonzero remote exit codes.
Pass an explicit `idempotency_key` for deduplication; a replay returns ProcessReplay,
not invented output. `processes.start(command_or_argv)` returns ProcessStarted.
Retrieve `processes.get(proc_id)` for status/output/stdin/signal/kill/wait.
`exec_stream` returns a closeable iterator with process metadata. Closing any
stream never kills the process. Save per-stream byte offsets and explicitly
reattach after StreamDisconnected; OutputGap and OutputExpired are never skipped.

Control POST/PATCH keys are generated once per call and preserved across retries.
Control 429/503 retries require Retry-After. Data retries require CE-Not-Forwarded,
except keyed exec/process requests may retry ambiguous network/502/504 failures
using the original key and identical payload. Data-plane keys are never generated.
Both clients accept `max_retry_after_seconds` (default 60, finite and nonnegative).
A 429/503 Retry-After beyond the cap or remaining waiter budget raises the server's
`ApiError` immediately with its Problem and `retry_after_seconds`. This also bounds
permitted data-plane and WebSocket-upgrade retries. A successful pending/running
operation poll with an excessive delay instead raises `WaitTimeout`, retaining
`retry_after_seconds`, `operation_id`, `computer_id` and the original `idempotency_key`,
without sleeping, resubmitting or cancelling server work.
Tokens are cached per computer/scope and refreshed at least 60 seconds before
expiry before new connections; existing streams are not reauthorized in place.
Lifetime uses the server Date header when available, with a monotonic request
start and a cap at the requested lifetime. Rejected expired/revoked tokens are
evicted only if that exact grant is still cached; a late rejection cannot evict a
newer grant. The local clock can only shorten that lifetime, guarding stale Date
headers without allowing a slow client clock to extend server authorization.
First output attaches and header-authenticated socket opens reuse cached tokens.
A lost stream/socket evicts its computer/scope token so an explicit reattach mints
fresh; secret-URL CDP connections use their newly created session credential.
Credential fields are omitted from model str/repr, but remain available through
explicit attributes and wire serialization; do not log credential model dumps.

`PermissionDenied` distinguishes guest Unix access refusals from authentication
or key errors and exposes optional `errno`, `path` and `user` fields.
`SecretAlreadyReturned.replay` retains the redacted response model; use
`exc.replay.id` to identify the resource when minting a replacement credential
(or dictionary keys for untyped private requests). `exc.location` retains Location.

`computer.pty()` creates a terminal handle; connect/reconnect with its `connect()`.
Its `close()` closes only a socket; `delete()` closes the retained session.
`desktop.viewer()` returns a session result, not connected exclusive control.
Use `desktop.control()` and `desktop.sessions.delete(id)` for explicit handoff.
`browser.cdp_url()` returns the server URL; optional `connect_playwright(browser_type)`
accepts your existing Playwright Chromium object without an SDK Playwright dependency.
Socket iteration ends on a normal close. Abnormal receive/iteration closure raises
`StreamDisconnected`; sockets never reconnect automatically. Text and binary
messages are not limited to websockets' default 1 MiB maximum.

Development (Python 3.13, real loopback PostgreSQL required):

    uv sync
    uv run pytest -q
    uv run python tools/generate_models.py --check
    uv build

Python 3.11 unit coverage without the Python-3.13-only ctl dependency (Bash):

    UV_PROJECT_ENVIRONMENT=.venv311 uv run --python 3.11 --no-dev --group unit pytest -q --ignore=tests/integration

Worktrees can set `CE_DEV_DB_PASSWORD_FILE` to the authorized development database
password file for integration tests; its contents are never printed or copied.
Without an explicit override, a missing worktree password file falls back to
`C:/MailEnableAgent/ce-agent-computers/.dev/secrets/dev-db-password`.
The test harness creates the configured basetemp's parent directory if needed.

Models are generated from ../../openapi.yaml using the committed generator.
Integration tests execute DOCS-OUTLINE's Python quickstart snippets unchanged,
using real local ctl/gateway listeners and the simulator. No external hosts are
contacted. The simulator is not proof of actual Linux, Chromium or Hyper-V behavior.
Computer-use integrations are included: `dory.adapters.anthropic.ComputerToolset`
and `dory.adapters.openai.ComputerTool` accept sync or async computers,
without installing either provider SDK. `cec mcp` now implements the formerly
planned manifest command as a stdio MCP server using the usual CLI credentials;
stdout is JSON-RPC only. It lists all 36 tools (the hosted server filters by key
scope), returns API Problems as tool errors, and never automatically retries.

Protocol documentation checked 2026-10-26: the current official MCP revision is
2026-07-28. This implementation supports only the initialize-based 2025-11-25
revision, tested with mcp 1.26.0. It is a legacy-protocol server in current MCP
terminology, not a modern or dual-era server. It does not implement server/discover,
modern per-request metadata negotiation, 2025-03-26 batches, the deprecated HTTP+SSE
transport, or older revision semantics. A client must support 2025-11-25 to continue
after negotiation.

Hosted initialize accepts an absent version header or `MCP-Protocol-Version:
2025-11-25`, independently of the proposed revision. A supplied unsupported header
is refused with HTTP 400 even on initialize. Every subsequent HTTP message requires
the supported header; the absent historical 2025-03-26 default is not supported.
There is no HTTP protocol session or negotiation cache. Arrays are refused as one
invalid envelope, not processed as batches. Valid request method/parameter errors
are correlated JSON-RPC errors over HTTP 200; API/inputSchema refusals remain tool
results with `isError:true`. An incompatible client must disconnect rather than
continue using the revision it originally proposed.

The verified raw dual-era fallback sequence is a bounded client-policy fixture.
It sends `server/discover` first:
stdio gets a non-modern -32601 refusal; HTTP with the 2026-07-28 header gets HTTP
400, not modern -32022 negotiation. The fixture then sends legacy initialize
(without the unsupported HTTP header), accepts 2025-11-25, sends initialized, and
completes ping, tools/list and a harmless list_computers call. A modern-only client
stops instead. This does not authorize replaying an effectful modern tools/call,
or fallback after authentication, Origin, rate, size or maintenance refusal.
The official pinned-client happy-path/recovery tests are separate from these raw
client-policy fixtures; no Claude Code, Cursor, Codex or modern SDK certification
is claimed.

Protocol references (dated documents reviewed for this implementation):
[2025-11-25 lifecycle](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle),
[2025-11-25 transports](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports),
[2025-06-18 batch removal](https://modelcontextprotocol.io/specification/2025-06-18/changelog#major-changes),
[2026-07-28 terminology/versioning](https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning#terminology),
[modern stdio backward compatibility](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio#backward-compatibility),
and [modern HTTP backward compatibility](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http#backward-compatibility).

OpenAI actions and drag points accept nested mapping, attribute and Pydantic
objects without dropping unknown fields. Optional mouse `keys` may be absent,
null or empty; nonempty move modifiers execute as key-downs, move and reverse
key-ups in one bounded batch. Failure attempts release once, never force/replay,
and reports only fully completed provider actions. A supplied call `status` must
be `completed`. Pending checks require explicit callback approval of every complete
JSON check value (property order does not matter); changed messages or ID-only
approval are refused. The callback receives a copy, and approved original values
are echoed as JSON dictionaries. Existing preview gating, including pending
checks, still applies. Anthropic `repeat` defaults only when absent, not null.

Current acceptance blocker: the unchanged quickstart fails at step 5 because
ce_sim returns exit 127 (`python3: command not found`) for its Python `-c`
readiness probe. The failing test is retained, not skipped or rewritten. Other
integration tests cover the supported simulator flow; they do not replace this
acceptance requirement. See ../../build/slice-P2-3-report.md for verification and
the ctl-owned follow-up. The P2-3-fix verification is in
../../build/slice-P2-3-fix-report.md; SIM-fix is also responsible for the step-7
cursor-free screenshot default.

## CLI

Install the `cec` command with `uv tool install dory-run` or
`pipx install dory-run`. For this checkout use `cd sdk/python && uv sync`,
then `uv run cec --help`.

Run `cec login` for a hidden prompt, or `cec login --key-stdin` with a key on the
first line of stdin. Redirected stdin is never consumed beyond that line.
Credentials are stored at `~/.config/cec/credentials.toml` on every OS: POSIX
directory/file modes 0700/0600, or a protected current-user-only Windows DACL.
A nonempty `DORY_API_KEY` (or `CE_API_KEY`) overrides the file; `DORY_API_URL` (or `CE_API_URL`) overrides the SDK's
default control endpoint. Neither the CLI nor SDK loads `.env` files.
Environment keys are validated before HTTP; whitespace, quotes, backslashes and
control characters are rejected without echoing the key.

Use `--json` for machine-readable responses, preserving unknown JSON fields.
Lifecycle commands print the final Computer; streamed output is NDJSON. Binary
downloads are atomic and print file metadata with `--json`. Diagnostics are on
stderr, with credentials redacted. `desktop act --json actions.json` instead
reads the JSON request from that file and always emits JSON. `shell`, `ssh` and
the hidden `ssh-proxy` reject `--json`.
Remote stdout/stderr and stream data are relayed unchanged, including in JSON;
they are not CLI diagnostics. Explicit credential-return commands still print
their requested credential to stdout only.

`cec cp ID:/absolute/path DIRECTORY` validates the guest basename before touching
the derived local path. Windows rejects separators, drive/device names and trailing
dots/spaces; valid POSIX colon/backslash names remain supported. An explicit local
file target selects the local name instead of deriving one from the guest.

`cec ssh ID [-- CMD...]` keeps strict host-key checking and quotes known_hosts
paths, including spaces, apostrophes and literal percent signs. Its Python proxy
excludes implicit current-directory imports (`-P` on 3.11+, a path-removal bootstrap
on 3.10), without isolated mode or disabling installed/user-site packages. Explicit
caller PYTHONPATH policy remains the caller's responsibility.

| Exit | Meaning |
|---|---|
| 0 | Success, including accepted asynchronous work and background replay |
| Remote status | First synchronous exec, attach, shell or system ssh exit |
| 124 / 128+N / 125 | Null remote exit: timeout / Linux signal / unknown |
| 1 | API, operation, transport, stream, replayed-secret or internal error |
| 2 | Local usage or configuration error |
| 3 | Local lifecycle wait expired; server work continues |
| 4 | Keyed synchronous exec replay; use the printed attach hint |
| 130 | Ctrl+C; server work is not cancelled |

`cec create --size ac-2 --json` waits for running and ready. The lifecycle
budget defaults to 600 seconds (`--wait-timeout-seconds`). A failure retains
known IDs and the original key and prints inspection/deletion instructions.
`cec rm ID --yes` returns on acceptance, not physical purge.

Control-plane POST/PATCH calls generate one idempotency key, or use the supplied
`--idempotency-key`, across at most three retries. Only control-plane 429/503
with an integer Retry-After within `--max-retry-after-seconds` (default 60) and
the remaining waiter budget are retried. Data-plane calls and their token mints
are never retried automatically. `cec exec ID --idempotency-key KEY -- ARGV...`
passes argv unchanged and does not consume stdin. After an uncertain keyed
execution, repeat with that same key, not a new one.
The same CLI retry cap also governs successful pending-operation polling, even
though SDK request retries are disabled. A pending poll over the cap or remaining
budget exits 3 with `wait_timeout`, the original IDs/key and `retry_after_seconds`;
it does not sleep or submit another lifecycle POST. Actual over-cap 429/503
responses remain exit-1 API errors with their server Problem. Integer Retry-After
zero is eligible for the CLI's minimum one-second retry sleep and existing budget.

`cec manifest --json` (also `cec manifest`) lists the registered command paths,
arguments, flags, examples and launch operation coverage. It records the three
browser-only connect-token/VNC exemptions and the available stdio `mcp` command. The
manifest and argparse use the same registry; no OpenAPI file is needed at runtime.
Help and manifest describe required `exec -- ARGV...`, optional `ssh [-- CMD...]`,
and the `cp` output union `FileStat|BatchUploadResult|file`.
