# Coasty Computer Use API > The single, complete reference for the Coasty Computer Use (CUA) API. Coasty > turns a screenshot plus an instruction into structured GUI actions, drives > autonomous task runs on a machine, and composes those runs into versioned > workflows. This document covers every endpoint, request field, response shape, > error, rate limit, scope, and price. - Base URL: `https://coasty.ai/v1` - Auth header: `X-API-Key: ` (or `Authorization: Bearer `) - Human docs: https://coasty.ai/docs - Manage keys: https://coasty.ai/developers/keys - Site-wide LLM doc: https://coasty.ai/llms-full.txt --- ## 1. Overview Coasty exposes three layers, smallest to largest: 1. **Core inference** (`/v1/predict`, `/v1/sessions`, `/v1/ground`, `/v1/parse`). You supply screenshots and instructions; Coasty returns the actions to take. You execute the actions on your own machine and loop. 2. **Submit-and-forget Tasks** (`/v1/tasks`). You give Coasty one task; it provisions, executes, verifies, cleans up, and reports pass/fail with no human takeover. 3. **Task Runs** (`/v1/runs`). You give the agent a task plus a `machine_id` and Coasty drives the whole loop server-side (autonomous, pass/fail verified, optional human takeover, per-step billing, streaming events, webhooks). 4. **Workflows** (`/v1/workflows`). A versioned JSON DSL that composes many runs with branching, loops, parallelism, asserts, retries, and human approvals. How a single inference turn works: send a base64 screenshot and a natural language instruction; the model returns an ordered list of `actions` (clicks, typing, key presses, scrolls, etc.) and a `status` of `continue`, `done`, or `fail`. With `/v1/predict` you manage trajectory yourself; with `/v1/sessions` the server remembers the trajectory across steps. ### Base URL All endpoints live under: ``` https://coasty.ai/v1 ``` ### Authentication Send your API key in either header (both are accepted on every `/v1` endpoint): ``` X-API-Key: sk-coasty-live-<48 hex> Authorization: Bearer sk-coasty-live-<48 hex> ``` Read the key from the `COASTY_API_KEY` environment variable rather than hard coding it. A missing or malformed key returns `401 INVALID_API_KEY` (which also sends a `WWW-Authenticate: Bearer` challenge header). ### Request ids and response headers Every response produced by the Coasty application carries `X-Request-Id`, which identifies the current HTTP attempt. `X-Coasty-Request-Id` and a body `request_id` normally match it. On an exact idempotent replay, however, the Coasty-specific header and/or stored body can preserve the original logical operation id while `X-Request-Id` identifies the new replay attempt. Log every distinct value. A CDN/network failure can happen before Coasty builds a response and may contain no Coasty request id. Billed responses also return two headers so you can track spend without a second call: - `X-Credits-Charged`: the net cost of this HTTP attempt in credits (1 credit = $0.01; `0` on test keys, free configured operations, confirmed refunds, and idempotent replays). - `X-Credits-Remaining`: your wallet balance after the charge (USD cents), emitted only when an authoritative wallet result/read is available. It is omitted rather than guessed during a wallet outage. **Refunds are machine-observable.** Per-request charges are submitted for refund when the service can prove the billed operation failed without an ambiguous external commit (e.g. a `5xx` `PREDICTION_FAILED` / `GROUNDING_FAILED`). An ambiguous post-dispatch mutation such as `SNAPSHOT_OUTCOME_UNKNOWN` deliberately retains its debit until reconciliation. On a confirmed refund, the response carries `X-Credits-Charged: 0` **and** `X-Credits-Refunded: ` (the credits returned to your wallet), so you can confirm the refund from the response headers — you no longer have to re-poll `/v1/usage`. If the wallet service cannot confirm the refund, the API instead returns `503 BILLING_UNAVAILABLE`, preserves the non-zero `X-Credits-Charged` value, and omits `X-Credits-Refunded`. Do not assume funds were restored in that case; inspect the error's retry fields. A response with `retryable: true`, `retry_with_same_idempotency_key: true`, and `Idempotency-Status: completed` means a shared refund checkpoint was confirmed: retry the original mutation with the **same** key and identical body to settle that debit without running the model again. If either retry field is `false` (including unkeyed requests or a checkpoint-store failure), do **not** retry automatically; quote the `request_id` to support. `GET /v1/idempotency/{key}` never exposes the private settlement marker and is deliberately non-retryable; only the original mutation route can perform the settlement. Once a refund is confirmed (`X-Credits-Refunded` is present), that stable debit id is permanently compensated. Reusing its Idempotency-Key cannot fund a new execution: a durable tombstone replays the refunded failure, and the wallet ledger independently returns `409 IDEMPOTENCY_ALREADY_REFUNDED` if the cache marker is unavailable. Use a **new** Idempotency-Key for a genuinely new attempt. **Idempotent replays bill 0.** A replay (same `Idempotency-Key`) is served from the cache with `X-Coasty-Idempotent-Replay: true` (plus `Idempotency-Replayed: true` and `Idempotency-Status: completed`) and `X-Credits-Charged: 0`. Inference responses also zero the replayed body's `usage.credits_charged` and set `usage.billed: false`. A machine-snapshot replay retains the original gross `credits_charged` in its stored body for auditability, while the header remains `0` because the replaying HTTP attempt costs nothing. `X-Credits-Remaining` appears only when the route can read the current balance authoritatively. See the dedicated **Idempotency** section for the full contract. **`usage.billed` flag.** Every billed inference response now carries `usage.billed`: `true` on a real billed call, and `false` on test keys (`sk-coasty-test-*`) and on idempotent replays. Branch on it to tell a paid call apart from a free one without comparing credit numbers. Other useful headers: `X-Coasty-Key-Kind` (`live` / `test` / `legacy`), `X-Coasty-Test-Mode: true` (test keys only), and `X-Coasty-Idempotent-Replay: true` when a response was served from the idempotency cache. The rate-limited CUA inference operations (predict, ground, and session helpers) carry `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset` (the unix epoch second the window rolls over), mirrored under the IETF-draft `RateLimit-*` names. They are **advisory**: surface them for backoff, but treat a `429 RATE_LIMITED` body (with its `Retry-After`) as authoritative. Other operations do not promise these headers. The per-operation OpenAPI response headers are the source of truth. **Response-headers quick reference** (availability is operation-specific; see OpenAPI): | Header | Meaning | | --- | --- | | `X-Request-Id` | Current HTTP-attempt correlation id. | | `X-Coasty-Request-Id` | Normally the attempt id; an exact replay can preserve the original operation id. | | `X-Credits-Charged` | On API-billed operations, credits this attempt cost (`0` on test keys and replays). | | `X-Credits-Remaining` | On operations with an authoritative wallet result, balance after the charge (USD cents). | | `X-Credits-Refunded` | On a confirmed billed-operation refund, credits returned (paired with `X-Credits-Charged: 0`). | | `X-Coasty-Idempotent-Replay` | On reserve-and-replay operations, `true` when served from the idempotency cache. | | `Idempotency-Status` | On reserve-and-replay operations, `processing` or `completed`. | | `Idempotency-Replayed` | On reserve-and-replay operations, `true` on a replay and `false` on the original. | | `X-RateLimit-Limit` / `-Remaining` / `-Reset` | On rate-limited CUA inference operations, advisory budget (also under `RateLimit-*`). | | `X-Coasty-Key-Kind` | `live` / `test` / `legacy`. | | `X-Coasty-Test-Mode` | `true` on test keys only. | ### Key management - Create, list, and revoke keys at https://coasty.ai/developers/keys, or via the API: `POST /v1/keys`, `GET /v1/keys`, `DELETE /v1/keys/{key_id}`. All three require the `keys` scope, which is **opt-in** and is not on a default key, because `POST /v1/keys` **mints** further keys. Treat a key that holds it as account-level authority, not merely a reader of key metadata. - The raw key is shown exactly **once** at creation; store it securely. - Per-account cap: **200 active keys**. Keys are free, so mint one per service or per environment rather than sharing one. - Each key carries a set of scopes (see Reference). New keys are granted a broad default set (20 scopes) that reaches every ordinary product surface. Only three scopes stay opt-in: `keys`, `browser:execute`, and `connection:read`. - `GET /v1/keys` and `DELETE /v1/keys/{key_id}` are **scoped to the calling key's own mode**. A sandbox (`sk-coasty-test-*`) key lists and revokes only sandbox keys; a live key sees live and legacy keys. A cross-mode `key_id` returns `404 KEY_NOT_FOUND`, exactly like an unknown id, so it cannot be used to probe for the existence of live keys. Each list item carries `key_kind` (`live` / `test` / `legacy`). - Both routes return `503 DB_UNAVAILABLE` with `Retry-After` on a key-store outage, never a bare 500. ### Test vs live keys | Prefix | Kind | Bills your wallet? | | --- | --- | --- | | `sk-coasty-live-<48 hex>` | live | Yes | | `sk-coasty-test-<48 hex>` | test (sandbox) | No (free) | | `cua_sk_<48 hex>` | legacy (accepted through 2026-11-01) | Yes | Test keys (`sk-coasty-test-*`) use the same wire schemas and sandbox-supported validation paths as live keys but **never debit your wallet**. Stored BYOK key management is intentionally live-only: test keys receive `403 FORBIDDEN` and cannot read, overwrite, or delete the production credential store. Responses from test keys carry `X-Coasty-Test-Mode: true` and `X-Credits-Charged: 0`. The `X-Coasty-Key-Kind` response header reports which family authenticated (`live`, `test`, or `legacy`). ### Billing model (USD) Your developer wallet is a **prepaid USD balance** (denominated in cents). Costs are counted in **credits, and 1 credit = 1 cent = $0.01 exactly** — Developer API wallet `credits_charged` / `total_credits` fields use that unit. The explicit exception is `ScheduleRunRecord.credits_charged`: it reports consumer subscription-credit quota units for non-Unlimited scheduled execution, not USD cents, and must not be converted at $0.01 per credit. Direct metered inference charges reserve funds before the model call. A conclusive server-side inference failure submits a refund; treat it as complete only when `X-Credits-Refunded` is present. An unconfirmed refund returns `503 BILLING_UNAVAILABLE` as described above. Documented post-dispatch outcome-unknown operations are not blindly refunded. Machines additionally bill an hourly runtime rate, metered per minute. See the Pricing table in the Reference section for exact costs. --- ## 2. Quickstart ### Step 1: get a key Create a key at https://coasty.ai/developers/keys and export it: ```bash export COASTY_API_KEY="sk-coasty-live-..." ``` ### Step 2: your first prediction ```bash # screen.png is a screenshot of the screen you want to control SCREENSHOT=$(base64 < screen.png | tr -d '\n') curl -s https://coasty.ai/v1/predict \ -H "X-API-Key: $COASTY_API_KEY" \ -H "Content-Type: application/json" \ -d @- < v5, the default and latest engine "max_steps": 150, # this IS the default; raise it for longer work "on_awaiting_human": "pause", }, timeout=30, ).json() run_id = run["id"] webhook_secret = run.get("webhook_secret") # create/replay response only; store it now while run["status"] not in TERMINAL: time.sleep(2) run = requests.get(f"{BASE}/runs/{run_id}", headers=HEADERS, timeout=30).json() print(run["status"], run["steps_completed"], "steps") print(run["result"]) # {"passed", "status", "summary", "usage", "verdict"?} # summary is the LAST 2000 chars of the trajectory. For the full trajectory: log = requests.get(f"{BASE}/runs/{run_id}/log", headers=HEADERS, timeout=30).json() print(log["steps_completed"], "steps,", log["steps_logged"], "logged") ``` --- ## 3. Core endpoints ### CUA versions `cua_version` selects the engine. Pass it on `/v1/predict`, `/v1/sessions`, and `/v1/runs`. | Version | Description | Avg step | Tiers | | --- | --- | --- | --- | | `v1` | Baseline: single action per call, reflection, 8-screenshot trajectory | 9-10s | all tiers | | `v3` | Lean: multi-action per call, no reflection, aggressive compaction | 3.5-4s | all tiers | | `v4` | Autonomous + verifier (pass/fail, recovery, exploration, cost governor) | varies | all tiers | | `v5` | Latest (default): autonomous + verifier with improved grounding and recovery | varies | all tiers | `v5` is the **default** when you omit `cua_version`, and `v1` / `v3` / `v4` / `v5` are all supported on every tier. ### Prompt steering: instructions vs system_prompt - `instructions` (string, optional): extra guidance **APPENDED** to the built-in CUA system prompt. Use this to steer behaviour while keeping the base prompt. - `system_prompt` (string, optional): a custom prompt that **REPLACES** the base agent prompt (on runs it takes priority as a preamble). May be combined with `instructions`, which is appended after the replacement. - Both are available on **every tier, including free**. There is no per-tier prompt ladder: the developer API is prepaid, so your credit balance, not your tier, is what bounds what you may do. - The budget is **32,000 characters SHARED between the two fields**, not 32,000 each. The server computes `len(system_prompt) + len(instructions)` and returns `400 INPUT_TOO_LARGE` when the sum exceeds it. The request schema independently accepts up to 32,000 for `system_prompt` and 16,000 for `instructions`, so a body that passes schema validation can still be rejected by the shared budget at 48,000 combined. Size the pair together. - Long prompts are priced, not gated: `/v1/predict` and session predict add +$0.01 (1 credit) when `system_prompt` plus trimmed `instructions` exceeds 500 characters. Run and workflow steps carry no prompt surcharge. --- ### POST /v1/predict Stateless action prediction. Scope: `predict`. Send a screenshot plus an instruction, get an ordered list of actions back. You manage trajectory. **Price:** $0.05 base (5 credits) per call, plus exact surcharges: +$0.02 (2 cr) per `trajectory` screenshot you attach, +$0.01 (1 cr) per HD image (width > 1280 or height > 720 — charged on the current screenshot and each trajectory screenshot), +$0.03 (3 cr) when `cua_version` is `v1`, and +$0.01 (1 cr) when the combined length of `system_prompt` plus trimmed `instructions` exceeds 500 characters. The task `instruction` is not counted. A conclusive failure after a wallet debit submits a refund; only `X-Credits-Refunded` confirms settlement. **Idempotency:** this endpoint honors the `Idempotency-Key` request header. A replay returns the original response with `X-Coasty-Idempotent-Replay: true` and bills 0 (the cached result is served without a second model call). **Request body** | Field | Type | Req | Default | Notes | | --- | --- | --- | --- | --- | | `screenshot` | string | yes | - | A static PNG/JPEG as raw base64 or exact `data:image/png;base64,` / `data:image/jpeg;base64,` URI. Payload must be 100-10,485,760 chars; declared MIME must match the decoded bytes. All images plus JSON share the 15 MiB request-body cap. | | `instruction` | string | yes | - | Natural language task. Must be non-empty. | | `cua_version` | string | no | `v5` | `v1` / `v3` / `v4` / `v5`. | | `model` | `"default"`\|null | no | null | Managed model alias. For a specific BYOK model, use `llm.model`. | | `system_prompt` | string\|null | no | null | REPLACES the base prompt. | | `instructions` | string\|null | no | null | APPENDED to the base prompt. | | `screen_width` | int\|null | no | measured from the screenshot when omitted | 320-3840 when set. Supply with `screen_height`, or omit both. | | `screen_height` | int\|null | no | measured from the screenshot when omitted | 240-2160 when set. Supply with `screen_width`, or omit both. | | `trajectory` | array | no | [] | Up to 19 prior steps: `[{screenshot, screen_width?, screen_height?, actions, reasoning}]`. Per-step dimensions are paired and default to that frame's decoded size. JPEG-compress or downscale prior frames so the complete JSON body remains at or below 15 MiB. | | `max_actions` | int | no | 5 | 1-10. Capped to your tier max. | | `tools` | string[]\|null | no | null | Allowed action types (null = all). | | `action_policy` | object\|null | no | null | Fail-closed post-model enforcement for allowed/blocked actions, blocked keys/window close, action count, and coordinate bounds. The complete proposed batch is checked atomically. | | `include_reasoning` | bool | no | true | Include the agent's reasoning. | | `include_raw_code` | bool | no | true | Include a canonical pyautogui debug representation generated from the validated structured actions. It is never the model's original text. When false, code is cleared before storage/response: top-level `raw_code` is `[]` and each action's `raw_code` is `""`. | **Response** (`PredictResponse`) ```json { "request_id": "req_8f2c1e9a", "status": "continue", "reasoning": "The login form is visible. I'll click the email field, then type the address.", "actions": [ { "action_type": "click", "params": { "x": 512, "y": 340, "button": "left", "clicks": 1 }, "description": "", "raw_code": "pyautogui.click(512, 340, clicks=1, button='left')" }, { "action_type": "type_text", "params": { "text": "you@example.com" }, "description": "", "raw_code": "pyautogui.write('you@example.com')" } ], "raw_code": ["pyautogui.click(512, 340, clicks=1, button='left')", "pyautogui.write('you@example.com')"], "cua_version": "v5", "screen_width": 1920, "screen_height": 1080, "usage": { "input_tokens": 1523, "output_tokens": 245, "credits_charged": 6, "cost_cents": 6, "breakdown": [ { "item": "base", "credits": 5 }, { "item": "hd_images", "credits": 1, "count": 1 } ] } } ``` `status` is one of `continue`, `done`, `fail`. Each action object is `{ action_type, params, description, raw_code }`. The structured `action_type` + `params` pair is authoritative. When requested, `raw_code` is regenerated from that sanitized pair; the API never echoes arbitrary model source or a recognized command with an unparsed suffix. Treat it as a debug aid, not executable input. `usage.cost_cents` is the USD cost in cents. `screen_width` / `screen_height` **echo the dimensions the server actually used** for this call — i.e. the coordinate space the returned action `(x, y)` are expressed in (the screenshot's true size when you omit them). Echoing them removes the coordinate-scaling guesswork: you no longer have to assume which space the coordinates are in. `cua_version` echoes the CUA engine version that served the call (e.g. `"v5"`). `usage.breakdown` is the **per-call cost breakdown** that makes the charge self-auditable: an ordered list of `{ item, credits, count? }` lines whose `credits` **sum to `credits_charged`**. `item` is one of `base`, `trajectory`, `hd_images`, `engine`, `custom_prompt`; `count` is an optional multiplier (e.g. the number of HD screenshots billed) and is omitted where it adds nothing. `breakdown` is `null` (omitted) on free / test / no-charge calls (and on `/v1/parse`, which never bills); when present, the lines always reconcile to the total. **Coordinate contract.** Every `(x, y)` in `actions` is in the **pixel space of the screenshot you submitted**, with a **top-left origin** at `(0, 0)` and **no normalization** (coordinates are never 0..1 or percentage-scaled). The response echoes the `screen_width` / `screen_height` the server used; when you omit those fields the server **measures the screenshot's true size**, so the returned `(x, y)` are always in the space of the exact image you sent. Click those pixels directly (or scale by the echoed dims if you resized between capture and click). **Latency & recommended timeouts.** A stateless `/v1/predict` (on `v3` / `v4` / `v5`) is a **single model call** — typically a few seconds up to ~30s. A session `predict` (`/v1/sessions/{id}/predict`) runs **multiple serial model calls** and can take longer; a heavy step can run up to **~300s** server-side. But any single **synchronous** HTTP response is bounded by the **~100s edge timeout**, so for the longest steps either: - set a **client timeout of at least 120s** (not the old 60s) on predict / session-predict, **or** - use the **SSE-keepalive** mode below (the connection is held open with comment frames), **or** - use the asynchronous **runs** API (`/v1/runs`) for long autonomous work. **SSE-keepalive predict (opt-in).** On `POST /v1/predict` and `POST /v1/sessions/{id}/predict`, send `Accept: text/event-stream` (or add `?stream=keepalive` to the URL) and the result comes back as **Server-Sent Events** instead of one JSON body. While the model is inferring, the server emits `: keepalive` comment frames (about every **15s**) so the edge timeout never cuts the connection, then a terminal `event: result` whose `data:` is the same `PredictResponse` / `SessionPredictResponse` JSON. On failure the terminal frame is `event: error` with `data:` set to the standard error envelope. ``` : keepalive : keepalive event: result data: {"request_id":"req_8f2c1e9a","status":"done","actions":[...],"usage":{...}} ``` **Without the Accept header** (no `Accept: text/event-stream`, no `?stream=keepalive`) the response is unchanged — plain JSON, exactly as documented above. Use the SSE mode only for long steps. **curl** ```bash SCREENSHOT=$(base64 < screen.png | tr -d '\n') curl -s https://coasty.ai/v1/predict \ -H "X-API-Key: $COASTY_API_KEY" \ -H "Content-Type: application/json" \ -d @- < fresh screenshot + instruction -> DELETE session ^ | | act + observe| +--------------+ ``` #### 60-second reliable-loop checklist | Step | What to do | | --- | --- | | **1. Create** | Create one session for this flow run. Send short immutable rules, tools, model choice, and `action_policy` once. | | **2. Request** | Send a fresh screenshot plus one observable micro-goal, its expected screen, and an explicit completion condition. | | **3. Act** | Validate structured actions, reject prohibited input, then execute the admitted batch. Never evaluate `raw_code`. | | **4. Observe and verify** | Capture a fresh screenshot. Verify Save, navigation, modal transitions, irreversible operations, and completion. | | **5. Finish** | Delete the session. Start a new session before another patient, task, or run; reset only for deliberate same-config reuse. | 1. Create one session for one concrete flow instance. Put short immutable rules in create-time `instructions` (available on every tier, including free). `instructions` appends to Coasty's tuned prompt; `system_prompt` replaces it, so prefer `instructions` unless you intentionally own the whole prompt. 2. Send only the current observable micro-goal in each `POST /v1/sessions/{id}/predict` body, together with the latest screenshot. The per-turn schema accepts only `screenshot`, `instruction`, `include_reasoning`, and `include_raw_code`. Re-sending rules, model, tools, `action_policy`, or BYOK fields as extra per-turn fields returns `422 VALIDATION_ERROR`. 3. While that micro-goal is unfinished, repeat only the same short goal and observable completion condition. Do not repeat a large workflow description on every turn. After the state is verified, send the subsequent micro-goal. 4. `status: "done"` ends the current model loop; it does **not** close the session. Delete in `finally` to free quota. 5. Before another patient, task, or run, delete and create a new session for the cleanest execution boundary. `reset` is available for deliberate same-config reuse, but it is not a new resource: it clears trajectory while preserving session configuration, BYOK binding, cumulative usage, and operation replay history. Use new step `Idempotency-Key` values after a reset. Deleting a session is execution cleanup, not a data-erasure or regulated-data retention control. It removes the active trajectory and releases the concurrency slot; idempotency/replay, metering, audit, and model-provider records follow their own retention settings. Before sending patient, financial, or other regulated data, confirm that your Coasty agreement, selected model provider, region, logging settings, and retention configuration meet your requirements. Use the applicable privacy/export/erasure controls for data-rights requests. Custom `instructions` / `system_prompt` are available on every tier, including free, against a shared 32,000-character budget. If a deployment has explicitly configured a tier's budget to 0, the fields return `400 FEATURE_NOT_AVAILABLE`; in that case rely on the built-in prompt and keep each micro-goal self-contained. `action_policy` is a separate enforcement control and is not part of the custom prompt budget; set invariant constraints once at session creation. Session create and session predict are reserve-and-replay operations. Generate the `Idempotency-Key` before the first send, serialize the body once, and retain both. After transport loss, resend only the same key with the identical method, path, body, and BYOK identity; reconcile an ambiguous outcome with `GET /v1/idempotency/{key}` before starting a new operation. Session DELETE has no generic replay record. If its response is lost, `GET /v1/sessions/{id}` is authoritative: 404 confirms cleanup; 200 means the session still exists and a bounded DELETE retry is allowed. #### Recommended micro-goal prompt format ```text Immutable rules (send once in session instructions): - Never press Escape or close the Group Note window. - Paste only with one Ctrl+V chord after focus is visible. Micro-goal A (send now): Goal: focus the Group Note body. Expected screen: the caret or focus highlight is visible in the note body. [done] when: note-body focus is visible. Micro-goal B (send only after A is verified): Goal: paste the clipboard once with one Ctrl+V chord. Expected screen: the note body visibly contains the pasted text. [done] when: the pasted text is visible in the note body. ``` The four parts have separate jobs: - **Short immutable rules:** stable safety and data-entry constraints. Send them once at session creation, not with every screenshot. - **One observable micro-goal:** one state transition the current screen can support. Do not ask one turn to open a patient, edit a note, save it, and navigate elsewhere. - **Expected screen:** the concrete visual state that should follow the action. - **Explicit completion condition:** one visible fact that permits the model to claim completion. `[done] when:` is an optional human-readable prompt convention. It is not API syntax or part of the wire protocol. #### Completion: prompt label, action, status, and client verification - The API does not parse `[done]` in the instruction and prompt text alone never completes a step. - The authoritative loop-control field is `response.status`: `"continue" | "done" | "fail"`. - A terminal action may also be present as `{"action_type":"done","params":{}}`. It has no OS effect. A valid response with `status: "done"` is not guaranteed to include that action, so do not search for an action or a literal string instead of reading `status`. - The model returns done when it believes either the observed screenshot already satisfies the completion condition or the proposed action batch will produce the requested result. This is a model claim, not durable proof of an application write. v5 has internal evidence checks, but clients must not use them as their business transaction boundary. - If a response contains Save (or another mutation) and done together, the screenshot necessarily predates that mutation. Execute the allowed mutation, capture a fresh screen, and verify before accepting completion. In plain English: `[done]` tells the model what visible condition to look for; `status: "done"` tells your loop what the model claimed; a fresh screenshot plus your own application-state check decides whether the real task succeeded. #### Act -> Observe -> Verify ```text ACT (policy-approved input) -> OBSERVE (wait for UI, capture a fresh screenshot) -> VERIFY (does the expected state exist?) yes -> advance / accept completion no -> describe the mismatch and re-plan from this screenshot ``` Verify after Save/submit, navigation, modal transitions, irreversible operations, and task completion. Prefer an application-specific DOM/API/state assertion when one exists, especially for irreversible actions. Avoid a verbose verification call after every harmless deterministic keystroke such as Tab in a stable form; that adds latency and distracts the model. Concise verification prompt: ```text Verify only whether the Group Note was saved. Expected screen: the Group Note window is closed and the saved note is visible in the patient's Chart. [done] when: both conditions are visible. Otherwise return fail and describe the mismatch. Do not click or type. ``` Long verification prompts increase latency and model distraction. Verification is observation-only. If the model proposes a click or key anyway, reject it in the client and verify again from the current screen. #### Server-enforced action policy Prompt text explains intent to the model. The optional `action_policy` is the fail-closed enforcement boundary: Coasty checks the complete normalized action batch after model generation and before returning or dispatching any action. If one action violates policy, none of that batch is admitted. Omission preserves the unrestricted compatibility behavior. ```json { "action_policy": { "blocked_keys": ["escape"], "block_window_close": true, "max_actions": 5 } } ``` | Field | Contract | | --- | --- | | `allowed_actions` | Optional allowlist of 1-128 normalized action names. Terminal control signals `done`, `fail`, and `awaiting_human` remain available. | | `blocked_actions` | Denylist of up to 128 names; it cannot overlap `allowed_actions`. | | `blocked_keys` | Up to 128 case-insensitive key names inspected in `key_press`, `key_combo`, and modifier-bearing actions. `esc` aliases `escape`. | | `block_window_close` | Blocks explicit close-window/tab/browser actions and common close shortcuts including Alt+F4, Ctrl/Cmd+W, and Cmd+Q. | | `max_actions` | 1-10,000. Maximum actions admitted in one Predict/Session response or Parse/direct Machine batch; cumulative across a Task, Workflow task tree, or Schedule firing including nested delegation. | | `coordinate_bounds` | Inclusive `min_x`/`min_y`/`max_x`/`max_y` rectangle checked for click/move/scroll anchors and both drag endpoints. | Supported request surfaces are `POST /v1/predict`, `POST /v1/sessions` (fixed for every turn), `POST /v1/parse`, direct machine `/actions` and `/actions/batch`, Task Run creation, saved or ad-hoc Workflow Run creation, and Schedule creation. Task and Workflow policies are atomically pinned with their run rows; a Schedule policy is immutable after create. Autonomous paths preserve it through retries, worker recovery, task steps, and nested CUA delegation. A key/window/coordinate policy rejects raw or otherwise uninspectable code rather than guessing that it is safe. Action names are surface-specific. Inference and Parse policies use prediction action names such as `type_text`; direct machine action policies use command names such as `type`. Copy names from the action catalog for the endpoint you are calling. Enforcement occurs after inference. Rejected output is never returned as executable work or dispatched, but the provider request already happened, so normal managed or BYOK token charges and usage logging still apply. Session, Task Run, Workflow Run, and Schedule responses do not echo the normalized `action_policy`. A successful create confirms acceptance, but retain the exact submitted policy (or a hash) in your client audit log and keep the client-side guard active during recovery. Failure shape depends on the surface: - Predict and Sessions return a normal terminal `status: "fail"` plus a `fail` action whose params include `code: "ACTION_POLICY_VIOLATION"`, `rule`, and `message`. - Parse and direct machine action/batch requests return `422 ACTION_POLICY_VIOLATION` with the same structured context. - Autonomous Task, Workflow task, and Schedule firing violations fail the active run before dispatch and surface `ACTION_POLICY_VIOLATION` through the run error/event lifecycle. Creation succeeds because the rejected action is produced later during execution. `action_index` and `action_type` are included only when the violation is attributable to one proposed action. Batch-level rules such as `max_actions` omit both fields. Handle `ACTION_POLICY_VIOLATION` before a generic terminal-failure branch. Execute nothing from that batch, capture a fresh screenshot, and either send short control feedback to the same session with a new `Idempotency-Key` or stop for human review. This is the recovery exception to ordinary `status: "fail"` handling. Treat screenshots and on-screen text as **untrusted model input**. Visual prompt injection can ask the model to ignore the task or click a destructive control. Action policy constrains the action shape; it cannot know whether a permitted click is semantically safe. For sensitive work, the client should also pin the expected machine, application/window, and domain, and require an authoritative state precondition or human approval before destructive operations. #### Escape-loop troubleshooting **Important:** prompt prohibitions are advisory, not enforcement. A model or recovery strategy can still propose Escape to dismiss a suspected modal or clear focus. Create the session with `action_policy: {"blocked_keys":["escape"],"block_window_close":true}` for server enforcement, then retain this client check as defense in depth: 1. Inspect structured `action_type` + `params`; never evaluate `raw_code`. 2. Reject any `key_press` or `key_combo` whose normalized keys contain `"escape"` or `"esc"`. **Do not execute it.** 3. Capture a fresh screenshot. The screenshot is the authoritative statement that the rejected input did not run. 4. Send the rejection to the **same session** as the next short instruction, using a **new** `Idempotency-Key` because the body changed: ```json { "screenshot": "", "instruction": "CONTROL FEEDBACK: the previous key_press([escape]) was rejected and NOT executed. The current screenshot is authoritative. Continue without Escape. Use one key_combo([ctrl,v]) only after focus is visibly in the note body." } ``` Reuse the old idempotency key only for a byte-equivalent transport retry of the original request. Reusing it with feedback or a new screenshot returns `422 IDEMPOTENCY_KEY_REUSED`. The create-time `tools` allowlist can remove the entire `key_press` action class, but it cannot ban only Escape while retaining Tab/Enter. If the same policy violation is proposed three times, stop the paid loop and escalate or reset instead of retrying without a bound. --- ### POST /v1/ground Resolve a natural language description of an element to exact `(x, y)` pixel coordinates. Scope: `ground`. **Price:** $0.03 (3 credits) per call, +$0.01 (1 credit) if the screenshot is HD (width > 1280 or height > 720). **Idempotency:** this endpoint honors the `Idempotency-Key` request header. A replay returns the original response with `X-Coasty-Idempotent-Replay: true` and bills 0 (the cached coordinates are served without a second model call). **Request body** | Field | Type | Req | Default | | --- | --- | --- | --- | | `screenshot` | string | yes | - | | `element` | string | yes | - | | `screen_width` | int\|null | no | measured from the screenshot when omitted (320-3840 when set) | | `screen_height` | int\|null | no | measured from the screenshot when omitted (240-2160 when set) | **Response** (`GroundResponse`): ```json { "x": 512, "y": 340, "screen_width": 1280, "screen_height": 720, "usage": { "credits_charged": 3, "cost_cents": 3, "breakdown": [ { "item": "base", "credits": 3 } ] } } ``` `screen_width` / `screen_height` **echo the dimensions the server actually used** — the coordinate space the returned `(x, y)` are in (the screenshot's true size when you omit them), so there is no coordinate-scaling guesswork. `usage.breakdown` is the same self-auditable `[{ item, credits, count? }]` cost list as `/v1/predict` (summing to `credits_charged`; `null` on a free / test call). ```bash curl -s https://coasty.ai/v1/ground \ -H "X-API-Key: $COASTY_API_KEY" \ -H "Content-Type: application/json" \ -d "{\"screenshot\":\"$SCREENSHOT\",\"element\":\"the blue Submit button\"}" ``` --- ### POST /v1/parse Turn raw pyautogui code into structured actions. Deterministic, no model call, and **free**. Scope: `parse`. **Request body** | Field | Type | Req | Notes | | --- | --- | --- | --- | | `code` | string | yes | Non-empty, under 50,000 chars. | | `action_policy` | object\|null | no | Validate parsed structured actions with the same fail-closed policy. A violation returns `422 ACTION_POLICY_VIOLATION`. | **Response** (`ParseResponse`): `{ "actions": [ { action_type, params, ... } ] }`. ```bash curl -s https://coasty.ai/v1/parse \ -H "X-API-Key: $COASTY_API_KEY" \ -H "Content-Type: application/json" \ -d '{"code": "pyautogui.click(100, 200)"}' ``` --- ### GET /v1/models List available models, CUA versions, and action types. No body. ```json { "models": [ { "id": "default", "description": "Default model - balanced performance and cost" } ], "cua_versions": [ { "id": "v1", "description": "Baseline - single action per call, reflection enabled, 8-screenshot trajectory", "avg_step_time": "9-10s", "features": ["reflection", "single_action"], "managed_stateless_predict_mode": "full_pipeline", "latest": false }, { "id": "v3", "description": "Lean - multi-action per call, no reflection, aggressive compaction", "avg_step_time": "3.5-4s", "features": ["multi_action", "compaction"], "managed_stateless_predict_mode": "shared_fast_planner", "latest": false }, { "id": "v4", "description": "Autonomous - closed-loop verifier, recovery, exploration, cost governor", "avg_step_time": "3.5-4s", "features": ["multi_action", "verifier", "recovery", "exploration"], "managed_stateless_predict_mode": "shared_fast_planner", "latest": false }, { "id": "v5", "description": "Latency-first rebuild of v4; latest and default", "avg_step_time": "2-3s", "features": ["multi_action", "verifier", "recovery", "exploration", "concurrent_grounding"], "managed_stateless_predict_mode": "shared_fast_planner", "latest": true } ], "action_types": ["click", "type_text", "key_press", "key_combo", "scroll", "drag", "move", "wait", "done", "fail"], "machine_action_commands": ["arrange_windows", "browser_click", "browser_close", "browser_close_tab", "browser_execute", "browser_get_clickables", "browser_get_dom", "browser_info", "browser_list_tabs", "browser_navigate", "browser_open", "browser_open_tab", "browser_screenshot", "browser_scroll", "browser_state", "browser_switch_tab", "browser_type", "browser_wait", "click", "click_with_modifiers", "close_window", "directory_delete", "directory_list", "double_click", "drag", "file_append", "file_delete", "file_download", "file_edit", "file_exists", "file_list_downloads", "file_read", "file_write", "key_combo", "key_press", "list_windows", "maximize_window", "minimize_window", "move", "move_window", "restore_window", "screenshot", "scroll", "switch_to_window", "terminal_clear", "terminal_close", "terminal_connect", "terminal_execute", "terminal_read", "type"], "pricing": { "value_kind": "effective_runtime", "published_defaults_path": "/api/pricing", "currency": "usd", "credit_usd_cents": 1, "base_fees_credits": { "predict": 5, "session_create": 10, "session_predict": 4, "ground": 3, "parse": 0 }, "surcharges_credits": { "trajectory_screenshot_each": 2, "high_resolution_image_each": 1, "v1_engine_per_request": 3, "long_system_prompt_per_request": 1 }, "long_system_prompt_threshold_chars": 500, "run_step_credits": { "v1": 8, "v3": 5, "v4": 5, "v5": 5 }, "workflow_task_step_credits": { "v1": 8, "v3": 5, "v4": 5, "v5": 5 }, "schedules": { "per_fire_credits": 0, "minimum_wallet_balance_cents": 20, "webhook_minimum_wallet_balance_cents": 20, "webhook_default_rate_limit_per_minute": 60, "webhook_replay_window_seconds": 300, "webhook_dedup_window_seconds": 60, "webhook_max_body_bytes": 1000000, "execution": { "balance_source": "subscription_credits", "credits_per_minute": 10, "minimum_balance_credits": 20, "billing_rounding": "ceil_billable_minutes", "billing_session_max_duration_seconds": 21600, "scheduler_timeout_seconds": 21600, "credit_meter_applies_to": "non_unlimited_accounts", "unlimited_credit_meter_bypass": true } }, "test_keys_bill": false } } ``` `managed_stateless_predict_mode` is intentionally explicit. With a managed key, `/v1/predict` on v3/v4/v5 uses the same low-latency, single-call planner; v1 uses its full pipeline. Stateful sessions, Runs, Workflow task steps, and BYOK predictions use the selected version's full engine. This prevents a client from assuming that selecting v4/v5 adds stateful verifier passes to a one-shot managed prediction. The legacy-named `long_system_prompt_threshold_chars` pricing field applies to the combined `system_prompt` plus trimmed `instructions` length on Predict and Session Predict. Exactly the reported threshold is free; the task `instruction` is not part of that surcharge. `action_types` is the CUA screenshot-prediction output vocabulary. `machine_action_commands` is the separate, exact 50-command allowlist accepted by direct Machine action requests and batch steps. It is sorted for stable diffing; use the OpenAPI `ActionRequest.oneOf` discriminator for each command's strict parameter schema. `pricing.value_kind = "effective_runtime"` means these values came from the running backend process, including supported operator overrides. The public `GET /api/pricing` snapshot and frontend tables publish checked-in defaults; use `GET /v1/models` when a budget guard needs the deployed values. Managed schedule dispatch is free but requires the reported API-wallet minimum, then uses the separately funded subscription-credit balance. BYOK schedules bypass both Coasty billing gates and report zero credits. Managed billing rounds billable minutes up and is bounded by the reported scheduler timeout. Startup rejects a scheduler timeout longer than the billing-session safety ceiling, preventing an unbilled execution tail. ### GET /v1/usage Usage summary for a billing period. Optional query param `period` (`YYYY-MM`, defaults to the current month). ```json { "period": "2026-06", "total_requests": 128, "total_credits": 540, "total_cost_cents": 540, "breakdown": { "predict": { "requests": 100, "credits": 500 } }, "balance": 9300, "wallet_balance_cents": 9300, "wallet_balance_usd": 93.0 } ``` `balance` / `wallet_balance_cents` is the prepaid USD wallet balance in cents. ### Bring your own model (BYOK) By default every LLM call in the computer-use harness runs on Coasty's managed models. With a live Coasty key, BYOK flips that: opt in and the **entire harness** — the worker, grounding, the code agent, and compaction; every LLM call — runs on your own Anthropic or OpenAI key instead. Opt-in is always explicit, per request or per stored key. `llm.provider: "managed"` (or omitting `llm` entirely) keeps the platform default, unchanged. The test-key boundary is narrower and is specified below. **The core promise: no silent fallback.** Once a request asks for BYOK, no code path can use Coasty's platform LLM keys. Local provider/model/key validation uses stable `LLM_*` codes. Provider authentication, quota, rate-limit, connection/timeout, and server failures are classified into the stable provider codes below. Other provider client rejections can use the endpoint's ordinary failure code, but they still never trigger platform fallback. **Stored keys.** Managed with three endpoints, all gated by the `llm_keys` scope (granted to new live keys by default). These endpoints require a live Coasty API key; sandbox keys cannot touch the production credential store: | Endpoint | Purpose | | --- | --- | | `PUT /v1/llm/keys/{provider}` | Store (upsert) your key. Body `{"api_key": "sk-..."}`. Returns `200 {provider, key_fingerprint, stored: true}` — the key is never returned again. | | `GET /v1/llm/keys` | List stored keys: `{keys: [{provider, key_fingerprint, created_at, updated_at}]}`. Non-secret metadata only. | | `DELETE /v1/llm/keys/{provider}` | Delete the stored key. `{deleted: true}`, or `404 LLM_KEY_NOT_FOUND` when none exists. | **Key-store outages are 503, not 422.** `GET /v1/llm/keys` and `DELETE /v1/llm/keys/{provider}` return `503 DB_UNAVAILABLE` with `Retry-After` when the stored-key service is unreachable, rather than a bare 500. Your stored keys are unchanged; retry shortly. The same distinction holds on the **execution** path. When a run, predict, or session resolves your stored key and the key **store** is down, you get `503 DB_UNAVAILABLE` with `Retry-After`, not `422 LLM_KEY_INVALID`. This matters: `LLM_KEY_INVALID` is emitted as `retryable: false`, so labelling a storage outage that way told a correct client "your key is bad, stop retrying" and made it rotate a working credential for nothing. - `503 DB_UNAVAILABLE`: the store is unavailable. **Retry.** Your key is fine. - `422 LLM_KEY_INVALID`: the credential itself is unusable (empty, malformed, wrong provider's format, or a stored envelope that could not be decrypted). **Do not retry.** Re-store it. Keys are AES-256-GCM encrypted at rest and authenticated to the tenant+provider row identity; only a sha256-prefix `key_fingerprint` of exactly 12 lowercase hexadecimal characters is ever echoed. A legacy unbound stored envelope is fingerprint-checked and atomically upgraded before plaintext can reach a provider. Use an `sk-coasty-live-*` key as `COASTY_API_KEY` for intentional production BYOK execution and stored-key management. **Test-key boundary.** With a test Coasty key, explicit BYOK is provider-direct only for the direct CUA flow: `POST /v1/predict`, `POST /v1/ground`, `POST /v1/sessions`, and `POST /v1/sessions/{id}/predict`. Predict, ground, and session create require an explicit per-request `X-LLM-Api-Key` (plus `X-LLM-Provider`) under test auth. A body `llm.provider` without that header fails closed with `422 LLM_KEY_NOT_CONFIGURED` ("Stored provider keys are unavailable for test API keys. Send X-LLM-Api-Key explicitly for direct BYOK."): a test key never reads or uses a stored live provider key. Session creation fixes the explicit header key for inherited session predicts but makes no inference call and bills no provider tokens; the actual provider calls occur on predict, ground, and session predict. Those calls debit zero Coasty credits, but Anthropic/OpenAI can bill the supplied provider key. Task runs, both Workflow run starts, and schedules remain deterministic sandbox executions under a test Coasty key only in managed mode (`llm.provider: "managed"` or no BYOK intent). Supplying BYOK headers or provider metadata to those async endpoints fails before execution with `422 LLM_PROVIDER_UNSUPPORTED` ("BYOK is unavailable for synthetic test runs, workflows, and schedules. Use managed mode or a live Coasty API key.") instead of silently ignoring a provider secret. They never decrypt or require a stored provider key and do not call or bill Anthropic/OpenAI. Test keys also cannot access the production key store. Keep real provider secrets out of sandbox requests and CI fixtures, and use a live Coasty key when you intend real asynchronous Task, Workflow, or schedule execution. ```bash curl -s -X PUT https://coasty.ai/v1/llm/keys/anthropic \ -H "X-API-Key: $COASTY_API_KEY" \ -H "Content-Type: application/json" \ -d "{\"api_key\": \"$ANTHROPIC_API_KEY\"}" # -> {"provider": "anthropic", "key_fingerprint": "a1b2c3d4e5f6", "stored": true} ``` **LLM-backed operations.** A live Coasty key can use BYOK across every Developer API path that calls an LLM. Configuration enters through seven root categories: 1. `POST /v1/predict` 2. `POST /v1/ground` 3. `POST /v1/sessions` (every later `/sessions/{id}/predict` inherits it) 4. `POST /v1/runs` 5. `POST /v1/workflows/runs` (ad-hoc definition) 6. `POST /v1/workflows/{workflow_id}/runs` (saved workflow) 7. `POST /v1/schedules` (later run-now, due, webhook, and chain fires inherit it) This is a seven-category configuration inventory, not a claim that only seven HTTP operations exist. The session family also executes `POST /v1/sessions/{id}/predict`, and schedules execute through multiple fire paths. Parsing and direct machine actions do not call an LLM. They do not need BYOK. **BYOK headers.** Accepted on all seven start/create operations above: | Header | Meaning | | --- | --- | | `X-LLM-Provider` | `anthropic` or `openai`. Required whenever `X-LLM-Api-Key` is sent — a key without a provider is a `422`. | | `X-LLM-Api-Key` | Your provider credential on this request. A direct call uses it once; session create retains a fixed owner-process copy for inherited predicts; Run/Workflow creation snapshots it encrypted until terminal state; schedule create only validates it against the stored key used at fire time. Requires an effective Anthropic/OpenAI provider, takes precedence where execution is immediate, and is never logged or echoed. | | `X-LLM-Model` | Model selection for this operation. Sessions retain it for inherited predicts, Runs/Workflows snapshot it, and schedules persist the non-secret selection for later fires. Model ids use the documented 1-256-character safe grammar. Invalid syntax is `422 LLM_MODEL_INVALID`; the provider can still reject an unavailable model. | For schedules, execution happens later without request headers. Store the key first with `PUT /v1/llm/keys/{provider}`. A supplied header key is validation only and must match that stored key; the current stored key is resolved again at every fire. **Body param.** Those seven start/create operations accept an `llm` object. Inherited session-predict and schedule-fire requests do not accept a new `llm` selection; they use the configuration fixed by their parent resource: ```json { "llm": { "provider": "anthropic", "model": "claude-sonnet-5", "grounding_model": "claude-sonnet-5", "compaction_model": "claude-haiku-4-5", "code_agent_model": "claude-sonnet-5" } } ``` - `provider`: `managed` | `anthropic` | `openai`. Anything else is `422 LLM_PROVIDER_UNSUPPORTED`. `managed` cannot be combined with an `X-LLM-Api-Key`; omit the header for managed inference. - `model`: the main worker model. Defaults: anthropic → `claude-sonnet-5`, openai → `gpt-5.6-sol`. Model ids are 1-256 characters, begin with a letter or number, and then use only letters, numbers, dot, underscore, colon, slash, plus, at-sign, or hyphen. Invalid syntax is `422 LLM_MODEL_INVALID`; the provider can still reject an unknown or inaccessible model. It must be vision-capable. - `grounding_model` / `compaction_model` / `code_agent_model`: per-role overrides for tuning cost vs quality (e.g. a cheaper compaction model). Each defaults to `model`. - There is deliberately **no `api_key` field in the body** (`422` if attempted): keys ride headers or the encrypted store only, so they can never be echoed in run objects, webhooks, or idempotency replays. **Grounding caveat.** Grounding (pixel-coordinate resolution) quality is tuned on the platform model. When running grounding on your own model, expect the best results with the defaults, and use `grounding_model` to experiment. **Sessions.** `POST /v1/sessions` resolves the BYOK provider/key once and keeps that fixed create-time configuration in the owning process's memory; every later `POST /v1/sessions/{id}/predict` inherits it. Deleting or rotating the stored key does not revoke or update an active session. To stop further calls, `DELETE /v1/sessions/{id}` (or let it expire); provider-side revocation also stops the key upstream. **Runs and workflow runs.** With a live Coasty key, the key is snapshotted **encrypted** into the run, so crash-recovery on another replica keeps using YOUR key; its ciphertext is scrubbed the moment the run reaches a terminal state. Under a test Coasty key, BYOK intent is rejected with `422 LLM_PROVIDER_UNSUPPORTED` before any snapshot or execution; only managed-mode runs use deterministic sandbox execution. Run and workflow-run responses echo a non-secret `llm` block: `{provider, model, key_fingerprint, key_source, key_scrubbed}` (`key_source` is `"stored"` or `"header"`). **Schedules are different.** A live schedule stores and returns only its non-secret provider/model-role preference and key fingerprint, never a key, ciphertext, or key source. At fire time the CURRENT stored key is resolved. The schedule's provider/model-role preference is immutable: PATCH rejects `llm`, so delete and recreate the schedule to change that selection. Rotating the stored provider key is separate: the replacement takes effect on the next fire without recreating the schedule. The schedule's displayed fingerprint remains its creation-time reference; per-fire usage attribution records the key actually used. Delete that key and future live firings fail loudly with `LLM_KEY_NOT_CONFIGURED`; they NEVER silently run on platform keys. Managed-mode test-key schedules remain deterministic sandbox executions and do not resolve or call a provider; test-auth BYOK intent is rejected before schedule creation. The authenticated Coasty key id that created a BYOK schedule is retained only as internal usage attribution and is not added to the schedule response. Once a live firing produces a provider result, its terminal schedule transition and zero-credit, content-free token usage admission commit atomically; a deferred analytics projection remains in a service-only retry outbox instead of being silently dropped. Deletion stops future stored-key lookups, but it does not revoke the encrypted snapshot already held by an active live run or workflow. Cancel each active live execution to stop further provider calls; terminal transition then scrubs its ciphertext. **Billing.** A BYOK LLM operation debits **zero Coasty platform credits**. Provider-direct predict, ground, and session-predict responses report `usage.credits_charged: 0`, `usage.cost_cents: 0`, real provider token counts, non-secret attribution, and `usage.platform_cost_exempt: true`. Session create reports zero tokens because it configures the inherited provider key without making an inference call. `X-Credits-Charged` is also `0`. Live asynchronous run/workflow creation cannot report future tokens; terminal run results expose usage when execution produced it. Live schedule create, get, list, PATCH, pause, and resume responses expose the non-secret `llm` preference. Schedule run-history records deliberately omit `llm`, provider credentials, screenshots, prompts, and token totals. Anthropic or OpenAI bills actual tokens only when a provider-direct call occurs. Managed-mode test Tasks, Workflow task children, and schedules are sandboxed and produce no provider token charge. BYOK intent on those test-auth async endpoints is rejected with `422 LLM_PROVIDER_UNSUPPORTED` before execution. Managed requests keep the published Coasty prices. Machine, cloud, network, or third-party app costs you separately choose are not waived. **Screenshot → actions with your key.** Send the current PNG/JPEG as raw base64 or an exact data URI. Coordinates in returned actions use the echoed `screen_width` / `screen_height` space: ```bash # Anthropic (replace $SCREENSHOT_B64 with a base64 PNG/JPEG) curl -s https://coasty.ai/v1/predict \ -H "X-API-Key: $COASTY_API_KEY" \ -H "X-LLM-Provider: anthropic" \ -H "X-LLM-Api-Key: $ANTHROPIC_API_KEY" \ -H "Content-Type: application/json" \ -d "{\"screenshot\":\"$SCREENSHOT_B64\",\"instruction\":\"Click Continue\"}" # OpenAI: identical body; only the provider key/header changes curl -s https://coasty.ai/v1/predict \ -H "X-API-Key: $COASTY_API_KEY" \ -H "X-LLM-Provider: openai" \ -H "X-LLM-Api-Key: $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d "{\"screenshot\":\"$SCREENSHOT_B64\",\"instruction\":\"Click Continue\"}" ``` An immediate BYOK predict, ground, or session-predict response includes non-secret attribution only: `usage.llm_provider`, `usage.llm_model`, `usage.llm_key_fingerprint`, `usage.llm_key_source`, token counts, and `platform_cost_exempt: true`. The plaintext provider key is never returned. **Provider egress and audit storage.** When a provider-direct BYOK call occurs, Coasty transmits the prompt and screenshots to the Anthropic or OpenAI account you selected; that provider's data retention, training, region, and compliance settings are governed by your provider agreement/account. Test-key Task, Workflow, and schedule sandbox execution sends none of that content to the configured provider. Direct BYOK predict, ground, and session-predict now use a fail-closed durability boundary. Before provider egress, one transaction commits the exact caller instruction, optional custom `system_prompt` / `instructions`, selected CUA version, non-secret provider attribution, the input screenshot, and every direct-predict trajectory screenshot. If the user's screenshot-encryption preference is enabled, those screenshot payloads are stored as AES-256-GCM ciphertext at rest with authenticated tenant, operation, and screenshot-slot identity; when it is disabled, the exact base64 is retained for the account-lifetime audit. If the encryption preference cannot be resolved, opted-in encryption cannot be honored, or that transaction fails, the provider is not called. After inference, the schema-validated public response, returned actions, response-visible reasoning/canonical raw code, token counters, and final audit row are checkpointed before durable usage-outbox admission and idempotency completion. If usage admission fails after that checkpoint, retrying the same `Idempotency-Key` replays and settles the saved result without another developer-paid provider call. That no-recall guarantee is scoped to a stable operation identity. Send an `Idempotency-Key` on provider-direct predict, ground, and session-predict when you need retry safety. An identical retry with that same key is replayed or left safely quarantined; it never starts a second provider inference for the original operation. Without an `Idempotency-Key`, a later HTTP request is a **new operation** and may call and bill your provider again. Do not automatically retry an unkeyed `SETTLEMENT_INCOMPLETE` response; reconcile provider usage and observed machine state first. The provider boundary is deliberately conservative under an unobservable crash. Once the durable journal says `started`, the same operation identity is never sent to Anthropic/OpenAI again unless a completed session owner can prove it has an in-memory replay. If the process dies after `started` but before it can checkpoint the response, Coasty returns `503 SETTLEMENT_INCOMPLETE` (outcome unknown) for that operation identity. It cannot reconstruct the missing response or exact token counts, and it will not guess by calling the provider twice. Reconcile that rare case with the provider usage dashboard and observed machine state before choosing a new Idempotency-Key. Live BYOK Tasks, Workflow task steps, and schedule firings apply the same pre-egress principle immediately before each `agent.predict` CUA visual decision step: Coasty synchronously commits the exact pre-predict frame (the screenshot supplied to that decision), exact effective worker instruction (including injected environment context), and non-secret provider attribution under an attempt-scoped request id. One immutable `model_input_NNNN` frame is retained per CUA visual decision step (bounded to 1,000 steps and the existing 10 MiB encoded screenshot ceiling). Synchronous delegated employees inherit the same private callback but derive a deterministic tenant/root/delegation-path-bound child attempt identity and keep their own local frame sequence. Parent, sibling, nested-child, and retry rows cannot skip the audit lane, overwrite one another, or collide on local steps. Usage accounting separately aggregates token totals and per-call role data for worker, grounding, code-agent, compaction, and derived calls. That usage coverage does not mean the model-input audit copies every internal role prompt, system template, or provider payload. These rows reuse the same tenant-scoped, service-only `api_requests` / `api_screenshots` storage, account-lifetime retention, export, and deletion rules as direct CUA artifacts; no separate TTL is invented. When your screenshot-encryption preference is enabled, stored model-input payloads are AES-256-GCM ciphertext bound to the tenant/request/frame-slot identity; when disabled, their exact base64 is retained. If the preference cannot be resolved or opted-in encryption cannot be honored, the provider is not called for that step. Pixels never enter Task/Workflow events, webhooks, idempotency records, or application stdout. Coasty does not claim to store every internal provider-call prompt, the internal system-template transcript, or a raw full provider payload. **BYOK error codes** (all carry the standard envelope; full rows in the operational catalog): `LLM_KEY_NOT_CONFIGURED` (422), `LLM_KEY_INVALID` (422), `LLM_MODEL_INVALID` (422), `LLM_KEY_NOT_FOUND` (404), `LLM_PROVIDER_UNSUPPORTED` (422), `LLM_PROVIDER_AUTH_FAILED` (401), `LLM_PROVIDER_RATE_LIMITED` (429, retryable), `LLM_PROVIDER_QUOTA_EXCEEDED` (402), `LLM_PROVIDER_ERROR` (502, retryable). --- ## Idempotency Send an `Idempotency-Key` only on operations explicitly listed below (or marked `x-idempotency: reserve-and-replay` in OpenAPI). On those operations, a dropped connection, local timeout, or crash-and-retry cannot charge twice or create a duplicate resource. Other mutations, including machine start, stop, restart, TTL updates, deletes, cancels, resumes, and schedule updates, do **not** implement reserve-and-replay and must not be retried under that assumption. The key is a string you choose, up to 128 chars from `[A-Za-z0-9_-:]` (a UUID is ideal). For `POST /v1/tasks`, `POST /v1/runs`, and the Workflow run-start operations, this guarantee deduplicates **creation of the top-level run**. It does not make each GUI, terminal, browser, or file side effect performed later by that autonomous run transactional or exactly once. Design irreversible tasks with idempotent actions, durable checkpoints, a read-before-write verification step, and an explicit recovery boundary. ### Generic concrete-credential operations (exactly 19) - `POST /v1/predict` - `POST /v1/sessions` - `POST /v1/sessions/{session_id}/predict` - `POST /v1/ground` - `POST /v1/machines` - `POST /v1/machines/{machine_id}/snapshot` - `POST /v1/machines/{machine_id}/actions` - `POST /v1/machines/{machine_id}/actions/batch` - `POST /v1/machines/{machine_id}/browser/{op}` - `POST /v1/machines/{machine_id}/terminal` - `POST /v1/machines/{machine_id}/files/{op}` - `POST /v1/schedules` - `POST /v1/schedules/{schedule_id}/run` - `POST /v1/schedules/{schedule_id}/triggers` - `POST /v1/tasks` - `POST /v1/runs` - `POST /v1/workflows` - `POST /v1/workflows/runs` - `POST /v1/workflows/{workflow_id}/runs` ### Separate external-enrollment domain `POST /v1/machines/external` also **requires** `Idempotency-Key`, but its OpenAPI policy is `x-idempotency: account-enrollment-replay`. Enrollment keys are account-scoped (not concrete-credential scoped) so exact token-recovery replays survive owner API-key rotation. This domain is intentionally independent: the same literal key can coexist with a generic reservation without replaying it in either direction. Use a distinct key anyway for operational clarity. ### What counts as the "same request" Two calls are the same request when they carry the **same key, target the same operation, AND have the same body**. The fingerprint is a **SHA-256 of an explicit operation discriminator plus the canonical JSON request body** — the body re-serialized with **sorted keys** so whitespace and key order never matter. On BYOK-capable operations it also includes the effective provider, role models, and a one-way key fingerprint, so changing `X-LLM-*` headers under the same key returns `422` instead of replaying work created with another provider identity. The plaintext provider key never enters the fingerprint or replay record. For `POST /v1/sessions/{id}/predict` the path `session_id` is **folded into the hash** as well, so the same key reused across two different sessions is correctly treated as two different requests. Reusing a key with a **different operation or body** is a client error: `422 IDEMPOTENCY_KEY_REUSED`. Resend the original body to collect the cached result, or pick a new key. ### Key scope A key is scoped to the **concrete API-key credential and live/test mode**. Rotating or replacing an API key creates a new replay namespace; a result created by the old credential cannot be collected through the new one. Test mode is isolated from live. Within one credential, an idempotency key is global across supported operations: **never reuse the same key on another endpoint**, even for an identical JSON body — that returns `422 IDEMPOTENCY_KEY_REUSED`. External-machine enrollment is the deliberate exception. `POST /v1/machines/external` stores its required enrollment key at account scope, so an exact key/body replay can recover the one-time device token after the owner API key rotates, during the 24-hour recovery window. ### Replay & in-flight windows - **Completed result — 24 hours.** Once a request finishes, its result is cached and **replayable for 24 hours**. A replay returns the original response verbatim with `X-Coasty-Idempotent-Replay: true`, `Idempotency-Replayed: true`, and `Idempotency-Status: completed`. - **In-flight reservation — endpoint-derived.** Ordinary operations use a **10-minute default**. Long-running provision and action-batch operations size the reservation from their bounded execution budget so it cannot expire while work is still legitimate; every derived lease is clamped to a **6-hour safety ceiling**. Clients should follow `Retry-After`, not infer completion from a fixed lease duration. ### A keyed replay never double-bills A replay is served from the cache without a second model call, so it is **free**: - header `X-Credits-Charged: 0` - body `usage.credits_charged: 0` and `usage.billed: false` - headers `X-Coasty-Idempotent-Replay: true`, `Idempotency-Replayed: true`, `Idempotency-Status: completed` ### Wait-and-return (self-healing retry) If a keyed request arrives while the original with the **same key** is **still executing**, the server does not error — it **waits (up to ~25s)** for the original to finish and then returns that result as a replay. So a client that timed out locally and retried with the same key **transparently receives the result it already paid for**, instead of an error or a second charge. Only if the original is *still* running after that wait do you get `409 IDEMPOTENCY_IN_FLIGHT`. That response carries: ```json { "error": { "code": "IDEMPOTENCY_IN_FLIGHT", "message": "A request with this Idempotency-Key is still processing.", "type": "rate_limit_error", "request_id": "req_...", "retry_after": 2, "retryable": true, "retry_with_same_idempotency_key": true } } ``` plus a `Retry-After` header and `Idempotency-Status: processing`. **Retry with the SAME key** after `Retry-After` — a fresh key would start a second, separately billed operation. ### Fetch-by-key: GET /v1/idempotency/{key} If you lost or aborted the response (e.g. the process died after sending the request), collect a generic reserve-and-replay result by the key alone — no body, no endpoint, just the key. Authenticate with the **same concrete API-key credential and live/test mode** that created the reservation; a rotated key has a different namespace. External-machine enrollment is not stored in this generic cache: recover its one-time device token only by repeating the exact `POST /v1/machines/external` operation, key, and body during its 24-hour account-scoped recovery window. ```bash curl -s "https://coasty.ai/v1/idempotency/order-4821" -H "X-API-Key: $COASTY_API_KEY" ``` **Completed** -> `200` (header `Idempotency-Status: completed`): ```json { "status": "completed", "request_id": "req_8f2c1e9a", "result": { "...": "the original response body, verbatim" }, "original_status": 200 } ``` **Still running** -> `200` (header `Idempotency-Status: processing`): ```json { "status": "processing", "request_id": "req_8f2c1e9a" } ``` **Unknown / expired key** -> `404 NOT_FOUND`. ### Status headers summary - `Idempotency-Status`: `processing` (original still running) or `completed` (a cached result was returned). - `Idempotency-Replayed`: `true` on a replay, `false` on the original execution. --- ## Machines (managed or external) A **machine** is the stable execution target used by Tasks, Workflows, and schedules. `kind: "managed"` is a Coasty-hosted VM. `kind: "external"` is a customer-operated driver that supplies screenshots and executes fenced typed commands. Both kinds use the same `machine_id`. For a managed machine, you provision one, poll until it is `running`, then either hand it to a [task run](#4-task-runs) (the agent drives it) or drive it yourself with the control endpoints below. Machines are optional — `/predict`, `/sessions`, and `/ground` run against *your* screen; you need a machine when you want the agent to act on either a Coasty-hosted VM or an enrolled driver you operate. Scopes: `machines:read` (list/get/screenshot/pricing), `machines:write` (provision/lifecycle/TTL/terminate), `snapshots:write` (snapshot), and the opt-in `connection:read` (SSH key + VNC password). Managed provisioning, external enrollment, snapshot, actions, action batches, browser, terminal, and file operations belong to the exact reserve-and-replay set and accept `Idempotency-Key`; enrollment requires it. Lifecycle start/stop/restart, TTL updates, and termination do not. ### External machines: bring your own screen and action executor Enroll a caller-operated Windows, macOS, Linux, or other machine with: ```bash curl -X POST https://coasty.ai/v1/machines/external \ -H "X-API-Key: $COASTY_API_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "display_name": "support-laptop", "platform": "windows", "protocol_version": "1", "capabilities": ["screenshot", "mouse", "keyboard", "scroll"], "screen_width": 1920, "screen_height": 1080 }' ``` `screenshot` is required for Task/Workflow execution. The complete capability enum is `screenshot`, `mouse`, `keyboard`, `scroll`, `terminal`, `files`, and `browser`; advertise only behavior the driver really implements. `screen_width` and `screen_height` are optional but must be supplied together. Protocol version is the string `"1"`. Enrollment is owner-authenticated with `machines:write`, requires `Idempotency-Key`, returns HTTP `201`, and produces: ```json { "machine": { "id": "3e8af80d-7a7d-454a-baf5-9f635e6c962b", "display_name": "support-laptop", "kind": "external", "status": "running", "capabilities": ["screenshot", "mouse", "keyboard", "scroll"], "protocol_version": "1", "connection_status": "disconnected", "last_seen_at": null }, "device_token": "dvc_coasty_live_...", "fencing_token": 1, "request_id": "req_..." } ``` The response is `Cache-Control: no-store`. `device_token` is exposed only by this enrollment response (including an exact same-key/same-body recovery replay while the 24-hour replay secret remains available), is scoped to this one machine, and is never shown by list/get. Reusing the key with a different body conflicts. Store it in the OS secret store. The owner API key remains responsible for enrollment, list/get, Tasks, Workflows, schedules, and deletion. The driver endpoints below require `Authorization: Bearer $COASTY_DEVICE_TOKEN`; they do not accept the owner key. Never put either credential in a URL, metadata, logs, screenshots, run events, webhooks, or generated client code. Device authentication is protected by layered limits. Before a credential is trusted, malformed or rotating tokens share a peer bucket of 1,000 attempts per minute and 40,000 per hour. After authentication, each device token is limited to 300 requests per minute and 12,000 per hour, while all device tokens owned by one account share an aggregate 1,200 requests per minute and 48,000 per hour. Screenshot observations also have a per-token image-heavy limit of 60 per minute and 3,600 per hour. Honor the retry metadata on a 429 rather than spinning. #### Driver protocol 1. **Heartbeat** — `POST /v1/machines/{id}/heartbeat` with `{"protocol_version":"1","fencing_token":1}`. This updates `connection_status` and `last_seen_at`, and returns authoritative `last_sequence` (zero before any frame) plus nullable `last_frame_id`. After a driver restart, long-poll once for the current fence, heartbeat with it, then submit `sequence = last_sequence + 1`; never reset the counter. A stale fence or revoked token never revives an older driver. 2. **Observation** — `POST /v1/machines/{id}/observations`: ```json { "sequence": 1, "screenshot": "", "media_type": "image/png", "sha256": "", "width": 1920, "height": 1080 } ``` `sequence` is positive and monotonic. Identical replay is accepted; different normalized frame content at an existing sequence returns `409 FRAME_SEQUENCE_CONFLICT`. Screenshot input may be raw base64 or a matching `data:image/...;base64,` URI. The encoded payload after that optional prefix is capped at 10,485,760 base64 characters; decoded dimensions must be 320x240 through 3840x2160. Only one-frame PNG/JPEG is accepted. Media type, optional dimensions, and optional request `sha256` are verified against the submitted decoded bytes. The server strips metadata and re-encodes the image before encrypting it. The response digest covers these normalized bytes and may therefore differ from the request digest. A live transport frame logically expires after 15 minutes and is never copied into SSE, webhooks, ordinary logs, or ordinary durable run history. That transport retention is separate from BYOK model-input auditing: when a live BYOK Task, Workflow, or schedule uses the frame for a visual decision, the fail-closed pre-provider audit retains a separate exact model-input copy under the account-lifetime screenshot rules in the BYOK section. 3. **Commands** — long-poll `GET /v1/machines/{id}/commands?after=0&limit=10&wait_seconds=20`. `wait_seconds` is 0-25 and `limit` is 1-50. A timeout is a normal `200` with `data: []`: ```json { "machine_id": "3e8af80d-7a7d-454a-baf5-9f635e6c962b", "data": [{ "id": "de3132f4-cb89-419a-9c76-38591976ea90", "cursor": 41, "protocol_version": "1", "command": "click", "parameters": {"x": 732, "y": 418, "button": "left"}, "deadline_at": "2026-07-14T20:01:00Z", "fencing_token": 1, "precondition_frame_id": "6e5ab4c4-5e56-4524-bce3-bcd8845b5679", "run_id": "4d6464a6-b9c0-4638-b408-ec3fe21b572a" }], "next_cursor": 41, "fencing_token": 1, "request_id": "req_..." } ``` Persist `next_cursor` only after durably processing the batch, then resume with `after=next_cursor`. Delivery is at least once. Deduplicate by command id. The server permits exactly one queued or delivered command per external machine; concurrent dispatch returns `409 MACHINE_BUSY`, preventing cross-replica races on a single physical display. Before input, verify protocol, capability, deadline, fence, and that the currently visible screen is still `precondition_frame_id`. Coordinates are pixels in that verified frame's decoded dimensions. Never evaluate model `raw_code`; execute allowlisted typed `command` + `parameters` only. 4. **Result** — POST to `/v1/machines/{id}/commands/{command_id}/results`: ```json { "fencing_token": 1, "precondition_frame_id": "6e5ab4c4-5e56-4524-bce3-bcd8845b5679", "success": true, "result": {"duration_ms": 82}, "observation": { "sequence": 2, "screenshot": "", "media_type": "image/png", "width": 1920, "height": 1080 } } ``` `precondition_frame_id` is required and must exactly echo the command envelope's value, including `null`; mismatch returns `409 FRAME_PRECONDITION_MISMATCH`. For every successful side-effecting command, capture the resulting screen and attach the observation to this same result request so action completion and the post-action frame commit atomically; completing first and submitting a separate later observation creates a planning race. The field remains optional for failures and commands that cannot produce a frame. A failed result must carry `error`; a successful result cannot. Byte-equivalent replay returns `replayed: true`. A conflicting second result, stale fence, cancellation, or expired deadline returns 409 and must not cause local re-execution. Once the heartbeat makes `connection_status: "connected"`, use the machine id unchanged in `POST /v1/runs`, saved/ad-hoc Workflow task steps, and schedules. Owner-authenticated direct Machine actions also enter this same fenced pull queue; the HTTP action call completes only after the driver acknowledges it. An offline driver never silently falls back to a managed VM. Serialize parallel Workflow task branches sharing one physical display unless the driver provides separate isolated displays. Enrollment, external runtime, direct actions, and frame transport are all zero credits and have no managed-VM runtime charge. `GET /v1/machines/pricing` reports these four zeroes under `external_machines`. Managed Task/Workflow model steps still use the selected CUA version's published per-step price. Live-key BYOK task steps record provider tokens but charge zero Coasty credits. Managed-mode test-key task steps remain deterministic sandbox and make no provider call; test-auth BYOK intent is rejected with `422 LLM_PROVIDER_UNSUPPORTED`. Bringing your own machine alone does not remove managed inference charges. Owner-authenticated `DELETE /v1/machines/{id}` revokes an external device token and outstanding command leases immediately; for a managed machine, the same endpoint terminates the VM. External `/connection` returns `409 INVALID_STATE`: Coasty never issues SSH, VNC, WebSocket, or browser-debug credentials for caller-owned hosts. External `/snapshot` returns `400 UNSUPPORTED_MACHINE_KIND` because Coasty does not own the disk. Owner-authenticated start, stop, and restart remain available as logical dispatch gates: they increment the fence and cancel pending commands, but do not power or reboot the caller-owned host. ### POST /v1/machines (provision) Provision a VM. Test keys (`sk-coasty-test-*`) return a mock instantly; live keys require the `machines:write` scope, a wallet balance of at least **20 credits for every live key (including Unlimited consumer subscribers)**, and room under your plan's concurrent-machine cap. Provisioning is **asynchronous**: the response returns the machine in `creating` status — poll `GET /v1/machines/{id}` until `status` is `running` before driving it. **Request body** (unknown fields are rejected with 422) | Field | Type | Req | Default | Notes | | --- | --- | --- | --- | --- | | `display_name` | string | yes | - | Human label. 1-64 chars. | | `os_type` | string | no | `linux` | `linux` or `windows`. Windows costs more to run. | | `desktop_enabled` | bool | no | `false` | Install a GUI (XFCE + VNC). Required for screenshots and VNC. | | `cpu_cores` | int\|null | no | auto | 1-16. Capped by tier. | | `memory_gb` | int\|null | no | auto | 1-64. Capped by tier. | | `storage_gb` | int\|null | no | auto | 8-500. | | `restore_from_snapshot` | bool | no | `false` | Boot from your latest snapshot instead of a clean image (Linux only). | | `ttl_minutes` | int\|null | no | null | Auto-destroy after N minutes (5-10080). Omit for no auto-destroy (adds a `Warning` header). | | `metadata` | object\|null | no | null | Free-form tags: <=16 entries, 64-char keys, 256-char values. | | `proxy` | object\|null | no | null | Route egress through a proxy. `{"mode":"managed"}` uses Coasty's residential upstream; `{"mode":"custom","scheme":"http","host":...,"port":...,"username":...,"password":...}` uses yours (http/https/socks5, auth optional). Installed AND proven -- the machine's egress address is compared with and without the proxy before `proxy.status` becomes `active`, so a proxy that is not carrying traffic fails instead of silently browsing from the datacenter IP. `password` is write-only and never returned. | ```bash curl -X POST https://coasty.ai/v1/machines \ -H "X-API-Key: $COASTY_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{"display_name": "agent-box", "os_type": "linux", "desktop_enabled": true, "ttl_minutes": 120}' ``` **The machine object** (returned by provision / list / get): | Field | Type | Notes | | --- | --- | --- | | `id` | string | UUID for live VMs; `mch_test_` for test mocks. Pass to runs/workflows and every `/v1/machines/{id}` call. | | `display_name` | string | The label you set. | | `kind` | string | `managed` or `external`. | | `capabilities` | string[] | Advertised external-driver capabilities; currently empty for managed machines. | | `protocol_version` | string\|null | `"1"` for external machines; null for managed. | | `connection_status` | string\|null | `connected`, `disconnected`, `stale`, or `revoked` for external machines. | | `last_seen_at` | string\|null | Most recent authenticated external-driver activity. | | `status` | string | Lifecycle status (see table). Poll until `running`. | | `os_type` | string | `linux` / `windows`. | | `desktop_enabled` | bool | GUI installed (needed for screenshots/VNC). | | `cpu_cores` / `memory_gb` / `storage_gb` | number | Provisioned resources. | | `public_ip` | string\|null | Public IP once assigned (null while `creating`). | | `auto_destroy_at` | string\|null | ISO-8601 resource expiry. Managed infrastructure is destroyed; external registration/device access is revoked while caller host/storage stay untouched. | | `ttl_minutes` | int\|null | TTL last applied (null = no automatic destroy/revoke). | | `is_test` | bool | `true` for a test-key mock VM. | | `billing` | object\|null | Runtime-billing summary (rates, total billed, `suspended_for_billing`). | | `created_at` / `started_at` | string\|null | ISO-8601 timestamps. | | `metadata` | object | Your tags, echoed back. | The response is `{ machine, connection, request_id }`. `connection` is **redacted** here (ports + `has_ssh_key` / `has_vnc_password` booleans only); fetch secrets via `GET /v1/machines/{id}/connection`. ### GET /v1/machines (list) and GET /v1/machines/{id} (get) List returns `{ data, has_more, request_id }`, newest first, `?limit=` 1-200 (default 50). Get returns one machine with redacted connection metadata. Both read straight from the registry. A wrong or someone-else's id returns `404 MACHINE_NOT_FOUND` (never 403 — ids can't be enumerated). Ids are mode-isolated: a test key cannot see a live machine and vice-versa. ### Managed-machine status lifecycle Poll `status`; drive the machine only while it is `running`. The "Billed" column is the runtime rate that applies in that status. | Status | Billed | Meaning | | --- | --- | --- | | `creating` | Free | Booting; getting an IP. Not yet drivable. | | `running` | running rate | Up and ready — the only status from which work executes. | | `starting` / `stopping` / `restarting` | running rate | Transitional. Poll until it settles. | | `stopped` | stopped rate | Powered off, disk + snapshots preserved. Start it again. | | `suspended` | stopped rate | Auto-stopped because the wallet emptied. Top up + start. | | `error` | Free | Provision/lifecycle failed. Start (retry) or terminate. | | `terminated` | Free | Permanently destroyed. A later GET returns 404. | ### Lifecycle: start / stop / restart / terminate - Managed `POST /v1/machines/{id}/start` — boot a `stopped` or `error` VM. Async. - Managed `POST /v1/machines/{id}/stop` — power off a `running` VM (disk kept). Async. - Managed `POST /v1/machines/{id}/restart` — reboot the VM. Async. - External start/stop/restart — logical dispatch gates only: advance the fence, cancel pending commands, and never power or reboot the caller-owned host. - Managed `DELETE /v1/machines/{id}` permanently tears down the VM; external DELETE revokes only its Coasty registration, device token, and command leases. The external host and storage remain untouched. Delete is idempotent. Lifecycle actions are state-checked: starting a non-stopped machine or stopping a non-running one returns `409 INVALID_STATE` with `current_state` and `allowed_from` in the body. Managed-machine power changes are asynchronous — poll their transitional status until it settles. External logical gates commit immediately and return `running` or `stopped`; they do not power the host. ```bash curl -X POST https://coasty.ai/v1/machines/$MACHINE_ID/stop -H "X-API-Key: $COASTY_API_KEY" curl -X DELETE https://coasty.ai/v1/machines/$MACHINE_ID -H "X-API-Key: $COASTY_API_KEY" ``` ### Auto-destroy / auto-revoke (TTL): PATCH /v1/machines/{id} A managed machine left running bills until destroyed, so set `ttl_minutes` as a safety net. A background sweep (~every 60s) terminates managed infrastructure once `auto_destroy_at` passes. For an external machine, expiry revokes only the Coasty registration/token/leases and never touches its host or storage. `PATCH` adjusts the deadline any time: `ttl_minutes` is measured **from now** (so it doubles as a lease extension), accepts `5`-`10080` (5 min to 7 days), and `0` clears auto-destroy. Anything else is `400 INVALID_TTL`. ```bash curl -X PATCH https://coasty.ai/v1/machines/$MACHINE_ID \ -H "X-API-Key: $COASTY_API_KEY" -H "Content-Type: application/json" \ -d '{"ttl_minutes": 30}' ``` ### Runtime billing Managed machines bill the **developer API wallet** (separate from subscription credits) by the minute, floored to whole credits in your favour: | State | Rate | | --- | --- | | Running (Linux) | **$0.05/hr** | | Running (Windows) | **$0.09/hr** | | Stopped or suspended | **$0.01/hr** (keep-alive) | | Creating / error / terminated | Free | | Snapshot | **$0.01** each (one-time) | | Per-call control ops (actions, terminal, files, browser, screenshot, connection) | Free | Transitional states bill at the running rate. If the wallet empties mid-run the next sweep **stops** the machine (status `suspended`) rather than destroying it — disk and snapshots are preserved; top up and `POST /start` to resume. Watch live accrual for every metered machine at `/v1/billing/active` (documented under Task Runs). ### Connect: GET /v1/machines/{id}/connection Returns the full `ssh_private_key_pem`, `vnc_password`, public IP, and ports. Gated by the **opt-in `connection:read` scope** (request it when you mint the key) and sent `Cache-Control: no-store`. Treat it like a password — never log it. SSH usernames: `ubuntu` (Linux), `Administrator` (Windows). VNC fields exist only on `desktop_enabled` machines. Normal machine responses expose only `has_ssh_key` / `has_vnc_password` booleans plus ports. ### Screenshots & snapshots - `GET /v1/machines/{id}/screenshot` — current screen of a desktop machine. A still-booting VM returns `502 SCREENSHOT_FAILED`; poll for `running` first. External-machine responses include an opaque `frame_id`; bind the next action to it with `precondition_frame_id`. Capturing again is a safe read-only resynchronization and advances the frame. - `POST /v1/machines/{id}/snapshot` — capture a restorable machine image. Needs `snapshots:write`; the default price is `$0.01`, while the response's `credits_charged` and `X-Credits-Charged` are authoritative for the deployed configuration. A conclusive pre-creation rejection submits a refund; only `X-Credits-Refunded` confirms settlement. A timeout, `5xx`, or malformed post-dispatch result is **not** blindly refunded because the image may exist; it returns terminal `SNAPSHOT_OUTCOME_UNKNOWN`. Boot a future machine from a confirmed image with `restore_from_snapshot: true`. ### Control surface (drive the VM directly) Each endpoint enforces a specific scope. Only two on this surface are opt-in: `browser:execute` (arbitrary JS) and `connection:read` (plaintext SSH key + VNC password). `actions:exec`, `terminal:exec`, `files:read`, `files:write`, and `snapshots:write` are all granted by default, so a freshly minted key can drive a machine end to end without any extra scope request. | Endpoint | Scope | Notes | | --- | --- | --- | | `POST /v1/machines/{id}/actions` | per-command | One control action (click/type/scroll/…). | | `POST /v1/machines/{id}/actions/batch` | union of step scopes | Up to 50 steps; `stop_on_error` defaults true. | | `POST /v1/machines/{id}/browser/{op}` | `actions:exec` (`browser_execute` needs `browser:execute`) | Browser ops (navigate, click, …). | | `POST /v1/machines/{id}/terminal` | `terminal:exec` | Shell command. Output truncated to 5000 chars. | | `POST /v1/machines/{id}/files/{op}` | `files:read` / `files:write` | File ops; reads vs writes pick the scope. | For a caller-owned external desktop, use an observation-bound loop: capture a screenshot, plan only against those pixels (directly or with `POST /v1/predict`), send one action with that response's `frame_id`, then use the action response's atomic post-action `screenshot` and `frame_id` for the next turn. The driver revalidates the screen immediately before OS input. A stale frame fails closed; do not retry an input blindly when its execution outcome is unknown. ```bash curl -X POST https://coasty.ai/v1/machines/$MACHINE_ID/terminal \ -H "X-API-Key: $COASTY_API_KEY" -H "Content-Type: application/json" \ -d '{"command": "ls -la /home/ubuntu"}' ``` **Idempotency nuance:** a command that never reached the VM (a dispatch failure) is **not** cached, so retrying the same `Idempotency-Key` runs it fresh; a command the VM actually ran (even if it errored) **is** cached. Image pixels are response-only and never stored in the generic idempotency cache. A replay cannot execute again: it retains `frame_id`, but returns `screenshot: null` and `observation_available: false`. ### Test mode `sk-coasty-test-*` keys skip real cloud provisioning: they return `mch_test_` ids (`is_test: true`) from an in-memory store, mock all results, and never bill — up to **5 mock machines** per user (`TEST_MACHINE_LIMIT`). Mock connection details use a non-routable `203.0.113.42` IP. Same request/response shapes as live, so you can build and run CI before flipping to a live key. ### Machine error codes `MACHINE_NOT_FOUND` (404, unknown/terminated/other-mode id) · `INVALID_MACHINE_ID` (400, bad id format) · `INVALID_STATE` (409, lifecycle conflict; carries `current_state` + `allowed_from`) · `INVALID_TTL` (400) · `TEST_MACHINE_LIMIT` (409) · `SCREENSHOT_FAILED` (502) · `INSUFFICIENT_CREDITS` (402, under 20 at provision) · `UPSTREAM_AUTH_FAILED` / `UPSTREAM_UNAVAILABLE` / `UPSTREAM_TIMEOUT` (502/503/504, transient provisioning-service issues — never your key). --- ## 4. Submit-and-forget tasks `POST /v1/tasks` is the highest-level Computer Use endpoint. Send one goal; you do not provision, select, monitor, or destroy a machine, and the agent never pauses to ask for human takeover. Admission returns immediately as an `agent.run`; Coasty completes the work asynchronously and ends in exactly one terminal outcome: `succeeded`, `failed`, `timed_out`, or `cancelled`. ```mermaid flowchart LR A["POST /v1/tasks
task + limits"] --> B["Queued immediately"] B --> C["Provision ephemeral desktop
stable idempotency + TTL"] C --> D["Observe → Act → Verify"] D -->|verified| E["succeeded"] D -->|cannot complete| F["failed / timed_out"] E --> G["Start idempotent cleanup"] F --> G E --> H["Signed terminal webhook"] F --> H G --> I["terminated
or retrying under TTL"] ``` ### Minimal request ```bash curl https://coasty.ai/v1/tasks \ -H "X-API-Key: $COASTY_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: invoice-download-4821" \ -d '{ "task": "Open the billing portal, download the newest invoice, and verify the PDF exists.", "webhook_url": "https://example.com/hooks/coasty" }' ``` Only `task` is required. That is the complete required integration. Store the returned `id` and `webhook_secret`. If `webhook_url` is present, you do not need to poll. Terminal delivery is HMAC-signed and at least once; deduplicate by `Coasty-Delivery`. You may still use `GET /v1/runs/{id}`, `GET /v1/runs/{id}/events`, or `POST /v1/runs/{id}/cancel` because the returned resource is the normal durable Run object. ### Request fields | Field | Type | Req | Default | Meaning | | --- | --- | --- | --- | --- | | `task` | string | yes | - | Complete observable goal, 1-16000 chars. | | `cua_version` | string | no | `v5` | `v1`, `v3`, `v4`, or `v5`. | | `instructions` | string\|null | no | null | Extra immutable operating rules. | | `system_prompt` | string\|null | no | null | Advanced task preamble; built-in safety/tool semantics remain active. | | `max_steps` | int | no | 150 | Hard 1-1000 step budget, also clamped by the server. | | `deadline_seconds` | int\|null | no | server default | End-to-end wall-clock budget, including provisioning. | | `action_policy` | object\|null | no | null | Enforced post-model controls such as blocked keys/domains and cumulative action limits. | | `webhook_url` | HTTPS URL\|null | no | null | Terminal callback. Private, loopback, userinfo, and unsafe targets are rejected. | | `metadata` | object\|null | no | null | Your non-secret correlation data, echoed back. | | `llm` | object\|null | no | managed | Optional Anthropic/OpenAI BYOK selection. Send the key only in `X-LLM-Api-Key`. | | `machine` | object | no | Linux desktop defaults | Workload preferences below. Machine id, TTL, and cleanup are never caller responsibilities. | `machine` accepts `provider`, `os_type` (`linux` or `windows`), `desktop_enabled`, `cpu_cores` (1-16), `memory_gb` (1-64), `storage_gb` (8-500), `restore_from_snapshot`, and `proxy`. Omitted sizing fields stay omitted so the machine service applies its current safe defaults. #### Choosing a backend `machine.provider` pins which backend runs the task's machine: | Value | Behaviour | | --- | --- | | `auto` (default) | Coasty chooses. A desktop or Windows task goes to Daytona, falling back to AWS when Daytona is disabled; a headless task goes to Azure. | | `aws` | Always AWS EC2. | | `daytona` | Always a Daytona sandbox. | | `azure` | Always an Azure container. | Leave it unset unless you have a reason to pin one — `auto` already picks the backend that suits the workload, and it keeps working if a backend is disabled in your deployment. Pin it when you need a specific environment, for example a provider whose egress range you have allowlisted somewhere else. The value is part of the run's idempotency identity, so replaying a request with the same `Idempotency-Key` lands on the same backend rather than silently migrating the task somewhere else. ```bash curl -X POST "$COASTY_API/v1/tasks" \ -H "Authorization: Bearer $COASTY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "task": "Open example.com and report the page heading.", "machine": { "provider": "aws", "os_type": "linux", "desktop_enabled": true } }' ``` ### Autonomy and terminal guarantees - Human takeover is hardwired to `fail` at the public Run contract, but the endpoint-owned executor first intercepts the model's handoff request. It never enters the `awaiting_human` state and never waits for a person. - When the model asks for a human, the runtime suppresses the request and tells the agent to carry on with a fresh screen. There is **no retry budget and no challenge-specific terminal error**: a verification screen, a CAPTCHA, an email confirmation, or any other checkpoint is treated as part of the task. `max_steps`, `deadline_seconds`, and your credit balance are the only things that stop a task. - Anything you put in the task is the agent's to use. If you supply a password, an address, or an inbox it can reach, retrieving a confirmation code from that inbox is ordinary work, not an escalation — so multi-step signup and verification flows complete rather than failing on the word "password". - Coasty does not provide or integrate third-party CAPTCHA-solving services, stealth/proxy evasion, access-control bypasses, or fabricated credentials, one-time codes, biometrics, payments, or approvals. The agent is explicitly prohibited from using them, and that prohibition is stated in the task prompt where the model can apply judgement — not enforced by a keyword classifier that ends the run. - If a task genuinely cannot be completed, it finishes with a clear explanation in `result.summary` rather than stalling or waiting. ### Seeing what the agent saw `GET /v1/runs/{run_id}/screenshots` (scope `runs:read`, free) returns the **model-input frames** for a run, oldest first: the exact images the agent was looking at before each decision. Captured for every run, managed and BYOK alike. Metadata only by default, because one frame is several hundred KB of base64: ```bash curl -s "https://coasty.ai/v1/runs/$RUN_ID/screenshots" -H "X-API-Key: $COASTY_API_KEY" ``` ```json { "object": "list", "data": [ { "index": 0, "attempt": 1, "step": 1, "taken_at": "2026-07-25T12:00:03Z", "width": 1280, "height": 720, "mime_type": "image/png", "size_bytes": 412334, "sha256": "9f2c…", "degraded": false, "encrypted_at_rest": true } ], "has_more": true } ``` Add `?include_image=true` to inline `image_b64`. That mode clamps the page to 10 frames and responds `Cache-Control: no-store`, because a frame can show whatever was on screen — an inbox, a dashboard, a billing page. Page with `?after_index=`. Read `index` as the stable address: it is flat and monotonic across the **whole** run. A run that was reaped and retried starts a new attempt whose `step` counter restarts at 1, so `step` alone is not unique — `attempt` tells you which try a frame belongs to. For what the agent **thought and did** at each of those frames, read `GET /v1/runs/{run_id}/log` (documented under Task Runs). Every step there carries a `screenshot_index` that is exactly this list's `index`, so the two join directly. Two fields worth knowing: - `degraded: true` means capture failed and the agent had to act on a reused or placeholder frame. If a run did something inexplicable, check this first. - `image_unavailable: true` replaces `image_b64` when a stored frame cannot be decoded. One bad frame never fails the page, and ciphertext is never returned dressed as an image. `width` and `height` are the **model coordinate space** — what the agent's clicks were computed against, which is not necessarily the machine's physical resolution. - `max_steps` and `deadline_seconds` are independent hard stops. - `succeeded` means the run reached its completion verifier, not merely that it emitted an action. Inspect `result.passed`, `result.summary`, and the final screenshot/event evidence appropriate to your application. - A provisioning failure becomes a terminal task error with the underlying stable error code; it is not misreported as successful admission. - The generated machine receives a TTL longer than the task deadline as a provider-side leak backstop. Cleanup begins after every terminal outcome, including failure and cancellation; late provisioning success is drained and compensated without reopening the task. - Cleanup is ownership-checked and idempotent. If termination is temporarily unavailable, `machine.cleanup_status` becomes `retrying`, recovery retries it, and the TTL remains authoritative. - A terminal webhook reports the canonical `machine.cleanup_status`. Delivery can occur while cleanup is `terminating` or `retrying`; do not interpret task completion as proof that provider termination has already finished. This is a no-pause guarantee, not a promise to defeat every anti-bot or account security control. Sites can deliberately require proof that no autonomous agent can legitimately supply. In that case the task returns a precise terminal failure instead of hanging or claiming success. The create response intentionally shows `machine_id: null` while provisioning: ```json { "id": "7a1b2c3d-4e5f-4678-9abc-def012345678", "object": "agent.run", "status": "queued", "machine_id": null, "machine": { "mode": "automatic", "status": "provisioning", "id": null, "cleanup": "always", "cleanup_status": "pending" }, "task": "Download and verify the latest invoice", "on_awaiting_human": "fail", "steps_completed": 0 } ``` **`machine.status` values (run-owned automatic machines).** This is the run's own view of the machine it provisioned for itself. It is a **different vocabulary** from the managed-machine resource lifecycle documented in the Machines section, and it has more than the three states you might expect. | `machine.status` | Meaning | | --- | --- | | `provisioning` | The run has asked for a machine; no provider handle yet. `machine.id` is null. | | `starting` | The provider handle and billing record are durable, but the desktop may still be booting. Execution readiness is verified separately before the agent is allowed to start. | | `reconciling` | Provisioning hit a recoverable provider condition and is being reconciled automatically. The run stays `running`; the accompanying `status` event carries `phase: "machine_reconciling"`. | | `terminated` | Cleanup finished; the machine is gone. | | `cleanup_failed` | Termination did not confirm. `cleanup_status` is `retrying` and recovery will retry it; the TTL remains the authoritative backstop. Do not read this as a leaked machine. | `cleanup_status` moves independently through `pending` → `terminating` → `terminated`, or to `retrying` when termination is temporarily unavailable. ### Idempotency, retries, and pricing Always send a stable `Idempotency-Key` for the logical task. A retry with the same key and identical body returns the original run; a changed body returns `422 IDEMPOTENCY_KEY_REUSED`. The same run id also derives the internal machine-provision key, preventing duplicate machines after process or network failure. Retry admission only when the error says `retryable: true`; honor `Retry-After`. Managed mode charges normal completed Task Run steps plus actual machine runtime. BYOK charges **zero Coasty platform credits for LLM steps**, but the developer still pays their Anthropic/OpenAI provider directly and the ephemeral machine runtime is still billed by Coasty. Test keys provision a sandbox machine, run a deterministic no-provider task, clean it up, and charge $0. For lower-level control, caller-owned machines, or optional human takeover, use `POST /v1/runs` instead. --- ## 5. Task Runs A run gives the agent a task plus a machine and drives it to completion server-side: an autonomous loop with pass/fail verification, optional human takeover, managed per-step wallet billing (or zero-cost BYOK), a streaming event log, and webhooks. Scopes: `runs:read` (list/get/events/log/screenshots) and `runs:write` (start/cancel/resume). The machine may be managed or external. For an external target, connect its driver first; screenshot/action transport happens through the machine protocol and the run body remains `{machine_id, task, ...}`. **Run endpoints** | Method + path | Scope | Description | | --- | --- | --- | | `POST /v1/runs` | `runs:write` | Start a run. Honors `Idempotency-Key`. | | `GET /v1/runs` | `runs:read` | List runs (`status`, `limit`). | | `GET /v1/runs/{id}` | `runs:read` | Get one run. **Authoritative** for state and `steps_completed`. | | `POST /v1/runs/{id}/cancel` | `runs:write` | Cancel an active run. | | `POST /v1/runs/{id}/resume` | `runs:write` | Resume after a human takeover. | | `GET /v1/runs/{id}/events` | `runs:read` | SSE stream of the timeline. Best for watching a run live. | | `GET /v1/runs/{id}/log` | `runs:read` | **Assembled per-step trajectory as plain JSON. The only supported way to read a finished run's full trajectory.** | | `GET /v1/runs/{id}/screenshots` | `runs:read` | The model-input frames the agent saw. Free. | **Pricing.** Each managed completed agent step bills your wallet $0.05 (5 credits) on `v3`/`v4`/`v5`, or $0.08 (8 credits) on `v1` (5 base + 3 v1 engine surcharge). Steps are billed one at a time as they complete, idempotently per step; bookkeeping steps emitted when you resume a paused run are not billed, and no trajectory/HD/prompt surcharges apply to run steps. Creating a managed run requires the wallet to cover at least one step (otherwise `402 INSUFFICIENT_CREDITS`); if the wallet runs dry mid-run the run fails with `WALLET_EXHAUSTED` and only completed steps stay billed. Test keys bill $0. Live-key BYOK runs skip the wallet precheck and every step debit; their terminal usage reports real provider tokens, attribution, and zero Coasty credits. Managed-mode test-key runs stay deterministic sandbox executions and do not call or bill a provider. BYOK headers or provider metadata instead fail before execution with `422 LLM_PROVIDER_UNSUPPORTED`; no stored key is read or decrypted. ### POST /v1/runs Start a run. Returns immediately with `status: "queued"` and a create-response-only `webhook_secret` (only when you pass a `webhook_url`). An exact bounded Idempotency-Key replay returns the same secret; GET/list never do. Idempotency is via the `Idempotency-Key` request header, not a body field. **Request body** (unknown fields are rejected with 422) | Field | Type | Req | Default | Notes | | --- | --- | --- | --- | --- | | `machine_id` | string | yes | - | Target managed or connected external machine. Must be owned by your key's user. 1-128 chars. | | `task` | string | yes | - | Natural-language goal. 1-16000 chars. | | `cua_version` | string | no | `v5` | `v1` / `v3` / `v4` / `v5`. | | `instructions` | string\|null | no | null | APPENDED to the base prompt. Up to 16000 chars. | | `system_prompt` | string\|null | no | null | Custom preamble (takes priority). Up to 32000 chars. | | `model` | string\|null | no | null | Legacy top-level model selector; prefer `llm.model` for BYOK. Uses the same 1-256-character safe model-id grammar. Secret-shaped values (`sk-*`, bearer/authorization/API-key/secret forms) fail non-reflectively with `422 LLM_MODEL_INVALID`; provider credentials belong only in `X-LLM-Api-Key`. | | `max_steps` | int | no | 150 | 1-1000. Clamped to the server ceiling (1000). Real long-horizon work (sign up, collect a code from an inbox, come back and finish) runs 60-120 steps, which is why the default is 150 and not a token 40 or 50. | | `action_policy` | object\|null | no | null | Immutable post-model controls inherited by the complete Task execution tree; `max_actions` is cumulative across nested delegation. | | `deadline_seconds` | int\|null | no | null (server default 1800) | 1-86400. Wall-clock budget. Clamped server-side; read the **effective** value back off `RunResponse.deadline_seconds`. | | `on_awaiting_human` | string | no | `pause` | `pause` / `fail` / `cancel` when a human is needed. | | `awaiting_human_timeout_seconds` | int\|null | no | null (server default 1800) | 1-86400. How long to wait while paused. Clamped server-side; read the **effective** value back off `RunResponse.awaiting_human_timeout_seconds`. | | `webhook_url` | string\|null | no | null | HTTPS only, no userinfo. Notified on terminal + awaiting_human. | | `metadata` | object\|null | no | null | Opaque caller metadata. Max 50 keys. | When supplied, `action_policy` is validated at create time, atomically pinned with the Task Run, restored on worker recovery, and inherited by nested CUA delegation. Every model-produced batch is checked before dispatch. A violation fails the run with `ACTION_POLICY_VIOLATION`; provider inference completed before rejection retains normal managed billing or BYOK usage attribution. Header: `Idempotency-Key: ` makes a retried create safe. Reusing a key on a different operation or with a different body returns `422 IDEMPOTENCY_KEY_REUSED`. **The Run object** (`RunResponse`, returned by create / get / list) | Field | Type | Notes | | --- | --- | --- | | `id` | string | Run id. | | `object` | string | Always `"agent.run"`. | | `status` | string | `queued` / `running` / `awaiting_human` / `succeeded` / `failed` / `cancelled` / `timed_out`. | | `machine_id` | string\|null | The machine the agent is driving. Null only while `POST /v1/tasks` is still provisioning. | | `machine` | object\|null | Automatic lifecycle view: `{ mode, status, id, cleanup, cleanup_status, error? }`. Null on ordinary caller-supplied-machine runs. `status` is one of `provisioning` / `starting` / `reconciling` / `terminated` / `cleanup_failed` (see below). | | `task` | string | The goal you submitted. | | `cua_version` | string | The engine that ran: `v1` / `v3` / `v4` / `v5` (default `v5`). | | `instructions` | string\|null | Extra guidance appended to the base prompt. | | `max_steps` | int | Hard cap on agent steps. Default **150**. | | `deadline_seconds` | int | **Effective** wall-clock budget after the server applied its ceiling. Echoed back so a clamp is never silent: ask for 86400 against a lower server ceiling and you can read the value the run will actually be held to, instead of discovering it as a surprise `DEADLINE_EXCEEDED`. | | `awaiting_human_timeout_seconds` | int | **Effective** ceiling on how long the run may sit in `awaiting_human` before `on_awaiting_human` is applied. Also post-clamp. | | `on_awaiting_human` | string | `pause` / `fail` / `cancel`. | | `steps_completed` | int | Steps run so far. **Authoritative** count, including when `GET /v1/runs/{id}/log` reports `log_complete: false`. | | `credits_charged` | int | Developer API wallet units (1 unit = $0.01). `cost_cents` has the same numeric value; divide by 100 for USD. | | `cost_cents` | int | Dollar cost so far, in cents. | | `result` | object\|null | `{ passed, status, summary?, usage, verdict? }` once finished. `summary` is ABSENT on a plain failed run. See "Run result shape" below. | | `error` | object\|null | `{ code, message }` when failed. | | `awaiting_human_reason` | string\|null | Why the run paused. | | `llm` | object\|null | BYOK attribution (non-secret): `{ provider, model, key_fingerprint, key_source, key_scrubbed }`. Null when the run used the managed model. The encrypted key ciphertext is never serialized. | | `metadata` | object\|null | The metadata you attached. | | `webhook_url` | string\|null | Where lifecycle events are POSTed. | | `webhook_secret` | string\|null | Per-run HMAC signing secret. Returned by create and an exact bounded Idempotency-Key replay; null on get/list. | | `created_at` | string\|null | ISO-8601. | | `started_at` | string\|null | When the run left the queue. | | `awaiting_human_since` | string\|null | When it last paused for a human. | | `finished_at` | string\|null | When it reached a terminal state. | | `request_id` | string\|null | Id of the create request. | **Example response** (a freshly created run): ```json { "id": "7a1b2c3d-4e5f-4678-9abc-def012345678", "object": "agent.run", "status": "queued", "machine_id": "m_9f2c", "task": "Open the billing page and download the latest invoice as PDF", "cua_version": "v5", "instructions": null, "max_steps": 150, "deadline_seconds": 1800, "awaiting_human_timeout_seconds": 1800, "on_awaiting_human": "pause", "steps_completed": 0, "credits_charged": 0, "cost_cents": 0, "result": null, "error": null, "awaiting_human_reason": null, "llm": null, "metadata": { "team": "finance" }, "webhook_url": "https://example.com/hooks/coasty", "created_at": "2026-06-01T12:00:00Z", "started_at": null, "awaiting_human_since": null, "finished_at": null, "request_id": "req_4f9a2b1c", "webhook_secret": "whsec_one_time_value_shown_here" } ``` **curl** ```bash BASE=https://coasty.ai/v1 AUTH="X-API-Key: $COASTY_API_KEY" # 1. Start a run. Create/exact-replay responses include webhook_secret; GET/list do not. RUN_ID=$(curl -s "$BASE/runs" -H "$AUTH" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: order-4821" \ -d '{ "machine_id": "m_9f2c", "task": "Open the billing page and download the latest invoice as PDF", "cua_version": "v5", "max_steps": 150, "on_awaiting_human": "pause" }' | python -c "import sys,json;print(json.load(sys.stdin)['id'])") # 2. Poll the run until it reaches a terminal state. while :; do RUN=$(curl -s "$BASE/runs/$RUN_ID" -H "$AUTH") STATUS=$(echo "$RUN" | python -c "import sys,json;print(json.load(sys.stdin)['status'])") echo "status=$STATUS" case "$STATUS" in succeeded|failed|cancelled|timed_out) break ;; esac sleep 2 done ``` **Python** ```python import os, time, requests BASE = "https://coasty.ai/v1" HEADERS = {"X-API-Key": os.environ["COASTY_API_KEY"]} TERMINAL = {"succeeded", "failed", "cancelled", "timed_out"} run = requests.post( f"{BASE}/runs", headers={**HEADERS, "Idempotency-Key": "order-4821"}, json={ "machine_id": "m_9f2c", "task": "Open the billing page and download the latest invoice as PDF", "cua_version": "v5", # omit for the default v5; v1/v3/v4/v5 on all tiers "max_steps": 150, # this IS the default; raise it for longer work "on_awaiting_human": "pause", }, timeout=30, ).json() run_id = run["id"] webhook_secret = run.get("webhook_secret") # create/replay response only; store it now # Effective limits after server clamping. Never assume what you asked for stuck. print("deadline", run["deadline_seconds"], "awaiting_human", run["awaiting_human_timeout_seconds"]) while run["status"] not in TERMINAL: time.sleep(2) run = requests.get(f"{BASE}/runs/{run_id}", headers=HEADERS, timeout=30).json() print(run["status"], run["steps_completed"], "steps") # result.summary is the LAST 2000 chars of the trajectory, so it usually holds # the final answer. For the full trajectory use GET /v1/runs/{id}/log. print(run["result"]) ``` ### Run result shape Once a run reaches a terminal state, `result` is populated. There is **no `output` field**; do not look for one. | Field | Type | Notes | | --- | --- | --- | | `passed` | bool | Whether the run is considered successful. When a verifier ran, this is the verifier's own `passed`. | | `status` | string | The agent's terminal token: `done` on success, `fail` on an agent-reported failure. | | `summary` | string | The **last 2000 characters** of the trajectory. | | `usage` | object | Token/step usage rollup for the run. | | `verdict` | object | **Present only when a verifier ran** (`v4` / `v5` autonomous verification). When it is present and `verdict.passed` is false, a run that would otherwise have been `succeeded` is downgraded. | `summary` is a **tail** slice, not a head slice. The agent appends its final answer last, so a head slice structurally discarded the conclusion. That was a real bug and is fixed: `summary` now ends with the agent's closing words. Two thousand characters is still a slice. If a run's answer is longer than that, or you need the reasoning and actions that produced it, read the log: ```python log = requests.get(f"{BASE}/runs/{run_id}/log", headers=HEADERS, timeout=30).json() ``` `GET /v1/runs/{id}/log` is the **only supported way to read a finished run's full trajectory**. It is documented in full below. ### GET /v1/runs List your runs. Query params: `status` (filter), `limit` (default 20). Returns `{ object: "list", data: [Run...], has_more, request_id }`. ### GET /v1/runs/{id} Get one run by id. Returns a `RunResponse`. ### POST /v1/runs/{id}/cancel Cancel an active run. Returns the run with `status: "cancelled"`. ### POST /v1/runs/{id}/resume Hand control back to the agent after a human takeover. Only valid while `status == "awaiting_human"`. Body: `{ "note": "" }`. After resume the run returns to `running`. ```python import os, requests BASE = "https://coasty.ai/v1" HEADERS = {"X-API-Key": os.environ["COASTY_API_KEY"]} run_id = "7a1b2c3d-4e5f-4678-9abc-def012345678" run = requests.get(f"{BASE}/runs/{run_id}", headers=HEADERS, timeout=30).json() if run["status"] == "awaiting_human": print("paused:", run["awaiting_human_reason"]) # ... a human completes the blocking step out of band ... resumed = requests.post( f"{BASE}/runs/{run_id}/resume", headers=HEADERS, json={"note": "Solved the captcha; continue"}, timeout=30, ).json() print(resumed["status"]) # back to "running" ``` ### GET /v1/runs/{id}/events (SSE) Server-Sent Events stream of the run timeline. **Resume is fully supported** (and the values are spelled out here so you do not have to guess them). **Resume.** Pass either the `Last-Event-ID: ` request header **or** the `?after=` query param to replay everything after that sequence; `Last-Event-ID` **takes precedence** when both are present. The cursor is the integer `seq` echoed in each `id:` line and is **monotonic per run**. The transport is ordered **at-least-once**, not exactly-once: the server emits only events whose `seq` is **strictly greater** than the supplied cursor, but a disconnect before the consumer durably records a processed cursor can replay that event. Deduplicate by `(run_id, seq)` and atomically persist the cursor with the side effects it guards. **Persisted replay window is effectively UNBOUNDED.** Successfully appended events are durable in Postgres, so you can resume from `seq=0` for the entire life of the run — there is no short buffer that ages events out. Start a fresh consumer at `?after=0` (or omit it) to get the whole history, then keep the last `seq` you saw as your reconnect cursor. Intermediate `text`, `reasoning`, `tool_*`, `step`, `billing`, pause/resume, status, and error appends are best-effort: a transient database write failure can leave a sequence gap rather than stopping or repeating an OS action. For Agent Runs, the terminal `status` and `done` events are admitted transactionally with terminal run state and are durable. Treat `GET /v1/runs/{id}` as authoritative for current state, and use SSE for the successfully persisted timeline. **Keepalive & framing.** A `: keepalive` comment is sent about every **15s** so the connection is not cut while the run is quiet. Each event is framed `id:` / `event:` / `data:` and carries `{ seq, type, data, created_at }`: ``` : keepalive id: 42 event: status data: {"status":"running"} ``` **Terminal frames (there are TWO).** The stream normally ends with `event: done` and then closes. There is **no `DONE` text sentinel**. But a stream can also be cut off by the server's own wall-clock ceiling. When it is, the last frame is instead: ``` event: timeout data: {"reason":"stream_max_duration"} ``` `event: timeout` is **not** a run outcome. It says the HTTP stream hit its maximum duration, nothing about the run, which may still be running. On receipt, reconnect with your last `seq` as `Last-Event-ID`, or fall back to polling `GET /v1/runs/{id}`. Treat **both** `done` and `timeout` as end-of-stream, and never treat `timeout` as a failure. The same frame terminates `GET /v1/workflows/runs/{id}/events`. **Run event types** | Type | Meaning | | --- | --- | | `status` | The run moved to a new status. | | `text` | A chunk of the agent's narration. | | `reasoning` | A chunk of the model's reasoning, if exposed. | | `tool_call` | The agent invoked a tool (click, keypress, navigation). | | `tool_result` | The result of the most recent tool call. | | `awaiting_human` | The run paused and is waiting for a human. | | `resumed` | Control was handed back after a takeover. | | `step` | A full agent step completed; carries `steps_completed`. | | `billing` | Incremental billing update (`credits_charged`, `cost_cents`). | | `error` | A non-fatal or fatal error occurred. | | `done` | Terminal event. The stream closes after this. | | `timeout` | The **stream** hit its maximum duration (`{"reason":"stream_max_duration"}`). Not a run outcome. Reconnect or poll. | ```bash # -N disables buffering so events arrive as they happen. # Pass Last-Event-ID (the last seq you saw) to replay after a drop. curl -N "https://coasty.ai/v1/runs/$RUN_ID/events" \ -H "X-API-Key: $COASTY_API_KEY" \ -H "Last-Event-ID: 42" ``` ### GET /v1/runs/{run_id}/log **What the run actually did, one record per step.** This is the only supported way to read a finished run's full trajectory, and in most cases the fastest way to recover its final answer. Scope: `runs:read`. `GET /v1/runs/{id}/events` streams the same underlying source over SSE, which suits watching a run live but makes inspecting a finished one awkward. `/log` returns plain JSON, already assembled: the model's reasoning is **split out of its `` markup** for you (`analysis`, `next_action`, `grounded_action`), every action arrives with its coordinates and outcome, and each step carries what it cost. No parsing required. The action **outcome** is not a reasoning field: read it off `actions[].ok` and `actions[].error`, which is the structured form of the same information. **Query params** | Param | Type | Default | Notes | | --- | --- | --- | --- | | `limit` | int | 50 | Steps per page. Range **1-200**. Out of range returns `400 INVALID_LIMIT` with `actual`, `min`, and `max` in the envelope. | | `after_step` | int | 0 | Cursor. Returns steps **after** this step number. Must be `>= 0`; a negative value returns `400 INVALID_EVENT_CURSOR`. | | `include_events` | bool | `false` | Also return the raw events each step was folded from, **nested inside** the step they belong to (never as a parallel array, so a page boundary cannot split a step from its events). | **Response** | Field | Type | Notes | | --- | --- | --- | | `object` | string | Always `"list"`. | | `data` | array | Per-step records (see below), oldest first. | | `lifecycle` | array | Run-level events that belong to no single step: queued/running/done transitions, run-level errors, awaiting-human pauses. Returned **whole on every page** because it is small and usually contains the reason the run stopped. Each entry is `{ seq, type, data, created_at }`. | | `has_more` | bool | Another page exists. | | `next_after_step` | int\|null | Pass as `after_step` to continue. Null when the log is complete. | | `live` | bool | True while the run is still going, so the log will grow. | | `steps_completed` | int | **Authoritative** count from the run record: how many steps actually ran. | | `steps_logged` | int | How many steps this log could reconstruct any evidence for. | | `log_complete` | bool | False when the log is missing steps the run is known to have executed. | | `request_id` | string\|null | Id of this request. | **Per-step record** (`data[]`) | Field | Type | Notes | | --- | --- | --- | | `step` | int | Step number within the attempt. | | `attempt` | int | Execution attempt. A run that is reaped and re-claimed restarts its step counter at 1, so `step` alone is **not** a unique address within a run. Key on `(attempt, step)`. | | `started_at` / `ended_at` | string\|null | ISO-8601. | | `analysis` | string\|null | The model's read of the screen, unwrapped from ``. Any section may be absent. | | `next_action` | string\|null | What it decided to do next, unwrapped. | | `grounded_action` | string\|null | The action after grounding to concrete coordinates, unwrapped. | | `actions` | array | Every tool call in this step, in order: `{ seq, tool, args, ok, error? }`. `args` carries coordinates. This is where the action outcome lives. | | `credits_charged` | int | Credits billed for this step. | | `cost_cents` | int | Same numeric value in cents. | | `screenshot_index` | int\|null | Flat index into `GET /v1/runs/{id}/screenshots` for the frame the agent saw **before** acting, when one was captured. | | `error` | string\|null | Step-level error. | | `events` | array\|null | Raw events, only with `?include_events=true`. | On an action, `ok` is the outcome the agent observed. It is `null` when the run ended before the result was recorded: a step cut off by a deadline or a crash has a call with no result, and reporting that as a failure would be a guess. An action in flight is genuinely different from one that failed. #### Read `log_complete` before concluding anything from an absence The event log is **best effort**. Appends are **not** part of the run's transaction, so a step can execute and be billed while its log rows are lost. This is not hypothetical: a real run whose record says 85 steps retained only 52 step markers, missing 33 outright. That is why three numbers are returned rather than one: - `steps_completed` is **authoritative**. It comes from the run record. - `steps_logged` is how much evidence survived. - `log_complete` is `steps_logged >= steps_completed`. **When `log_complete` is false, `steps_completed` wins, and the absence of a step from `data` is NOT evidence that it did not happen.** A caller debugging "why did it stop at 81" against an incomplete log would be chasing a step that never existed. Check the flag first. **Errors** | Status | Code | When | | --- | --- | --- | | 400 | `INVALID_LIMIT` | `limit` outside 1-200. | | 400 | `INVALID_EVENT_CURSOR` | `after_step` negative. | | 404 | `RUN_NOT_FOUND` | Unknown run, or a run owned by another tenant. Ownership is checked first, so a cross-tenant id 404s rather than returning an empty log (which would confirm the id exists). | | 503 | `DB_UNAVAILABLE` | Event-store read failure. Carries `Retry-After`; retry, do not treat the run as empty. | **Worked example: recover a finished run's final answer and full trajectory** ```python import os, requests BASE = "https://coasty.ai/v1" HEADERS = {"X-API-Key": os.environ["COASTY_API_KEY"]} run_id = "7a1b2c3d-4e5f-4678-9abc-def012345678" # 1. The run record is always authoritative for state and for step count. run = requests.get(f"{BASE}/runs/{run_id}", headers=HEADERS, timeout=30).json() assert run["status"] in {"succeeded", "failed", "cancelled", "timed_out"} # result.summary is the LAST 2000 chars of the trajectory, so it usually already # contains the agent's closing answer. Use it when 2000 chars is enough. print("summary tail:", (run.get("result") or {}).get("summary")) # 2. For the full trajectory, page the log. steps, after, complete = [], 0, True while True: page = requests.get( f"{BASE}/runs/{run_id}/log", headers=HEADERS, params={"limit": 200, "after_step": after}, timeout=30, ) if page.status_code == 503: # event-store blip, not an empty run raise SystemExit("retry after %s" % page.headers.get("Retry-After")) page.raise_for_status() body = page.json() steps.extend(body["data"]) complete = complete and body["log_complete"] lifecycle = body["lifecycle"] # whole on every page if not body["has_more"]: break after = body["next_after_step"] # 3. Trust steps_completed, not len(steps). if not complete: print( "WARNING: log is incomplete. The run executed", body["steps_completed"], "steps but only", body["steps_logged"], "are reconstructable. A missing step did NOT necessarily fail to happen.", ) # 4. The final answer is the last narration the agent produced. final = next( (s for s in reversed(steps) if s.get("analysis") or s.get("next_action") or s.get("grounded_action")), None, ) print("final answer:", (final or {}).get("analysis")) # 5. Lifecycle usually explains why it stopped. for ev in lifecycle: print(ev["type"], ev["data"]) ``` ```bash # First page, with the raw events folded into each step. curl -s "https://coasty.ai/v1/runs/$RUN_ID/log?limit=200&include_events=true" \ -H "X-API-Key: $COASTY_API_KEY" ``` Pair `/log` with `GET /v1/runs/{id}/screenshots` when you need to see what the agent saw: each step's `screenshot_index` is the flat index into that list. ### Run state machine ``` queued -> running -> (awaiting_human <-> running) -> succeeded | failed | cancelled | timed_out ``` Terminal states (`succeeded`, `failed`, `cancelled`, `timed_out`) are immutable. `awaiting_human` is only reached when `on_awaiting_human == "pause"`; with `fail` or `cancel` the run goes straight to the corresponding terminal state. ### Webhooks Pass a `webhook_url` when you create a run. The URL must be **HTTPS-only** and is **SSRF-guarded** (no private, loopback, or link-local hosts are accepted). Coasty POSTs signed JSON callbacks on lifecycle transitions. The create response, including an exact bounded Idempotency-Key replay, returns the per-run signing secret `webhook_secret` (a `whsec_...` value). GET/list never return it: store it, because every callback is signed with it. An Agent Run terminal transition transactionally writes its callback to a durable outbox; the non-terminal `run.awaiting_human` callback is direct and best-effort. **Webhook events** | Event | Meaning | | --- | --- | | `run.awaiting_human` | The run paused and needs a human to take over. | | `run.succeeded` | The run finished and verification passed. | | `run.failed` | The run ended in failure (verification failed or an error). | | `run.cancelled` | The run was cancelled via the cancel endpoint. | | `run.timed_out` | The run breached its deadline before finishing. | **Signature.** Each callback carries a header: ``` Coasty-Signature: t={unix_ts},v1={hex} ``` The signed bytes are `HMAC_SHA256(secret, f"{t}." + raw_request_body)` — i.e. the unix timestamp `t`, a literal `.`, then the **raw** (unparsed) request body. To **verify**: recompute that HMAC over `"{t}." + raw_body`, **constant-time** compare the hex to `v1`, and **reject if `abs(now - t) > 300` seconds** (a ±5-minute tolerance that bounds replay). **Delivery differs by event class.** Every **terminal** callback is durably queued and reaches a terminal ledger state after at most **3 durably recorded delivery attempts**. A worker can crash after sending the HTTP request but before recording its outcome; that ambiguous send is retried after lease expiry and can cause additional duplicate HTTP sends. A recorded connect-error, timeout, or `5xx` makes the next attempt eligible about 30 seconds later; `3xx` redirects are refused and a `4xx` is **terminal**. Because a receiver response or durable acknowledgement can be lost, terminal delivery is at-least-once and receivers **MUST be idempotent**. Every terminal callback attempt carries `Coasty-Delivery: `; the JSON body's `id` is the same UUID, and its logical `delivered_at` timestamp remains stable across retries. Atomically persist that UUID under a unique constraint before applying side effects. The non-terminal `run.awaiting_human` callback has up to 3 in-process attempts with 1-second then 4-second backoff, but no durable outbox or delivery UUID; a process failure can miss it. Dedupe it on `(run.id, event, run.awaiting_human_since)` instead. Treat `GET /v1/runs/{id}` as the **authoritative source of truth**; a missed or duplicated webhook never changes the stored run state. ```python import hashlib, hmac, os, requests BASE = "https://coasty.ai/v1" HEADERS = {"X-API-Key": os.environ["COASTY_API_KEY"]} # 1. Create a run with a webhook_url. Create/exact-replay returns webhook_secret; GET/list do not. run = requests.post( f"{BASE}/runs", headers=HEADERS, json={ "machine_id": "m_9f2c", "task": "Reconcile the invoice against the order", "webhook_url": "https://example.com/hooks/coasty", }, timeout=30, ).json() webhook_secret = run["webhook_secret"] # persist this securely # 2. In your webhook handler, verify the Coasty-Signature header. def verify(raw_body: bytes, signature_header: str, secret: str) -> bool: parts = dict(p.split("=", 1) for p in signature_header.split(",")) signed = f"{parts['t']}.".encode() + raw_body expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, parts["v1"]) # Example (your framework supplies the raw body + header): # ok = verify(request.body, request.headers["Coasty-Signature"], webhook_secret) ``` --- ## 5. Workflows A workflow is a versioned JSON DSL composing many runs with branching, loops, parallelism, asserts, retries, and human approvals. Scopes: `workflows:read` and `workflows:write` (granted to new keys by default). DSL version: `2026-06-01`. The `definition` is validated structurally on create and on ad-hoc start. When a run begins, the definition is **snapshotted** into the run, so editing a workflow never changes an in-flight run (version pinning). Updating a saved workflow bumps its `version`. **Pricing.** A workflow adds no fee of its own. Each `task` step executes as a run and bills the identical per-step rate: $0.05 (5 credits) on `v3`/`v4`/`v5`, $0.08 (8 credits) on `v1`. Control-flow steps — `if`, `assert`, `loop`, `parallel`, `retry`, `human_approval`, `succeed`, `fail` — are **free**. Total spend accrues against `budget_cents` (0 or null = uncapped); breaching it (or `max_iterations`) stops the run with `GUARD_EXCEEDED`. Test keys bill $0. ### Workflow endpoints | Method + path | Scope | Description | | --- | --- | --- | | `POST /v1/workflows` | `workflows:write` | Create a workflow. | | `GET /v1/workflows` | `workflows:read` | List workflows (`limit`, default 20). | | `GET /v1/workflows/{id}` | `workflows:read` | Get a workflow. | | `PUT /v1/workflows/{id}` | `workflows:write` | Update (bumps version). | | `DELETE /v1/workflows/{id}` | `workflows:write` | Archive a workflow. | | `POST /v1/workflows/{id}/runs` | `workflows:write` | Start a run of a saved workflow. | | `POST /v1/workflows/runs` | `workflows:write` | Start an ad-hoc run (inline `definition`). | | `GET /v1/workflows/runs` | `workflows:read` | List workflow runs (`workflow_id`, `limit`). | | `GET /v1/workflows/runs/{id}` | `workflows:read` | Get a workflow run. | | `GET /v1/workflows/runs/{id}/events` | `workflows:read` | SSE stream (Last-Event-ID replay). | | `POST /v1/workflows/runs/{id}/cancel` | `workflows:write` | Cancel a workflow run. | | `POST /v1/workflows/runs/{id}/resume` | `workflows:write` | Approve/reject a paused step. | Note: the static `/runs` subtree is declared before the dynamic `/{workflow_id}` routes, so `runs` is never captured as a workflow id. ### POST /v1/workflows (create) **Request body** | Field | Type | Req | Notes | | --- | --- | --- | --- | | `name` | string | yes | 1-128 chars. | | `slug` | string | yes | Stable per-account handle, matches `^[a-z0-9][a-z0-9_-]{0,62}$`. | | `definition` | object | yes | The workflow DSL (validated server-side). | | `inputs_schema` | object\|null | no | Typed input declarations: `{name: {type, required?, default?}}`. | | `description` | string\|null | no | Up to 2000 chars. | | `metadata` | object\|null | no | Opaque. | **Response** (`WorkflowResponse`): `{ id, object: "workflow", name, slug, version, dsl_version, definition, inputs_schema, description, status, metadata, created_at, updated_at, request_id }`. `PUT /v1/workflows/{id}` accepts optional `name`, `definition`, `inputs_schema`, `description`, `status` (`active` | `archived`), and `metadata`. Every successful PUT increments `version` exactly once, including metadata-only updates. A concurrent update based on a stale version returns `409 CONFLICT`; GET the workflow again, reapply the intended change to the latest state, and retry. ### Workflow DSL spec The `definition` holds a `steps` array (and optional top-level `output`). Each step is `{ id, type, ... }` where `id` matches `^[A-Za-z0-9_-]{1,64}$`. **Step types (9)** | Type | Shape | Description | | --- | --- | --- | | `task` | `{ id, type, task, machine_id?, cua_version?, instructions?, system_prompt?, max_steps?, save_as?, on_awaiting_human? }` | Run an agent task. Supports `{{var}}` templating. Binds its result under `save_as` and under the step id. | | `assert` | `{ id, type, condition, message? }` | Fail the workflow unless the structured condition holds. | | `if` | `{ id, type, condition, then: [...], else?: [...] }` | Branch on a structured condition. | | `loop` | `{ id, type, (count: int \| while: condition), body: [...], max_iterations? }` | Repeat a body a fixed number of times or while a condition holds. | | `parallel` | `{ id, type, branches: [[...], [...]] }` | Run independent branches concurrently. | | `human_approval` | `{ id, type, message?, timeout_seconds? }` | Pause for a human to approve or reject before continuing. | | `retry` | `{ id, type, body: [...], max_attempts: int }` | Retry a body up to `max_attempts` times on failure. | | `succeed` | `{ id, type, output?: {} }` | Finish the workflow successfully with an optional output. | | `fail` | `{ id, type, message? }` | Finish the workflow as failed with an optional message. | **Structured conditions (13 ops, injection-safe, no free-text eval)** | Op | Shape | Meaning | | --- | --- | --- | | `eq` / `ne` | `{ op, left, right }` | Equal / not equal. | | `lt` / `gt` / `lte` / `gte` | `{ op, left, right }` | Ordered numeric comparison. | | `contains` | `{ op, left, right }` | `left` contains `right` (substring or membership). | | `truthy` / `falsy` / `exists` | `{ op, value }` | Test a single value for truthiness, falsiness, or presence. | | `and` / `or` | `{ op, conditions: [...] }` | Combine several conditions. | | `not` | `{ op, condition }` | Negate a condition. | **Variable references** `{{path}}` resolve dotted paths into `{inputs, vars, }`: - `{{inputs.x}}` reads a bound input value. - `{{vars.y}}` reads a workflow variable. - `{{stepId.field}}` reads a prior task's result. A `task` binds: `{ status, passed, result, run_id, steps, error }`. For a step saved as `invoice` you can reference `{{invoice.passed}}` or `{{invoice.result}}`. **Hard guards** (set when starting a run, enforced during execution) - `budget_cents`: total spend cap across all task steps (0 or null = unlimited). - `max_iterations`: cap on total loop iterations consumed. - `deadline_seconds`: wall-clock budget for the whole workflow run. **Validation limits** (enforced at create / ad-hoc time) | Limit | Rule | | --- | --- | | Max steps | At most 200 steps total (counting every nested step). | | Max nesting depth | Steps nest at most 8 levels deep (if/loop/parallel/retry bodies). | | Parallel branches | A `parallel` step takes at most 16 branches; they run concurrently. | | Retry attempts | `retry.max_attempts` is an integer from 1 to 20. | | Parallel contents | `human_approval`, `succeed`, and `fail` are not allowed inside a parallel branch. | | save_as name | `save_as` must not be `"inputs"` or `"vars"` (reserved namespaces). | **Complete example DSL** (task -> assert -> if/branch): ```json { "steps": [ { "id": "fetch", "type": "task", "task": "Open order {{inputs.order_id}} and read the invoice total", "save_as": "invoice" }, { "id": "check", "type": "assert", "condition": { "op": "truthy", "value": "{{invoice.passed}}" }, "message": "Agent failed to read the invoice" }, { "id": "branch", "type": "if", "condition": { "op": "contains", "left": "{{invoice.result}}", "right": "PAID" }, "then": [{ "id": "ok", "type": "succeed", "output": { "state": "paid" } }], "else": [{ "id": "no", "type": "fail", "message": "Invoice not marked paid" }] } ], "output": { "paid": "{{invoice.result}}" } } ``` ### Starting a workflow run `POST /v1/workflows/{id}/runs` (saved) or `POST /v1/workflows/runs` (ad-hoc with an inline `definition`). **Request body** (`StartWorkflowRunRequest`) | Field | Type | Req | Notes | | --- | --- | --- | --- | | `inputs` | object\|null | no | Bound input values, available as `{{inputs.*}}`. | | `machine_id` | string\|null | no | Default machine for task steps that omit their own. | | `budget_cents` | int\|null | no | Spend cap, 0-10000000 (0/null = unlimited). | | `max_iterations` | int\|null | no | 1-100000. | | `deadline_seconds` | int\|null | no | 1-86400. | | `webhook_url` | string\|null | no | Lifecycle callbacks. | | `metadata` | object\|null | no | Opaque. | | `definition` | object\|null | no | For ad-hoc runs without a saved workflow. | | `inputs_schema` | object\|null | no | For ad-hoc runs. | | `action_policy` | object\|null | no | Create-time policy inherited by every task step, retry, recovery, and nested CUA delegation. | Saved and ad-hoc Workflow Runs atomically persist `action_policy` and pass it unchanged to every task step and nested delegation. Workflow budgets, iteration/deadline guards, approvals, and assertions remain independent. Supports the `Idempotency-Key` header (same semantics as runs). **The Workflow Run object** (`WorkflowRunResponse`) | Field | Type | Notes | | --- | --- | --- | | `id` | string | Workflow-run id. | | `object` | string | Always `"workflow.run"`. | | `status` | string | `queued` / `running` / `awaiting_human` / `succeeded` / `failed` / `cancelled` / `timed_out`. | | `workflow_id` | string\|null | The workflow this run belongs to (null for inline runs). | | `workflow_version` | int\|null | Version of the definition that ran. | | `machine_id` | string\|null | Default machine for task steps. | | `inputs` | object | The inputs you passed in. | | `output` | object\|null | Produced by a `succeed` step. | | `error` | object\|null | `{ code, message }` when failed. | | `awaiting_human_reason` | string\|null | Why the run paused. | | `awaiting_step_id` | string\|null | The step id awaiting approval. | | `iterations_used` | int | Loop iterations consumed. | | `spent_cents` | int | Total spend so far (USD cents). | | `budget_cents` | int | Spend cap (0 = unlimited). | | `webhook_url` | string\|null | Lifecycle callbacks. | | `webhook_secret` | string\|null | Returned by create and an exact bounded Idempotency-Key replay; null on get/list. | | `metadata` | object\|null | Opaque. | | `created_at` / `started_at` / `finished_at` | string\|null | Timestamps. | | `request_id` | string\|null | Id of the create request. | `resume` body (`POST /v1/workflows/runs/{id}/resume`): `{ "approved": true, "note": "" }`. `approved: false` rejects (fails) the pending `human_approval` step. **Example workflow run response:** ```json { "id": "wfr_5e6f7a8b", "object": "workflow.run", "status": "running", "workflow_id": "wf_1a2b3c", "workflow_version": 3, "machine_id": "m_9f2c", "inputs": { "order_id": "ord_4821" }, "output": null, "error": null, "awaiting_human_reason": null, "awaiting_step_id": null, "iterations_used": 0, "spent_cents": 0, "budget_cents": 500, "created_at": "2026-06-01T12:00:00Z", "started_at": "2026-06-01T12:00:01Z", "finished_at": null, "request_id": "req_9c8b7a6d" } ``` **curl: create a workflow, then start a run** ```bash BASE=https://coasty.ai/v1 AUTH="X-API-Key: $COASTY_API_KEY" # 1. Create a workflow: a task step, an assert, then an if/branch. WF_ID=$(curl -s "$BASE/workflows" -H "$AUTH" \ -H "Content-Type: application/json" \ -d '{ "name": "Invoice reconciliation", "slug": "invoice-reconcile", "inputs_schema": {"type": "object", "properties": {"order_id": {"type": "string"}}}, "definition": { "steps": [ {"id": "fetch", "type": "task", "task": "Open order {{inputs.order_id}} and read the invoice total", "save_as": "invoice"}, {"id": "check", "type": "assert", "condition": {"op": "truthy", "value": "{{invoice.passed}}"}, "message": "Agent failed to read the invoice"}, {"id": "branch", "type": "if", "condition": {"op": "contains", "left": "{{invoice.result}}", "right": "PAID"}, "then": [{"id": "ok", "type": "succeed", "output": {"state": "paid"}}], "else": [{"id": "no", "type": "fail", "message": "Invoice not marked paid"}]} ] } }' | python -c "import sys,json;print(json.load(sys.stdin)['id'])") # 2. Start a run of the saved workflow. curl -s "$BASE/workflows/$WF_ID/runs" -H "$AUTH" \ -H "Content-Type: application/json" \ -d '{"inputs": {"order_id": "ord_4821"}, "machine_id": "m_9f2c", "budget_cents": 500}' ``` **Python** ```python import os, requests BASE = "https://coasty.ai/v1" HEADERS = {"X-API-Key": os.environ["COASTY_API_KEY"]} definition = { "steps": [ {"id": "fetch", "type": "task", "save_as": "invoice", "task": "Open order {{inputs.order_id}} and read the invoice total"}, {"id": "check", "type": "assert", "condition": {"op": "truthy", "value": "{{invoice.passed}}"}, "message": "Agent failed to read the invoice"}, {"id": "branch", "type": "if", "condition": {"op": "contains", "left": "{{invoice.result}}", "right": "PAID"}, "then": [{"id": "ok", "type": "succeed", "output": {"state": "paid"}}], "else": [{"id": "no", "type": "fail", "message": "Invoice not marked paid"}]}, ], } # 1. Create the workflow. Re-using the same slug bumps its version. wf = requests.post( f"{BASE}/workflows", headers=HEADERS, json={ "name": "Invoice reconciliation", "slug": "invoice-reconcile", "inputs_schema": {"type": "object", "properties": {"order_id": {"type": "string"}}}, "definition": definition, }, timeout=30, ).json() print(wf["id"], "v", wf["version"], wf["dsl_version"]) # 2. Start a run of the saved workflow. run = requests.post( f"{BASE}/workflows/{wf['id']}/runs", headers=HEADERS, json={"inputs": {"order_id": "ord_4821"}, "machine_id": "m_9f2c", "budget_cents": 500}, timeout=30, ).json() print(run["id"], run["status"]) ``` Workflow run events use the same ordered, at-least-once cursor contract for every successfully persisted frame (`GET /v1/workflows/runs/{id}/events`, `Last-Event-ID` replay). Workflow intermediate **and terminal** event appends, and Workflow lifecycle callbacks, are currently best-effort in-process writes; they can be missed if storage or the worker fails between the durable state transition and notification. Reconcile with `GET /v1/workflows/runs/{id}`, which is authoritative, instead of waiting forever for a terminal event or callback. `GET /v1/workflows/runs/{id}/events` shares the run stream's **two terminal frames**: normally `event: done`, but `event: timeout` with `data: {"reason":"stream_max_duration"}` when the HTTP stream hits its own wall-clock ceiling. `timeout` says nothing about the workflow run, which may still be executing. Treat both as end-of-stream, then reconnect with your last `seq` as `Last-Event-ID` or poll `GET /v1/workflows/runs/{id}`. --- ## Local automation — automate ANY screen (no VM required) `/v1/predict`, `/v1/ground` and `/v1/sessions` are **screen-agnostic**: a screenshot goes in, coordinates and typed actions come out. The pixels can come from anywhere — the user's own desktop, a Playwright/Puppeteer browser page, an Android emulator (`adb exec-out screencap`), a VNC/RDP framebuffer, a Citrix window. Coasty-managed VMs (`/v1/machines`) are one execution target, not the only one. To automate locally you write a small loop: capture → predict → execute → repeat. ### The local agent loop (your own desktop) ```python # Automate YOUR screen — no VM needed. pip install requests mss pyautogui pillow import base64, contextlib, email.utils, io, json, os, random, time, uuid, requests, mss, pyautogui from datetime import timezone from PIL import Image API = "https://coasty.ai/v1" KEY = os.environ["COASTY_API_KEY"] # use a live key for real managed inference HDRS = {"X-API-Key": KEY, "Content-Type": "application/json"} pyautogui.FAILSAFE = True # slam the mouse into a corner to abort instantly REAL_W, REAL_H = pyautogui.size() # your actual desktop resolution SEND_W, SEND_H = 1280, 720 # what we tell the model (SD = 1 credit cheaper) SX, SY = REAL_W / SEND_W, REAL_H / SEND_H # scale model coords -> real pixels def screenshot_b64(): with mss.mss() as sct: shot = sct.grab(sct.monitors[1]) # primary monitor img = Image.frombytes("RGB", shot.size, shot.bgra, "raw", "BGRX") img = img.resize((SEND_W, SEND_H)) # MUST match screen_width/height buf = io.BytesIO(); img.save(buf, format="PNG") return base64.b64encode(buf.getvalue()).decode() WINDOW_CLOSE_ACTIONS = { "close_window", "window_close", "browser_close", "browser_close_tab", "close_tab", "terminal_close", } KEY_ALIASES = { "esc": "escape", "return": "enter", "control": "ctrl", "ctl": "ctrl", "command": "cmd", "super": "cmd", "win": "cmd", "windows": "cmd", "meta": "cmd", "option": "alt", "ctrl_l": "ctrl", "ctrl_r": "ctrl", "control_l": "ctrl", "control_r": "ctrl", "cmd_l": "cmd", "cmd_r": "cmd", "command_l": "cmd", "command_r": "cmd", "meta_l": "cmd", "meta_r": "cmd", "super_l": "cmd", "super_r": "cmd", "win_l": "cmd", "win_r": "cmd", "windows_l": "cmd", "windows_r": "cmd", "alt_l": "alt", "alt_r": "alt", "option_l": "alt", "option_r": "alt", } PYAUTOGUI_KEY_ALIASES = { "cmd": "command", "meta": "command", "return": "enter", "esc": "escape", "option": "alt", "ctrl_l": "ctrl", "ctrl_r": "ctrl", "control_l": "ctrl", "control_r": "ctrl", "cmd_l": "command", "cmd_r": "command", "command_l": "command", "command_r": "command", "meta_l": "command", "meta_r": "command", "super_l": "command", "super_r": "command", "win_l": "command", "win_r": "command", "windows_l": "command", "windows_r": "command", "alt_l": "alt", "alt_r": "alt", "option_l": "alt", "option_r": "alt", } def pyautogui_key(value): key = str(value).strip().lower() return PYAUTOGUI_KEY_ALIASES.get(key, key) def type_text_literal(value): # PyAutoGUI 0.9.x cannot faithfully type arbitrary Unicode. Never silently # drop patient names/notes: use an OS-native Unicode implementation in a # production desktop driver, or fail visibly as this portable sample does. if not value.isascii(): raise RuntimeError("type_text contains non-ASCII text; configure an OS-native Unicode typer") pyautogui.write(value, interval=0.02) @contextlib.contextmanager def held_keys(values): keys = [pyautogui_key(value) for value in (values or [])] for key in keys: pyautogui.keyDown(key) try: yield finally: for key in reversed(keys): pyautogui.keyUp(key) def normalized_keys(a): p = a.get("params", {}) values = [] for field in ("key", "keys", "hold_keys", "modifiers"): raw = p.get(field) values.extend([raw] if isinstance(raw, str) else (raw or [])) keys = set() for value in values: for part in str(value).strip().lower().replace("-", "+").split("+"): part = part.strip() if part: keys.add(KEY_ALIASES.get(part, part)) return keys def prohibited(a): keys = normalized_keys(a) return ( "escape" in keys or a["action_type"] in WINDOW_CLOSE_ACTIONS or {"alt", "f4"} <= keys or (("ctrl" in keys or "cmd" in keys) and "w" in keys) or {"cmd", "q"} <= keys ) def execute(a): t, p = a["action_type"], a["params"] if t in ("done", "fail"): return # terminal signals have no OS effect if t == "click": with held_keys(p.get("hold_keys")): pyautogui.click(p["x"] * SX, p["y"] * SY, clicks=p.get("clicks", 1), button=p.get("button", "left")) elif t == "move": pyautogui.moveTo(p["x"] * SX, p["y"] * SY) elif t == "type_text": type_text_literal(p["text"]) elif t == "key_press": pyautogui.press([pyautogui_key(k) for k in p["keys"]]) elif t == "key_combo": pyautogui.hotkey(*[pyautogui_key(k) for k in p["keys"]]) elif t == "scroll": if "x" in p: pyautogui.moveTo(p["x"] * SX, p["y"] * SY) if p.get("direction", "vertical") == "horizontal": pyautogui.hscroll(p["clicks"]) # +right / -left else: pyautogui.scroll(p["clicks"]) # +up / -down elif t == "drag": pyautogui.moveTo(p["x1"] * SX, p["y1"] * SY) with held_keys(p.get("hold_keys")): pyautogui.dragTo(p["x2"] * SX, p["y2"] * SY, duration=0.4, button=p.get("button", "left")) elif t == "wait": time.sleep(p["seconds"]) else: raise RuntimeError(f"unsupported action: {t}") def parse_retry_after_seconds(raw): if raw is None: return None try: return max(0.0, float(raw)) # delta-seconds except (TypeError, ValueError): try: # IMF-fixdate HTTP-date dt = email.utils.parsedate_to_datetime(str(raw)) if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) return max(0.0, dt.timestamp() - time.time()) except (TypeError, ValueError, OverflowError): return None def retry_after_seconds(res, error): # Header and canonical body are independent signals. Honor the largest # valid delay so a smaller or malformed intermediary header cannot shorten # the server's requested wait. candidates = ( parse_retry_after_seconds(res.headers.get("Retry-After")), parse_retry_after_seconds(error.get("retry_after")), ) valid = [value for value in candidates if value is not None] return max(valid) if valid else None def reconcile_idempotency(request_key, max_wait_seconds=600, initial_delay_seconds=0): """Collect a lost reserve-and-replay result; never invent a fresh operation.""" url = f"{API}/idempotency/{request_key}" deadline = time.monotonic() + max_wait_seconds if initial_delay_seconds > max_wait_seconds: raise RuntimeError( f"server Retry-After exceeds foreground reconciliation budget; " f"resume GET {url} after {initial_delay_seconds:.1f}s" ) if initial_delay_seconds > 0: time.sleep(initial_delay_seconds) attempt = 0 while True: delay = None try: res = requests.get(url, headers=HDRS, timeout=15) except requests.RequestException: res = None if res is not None: try: envelope = res.json() if not isinstance(envelope, dict): envelope = {} error = envelope.get("error") or {} if not isinstance(error, dict): error = {} except (ValueError, AttributeError, requests.RequestException): envelope, error = {}, {} print({ "reconcile_status": res.status_code, "x_request_id": res.headers.get("X-Request-Id"), "x_coasty_request_id": res.headers.get("X-Coasty-Request-Id"), "body_request_id": error.get("request_id") or envelope.get("request_id"), "cf_ray": res.headers.get("CF-Ray"), "idempotency_key": request_key, }) if res.ok and envelope.get("status") == "completed": original_status = envelope.get("original_status") result = envelope.get("result") if isinstance(original_status, int) and 200 <= original_status < 300 and isinstance(result, dict): return result raise RuntimeError( f"original operation completed with HTTP {original_status}; " f"inspect reconciled result for key={request_key}: {str(result)[:500]}" ) if res.ok and envelope.get("status") != "processing": raise RuntimeError(f"malformed idempotency lookup for key={request_key}") if res.status_code == 404: raise RuntimeError( f"idempotency key={request_key} is unknown or expired; outcome remains " "ambiguous. Do not start a replacement operation until resource state is checked." ) if not res.ok and res.status_code not in (429, 502, 503, 504): res.raise_for_status() delay = retry_after_seconds(res, error) remaining = deadline - time.monotonic() jitter = random.uniform(0, min(30, 2 ** min(attempt, 5))) delay = max(delay or 0, jitter) if remaining <= 0 or delay > remaining: raise RuntimeError( f"idempotency result still pending for key={request_key}; " f"resume GET {url} before any new operation" ) time.sleep(delay) attempt += 1 def post_with_retry(url, request_key, payload): # These documented POST routes are reserve-and-replay capable: keep the # same key and byte-equivalent body for transport/edge retries. Typed # failures must also explicitly permit same-key replay. body = json.dumps(payload, separators=(",", ":"), ensure_ascii=False) first_failure_at = None for attempt in range(4): # initial send + at most 3 retries delay = None remaining = ( 120.0 if first_failure_at is None else 120.0 - (time.monotonic() - first_failure_at) ) if remaining <= 0: return reconcile_idempotency(request_key) try: res = requests.post( url, headers={**HDRS, "Idempotency-Key": request_key}, data=body, # byte-identical across same-key retries timeout=max(0.001, min(120.0, remaining)), ) except requests.RequestException: print(f"transport failure attempt={attempt + 1} idempotency_key={request_key}") else: if res.ok: try: result = res.json() if isinstance(result, dict): return result except (ValueError, requests.RequestException): pass # A 2xx with a truncated/malformed body may have committed. The # keyed lookup recovers the stored response without a new POST. return reconcile_idempotency(request_key) try: envelope = res.json() if not isinstance(envelope, dict): envelope = {} error = envelope.get("error", {}) if not isinstance(error, dict): error = {} except (ValueError, AttributeError, requests.RequestException): envelope = {} error = {} ids = { "x_request_id": res.headers.get("X-Request-Id"), "x_coasty_request_id": res.headers.get("X-Coasty-Request-Id"), "body_request_id": error.get("request_id") or envelope.get("request_id"), "cf_ray": res.headers.get("CF-Ray"), "idempotency_key": request_key, } print(f"retry context attempt={attempt + 1}: {ids}") if error: if error.get("retryable") is not True: res.raise_for_status() if error.get("retry_with_same_idempotency_key") is not True: raise RuntimeError( "Retryable response did not permit same-key replay; inspect state " "before starting a new logical operation." ) if error.get("code") == "IDEMPOTENCY_IN_FLIGHT": return reconcile_idempotency( request_key, initial_delay_seconds=retry_after_seconds(res, error) or 0, ) elif res.status_code not in (429, 502, 503, 504): res.raise_for_status() delay = retry_after_seconds(res, error) first_failure_at = first_failure_at or time.monotonic() delay = delay if delay is not None else random.uniform(0, min(30, 2 ** attempt)) elapsed = time.monotonic() - first_failure_at if attempt == 3 or elapsed + delay > 120: # Do not poll before a server-directed Retry-After. Hand the delay # to reconciliation; if it exceeds that budget, the helper tells # the caller exactly when and where to resume GET polling. return reconcile_idempotency( request_key, initial_delay_seconds=delay, ) time.sleep(delay) def predict_with_retry(request_key, payload): return post_with_retry(f"{API}/sessions/{sid}/predict", request_key, payload) def delete_session_with_reconciliation(session_id): url = f"{API}/sessions/{session_id}" deadline = time.monotonic() + 120 for attempt in range(3): server_delay = None try: deleted = requests.delete(url, headers=HDRS, timeout=15) except requests.RequestException: deleted = None if deleted is not None: if deleted.ok or deleted.status_code == 404: return if deleted.status_code not in (429, 502, 503, 504): deleted.raise_for_status() try: envelope = deleted.json() if not isinstance(envelope, dict): envelope = {} error = envelope.get("error") or {} if not isinstance(error, dict): error = {} except (ValueError, AttributeError, requests.RequestException): error = {} server_delay = retry_after_seconds(deleted, error) print({ "cleanup_status": deleted.status_code, "x_request_id": deleted.headers.get("X-Request-Id"), "x_coasty_request_id": deleted.headers.get("X-Coasty-Request-Id"), "cf_ray": deleted.headers.get("CF-Ray"), }) # A lost DELETE response is ambiguous. GET is authoritative: 404 means # cleanup completed; 200 means the slot still exists and DELETE may retry. try: state = requests.get(url, headers=HDRS, timeout=15) if state.status_code == 404: return except requests.RequestException: state = None if attempt < 2: delay = max( server_delay or 0, random.uniform(0, min(4, 2 ** attempt)), ) if delay > deadline - time.monotonic(): raise RuntimeError( f"session cleanup retry exceeds budget; honor Retry-After and resume GET {url}" ) time.sleep(delay) raise RuntimeError(f"session cleanup unconfirmed; reconcile GET {url}") # A live Coasty key gives real managed inference. A test key without explicit # BYOK provider headers returns deterministic sandbox output rather than a model. session_payload = { "cua_version": "v5", "screen_width": SEND_W, "screen_height": SEND_H, "action_policy": { "allowed_actions": [ "click", "move", "type_text", "key_press", "key_combo", "scroll", "drag", "wait", ], "blocked_keys": ["escape"], "block_window_close": True, "max_actions": 5, }, } create_key = f"session-create-{uuid.uuid4().hex}" sess = post_with_retry(f"{API}/sessions", create_key, session_payload) sid = sess["session_id"] micro_goal = "Goal: compute 42 * 17. Expected screen: calculator shows 714. [done] when 714 is visible." verify_goal = "Verify only whether the calculator visibly shows 714. Return done if visible; otherwise describe the mismatch. Do not click or type." instruction = micro_goal completed = False rejections = 0 try: for step in range(25): request_key = f"step-{sid}-{step}-{uuid.uuid4().hex[:8]}" payload = {"screenshot": screenshot_b64(), "instruction": instruction} r = predict_with_retry(request_key, payload) print(f"step {r['step']}: {r['reasoning'][:80]}") policy_failure = next(( a for a in r["actions"] if a["action_type"] == "fail" and a.get("params", {}).get("code") == "ACTION_POLICY_VIOLATION" ), None) rejected = next((a for a in r["actions"] if prohibited(a)), None) if policy_failure or rejected: # Server policy rejects its whole batch. The client check is defense # in depth. Execute NOTHING, observe again, and explain the rejection # to this same session with a new key. rejections += 1 if rejections >= 3: raise RuntimeError( "three prohibited-action proposals; human review required" ) instruction = ( "CONTROL FEEDBACK: the previous prohibited action was rejected and " "NOT executed. The next screenshot is authoritative. Continue without " "Escape or closing any window." ) time.sleep(0.5) continue rejections = 0 if r["status"] == "fail": raise RuntimeError(f"agent failed: {r['reasoning']}") for action_index, a in enumerate(r["actions"]): # A production driver durably journals (request_key, action_index) # as PREPARED before input and COMPLETED after it. On restart, a # leftover PREPARED action is ambiguous: capture a fresh screenshot # and re-plan; never blindly execute that action again. execute(a) time.sleep(0.5) # let the UI settle if r["status"] == "done": # done is a model claim. Verify from pixels captured AFTER the last # action; also assert application/DOM state here when available. verify_payload = {"screenshot": screenshot_b64(), "instruction": verify_goal} verified = predict_with_retry(f"verify-{sid}-{uuid.uuid4().hex}", verify_payload) mutating = [ a for a in verified["actions"] if a["action_type"] not in ("done", "fail") ] if mutating or verified["status"] != "done": raise RuntimeError(f"completion mismatch: {verified['reasoning']}") completed = True print("finished and freshly verified") break instruction = micro_goal if not completed: raise RuntimeError("step cap reached before verified completion") finally: delete_session_with_reconciliation(sid) # stop the session clock ``` For a browser, use a fixed 1280x720 Playwright viewport so coordinates map 1:1 (`page.screenshot()` in, `page.mouse.click(x, y)` out — no scaling at all). For Android: `adb exec-out screencap -p` in, `adb shell input tap x y` out. ### Coordinate scaling — the #1 pitfall Coordinates come back **in the same space as the screenshot you sent**. If you downscale (e.g. a 2560x1440 desktop resized to 1280x720 to save a credit), multiply returned x/y by your scale factor before clicking. On `/v1/predict` and `/v1/ground`, `screen_width`/`screen_height` are now **optional**: omit them and the server measures the **screenshot's true size** (it no longer assumes 1920x1080). So an omitted-dims SD screenshot bills SD — the old trap where leaving them out silently defaulted to 1920x1080 (HD, +1 credit) is **gone**. To be unambiguous, the response **echoes** the `screen_width`/ `screen_height` it used, which is exactly the space the returned `(x, y)` live in — read those back instead of guessing. Still, a screenshot whose pixels do not match the coordinate space you click in is the number-one cause of "it clicks the wrong place", so keep capture, predict, and click in one resolution (or scale deliberately by the echoed dims). ### Executing every action type locally | action_type | params | desktop (pyautogui) | browser (Playwright) | | --- | --- | --- | --- | | `click` | x, y, button?=left, clicks?=1, hold_keys? | hold keys; `pyautogui.click(x, y, clicks, button)`; release | hold keys; `page.mouse.click(x, y, {button, clickCount})`; release | | `move` | x, y | `pyautogui.moveTo(x, y)` | `page.mouse.move(x, y)` | | `type_text` | literal text (does not read clipboard) | portable sample rejects non-ASCII; production desktop drivers need a validated OS-native Unicode typer | `page.keyboard.insertText(text)` | | `key_press` | 1-100 sequential taps | `pyautogui.press(keys)` | `page.keyboard.press(...)` once per key | | `key_combo` | 2-8 keys held as one chord | normalize `cmd` to PyAutoGUI `command`; `pyautogui.hotkey(*keys)` | `page.keyboard.press("Control+V")` | | `scroll` | clicks (+up / −down; +right / −left when horizontal), direction?, x?, y? | move to optional anchor; `scroll` or `hscroll` | move to optional anchor; `mouse.wheel(deltaX, deltaY)` | | `drag` | x1, y1, x2, y2, button?=left, hold_keys? | hold keys; `moveTo`; `dragTo(..., button)`; release | hold keys; `move/down(button)/move/up(button)`; release | | `wait` | seconds | `time.sleep(seconds)` | `page.waitForTimeout(s * 1000)` | | `done` | — | stop the ordinary loop; freshly verify before accepting completion | same | | `fail` | — | agent blocked — stop, read `reasoning` | same | ### Prompt presets (best-suggestion `instructions` values) `instructions` is APPENDED to the tuned base agent prompt (unlike `system_prompt`, which replaces it — prefer `instructions`). **Availability and budget.** Custom prompts are available on **every tier, including Free**. There is no plan gate. Every tier resolves to the same **32,000 character** budget. **The budget is SHARED.** `system_prompt` and `instructions` are summed against one allowance, not measured separately: ``` len(system_prompt) + len(instructions) > 32000 -> 400 INPUT_TOO_LARGE ``` The wire schema accepts `system_prompt` up to 32,000 **and** `instructions` up to 16,000, so a body that passes schema validation can still be rejected by the shared budget at 48,000 combined. Size the pair together, not each one against the schema maximum. If a deployment configures a tier's budget to 0, custom prompts are disabled for that tier and any non-empty value returns `400 FEATURE_NOT_AVAILABLE` instead. That is a configuration choice, not the shipped default. Pass a preset on session create (applies to every step) or per predict call. The presets: * **Precise UI control** (default pick): "Be precise. Before clicking, confirm the target element is actually visible in the CURRENT screenshot — never click from memory of a previous screen. Click the visual center of elements, not their edges. If the element you need is not visible, scroll toward where it should be instead of guessing coordinates. If two elements look similar, prefer the one whose text matches the task exactly. After typing into a field, verify focus landed in the right field before continuing." * **Forms & data entry**: "You are doing data entry. Prefer keyboard navigation (Tab between fields, Enter to submit) over clicking when a form has focus. Clear a field (ctrl+a then type) before entering a new value — never append to stale text. Enter values EXACTLY as given in the task: do not reformat dates, trim IDs, or autocorrect spellings. After filling each field, confirm the screenshot shows the value you typed. Do not submit the form until every required field is verified filled." * **QA & regression testing**: "You are executing a QA test step. Follow the instruction literally — do NOT improvise workarounds when the UI misbehaves; surfacing the failure is the point. If an expected element is missing, a button is disabled, or an error/dialog appears that the task does not mention, stop and emit fail() with what you observed. Wait for loading indicators to finish before asserting anything. If warnings or console-style error text appear, stop and fail() with what you see." * **Read & extract**: "Your goal is to READ information from the screen, not to change anything. Interact only to reveal the data (scroll, switch tabs, expand rows) — never edit, submit, or delete. When you can see the requested information, write the extracted values verbatim as plain text before your code block — for this task that text IS the deliverable and overrides the code-only response format — exactly as rendered on screen including units and punctuation, then emit done(). If the data spans multiple screens, scroll through all of it before finishing." * **Cautious (non-destructive)**: "Operate in non-destructive mode. NEVER click buttons that delete, remove, purchase, pay, send, post, publish, or permanently change state — if completing the task requires one, stop and emit fail() explaining which action needs human approval. Never enter credentials, 2FA codes, or payment details even if a login wall appears: fail() and describe the prompt instead. Dismissing cookie banners and closing popups is allowed. When in doubt about whether an action is reversible, do not take it." * **Fast batch mode**: "This is a repetitive batch task on a UI you have already seen. You may chain click field, type value, Tab in one step here: the usual one-state-change rule is relaxed on this stable UI. Skip re-verifying elements that were stable in previous screenshots. Still stop immediately if the screen layout changes unexpectedly, an error appears, or a click lands on the wrong element — batch speed never justifies compounding a mistake." ### Local-run safety You are giving a model control of a real mouse and keyboard. Keep `pyautogui.FAILSAFE` on (mouse to a corner aborts) and run with a step cap. An `Idempotency-Key` deduplicates prediction and billing when the same body is retried; it does **not** make caller-executed mouse, keyboard, browser, or OS inputs exactly once. Durably journal `(request_key, action_index)` as prepared before input and completed after it. If a crash leaves a prepared action ambiguous, capture a fresh screenshot, verify state, and re-plan instead of repeating it. Use the Cautious preset around anything irreversible. Develop against a `sk-coasty-test-*` key (free) and switch to live only after the loop is stable. --- ## 6. Reference ### Action types Every action type the model can return in `actions`. **This is the canonical wire shape** — the exact `params` keys returned in `PredictResponse.actions` (list-shaped `key_press.keys`, seconds-based `wait`, `x1/y1/x2/y2` drag). The "Executing every action type locally" table above maps these same params to pyautogui / Playwright. | Type | Params | Description | | --- | --- | --- | | `click` | `{ x, y, button?, clicks?, hold_keys? }` | Click at the pixel coordinate (`button` defaults to `"left"`, `clicks` to 1; up to 8 held keys). | | `type_text` | `{ text }` | Type the supplied literal string at the current focus. It does not read or paste the clipboard. | | `key_press` | `{ keys: [..] }` | Tap 1-100 keys sequentially, releasing each before the next, e.g. `["enter"]` or `["tab", "tab", "enter"]`. | | `key_combo` | `{ keys: [..] }` | Hold 2-8 keys as one chord, e.g. `["ctrl", "v"]` or `["cmd", "v"]`. | | `scroll` | `{ clicks, direction?, x?, y? }` | Scroll at a position. `clicks` is signed (+up / -down); `direction` is one of `"vertical"` (default) or `"horizontal"` (horizontal comes from `hscroll`). | | `drag` | `{ x1, y1, x2, y2, button?, hold_keys? }` | Press, move, and release between two points, optionally holding up to 8 keys. | | `move` | `{ x, y }` | Move the cursor without clicking. | | `wait` | `{ seconds }` | Pause `seconds` before the next step (e.g. for a page load). | | `done` | `{}` | Terminal completion claim with no OS effect. Read `status`, then verify fresh post-action pixels/application state before accepting completion. | | `fail` | `{ reason? }` | The task is impossible. `status` becomes `"fail"`. | #### Exact keyboard and clipboard semantics - **Literal entry:** `type_text {"text":"abc"}` injects the supplied text at the current focus. It never reads the system clipboard. - **Sequential keys:** `key_press {"keys":["tab","enter"]}` means press and release Tab, then press and release Enter. It is not a chord. - **One chord:** `key_combo {"keys":["ctrl","v"]}` means hold Ctrl while pressing V. This is the canonical Ctrl+V paste action. On macOS use `["cmd","v"]` (or the executor's documented Command alias). - **Canonical names and policy aliases:** emit lowercase `ctrl`, `alt`, `shift`, `cmd`, `escape`, and `enter`. Server action policy normalizes `esc`, `return`, `control/ctl`, `command/super/win/windows`, and `option`. `meta` is not a current server alias: emit `cmd` on the wire and normalize meta to cmd in your client-side guard for executor portability. - **Clipboard ownership:** the caller must put the note on the clipboard before executing Ctrl+V. There is no `clipboard_paste` action, and two `key_press` actions for Ctrl then V are not equivalent. - **Focus:** text and keyboard actions are focus-sensitive. They go to whichever application/control owns OS focus at execution time. The screenshot can show likely focus; the Predict/Sessions API receives no separate focus or clipboard metadata and cannot prove either one. - **Machine action mapping:** Predict/Sessions return `action_type:"type_text"`; `POST /v1/machines/{id}/actions` expects `command:"type"` with `{"text":"..."}`. `key_press` and `key_combo` keep their names. `done` and `fail` are client terminal signals, not machine commands. ### Error envelope Every error produced by the Coasty application uses the same JSON shape with the HTTP status set accordingly. Its body is wrapped in an `error` object. An edge/network failure that happens before the application can instead be non-JSON; handle that separately as described below. ```json { "error": { "code": "INSUFFICIENT_CREDITS", "message": "Operation needs 20 credits; you have 5.", "type": "billing_error", "request_id": "req_8f2c1e9a", "suggestion": "Top up at https://coasty.ai/credits, or switch to a sandbox key 'sk-coasty-test-...' for free testing.", "docs_url": "https://coasty.ai/docs#errors", "required": 20, "balance": 5, "retryable": false, "retry_with_same_idempotency_key": false } } ``` Field reference (every error carries `code`, `message`, `type`, `request_id`, `suggestion`, `retryable`, and `retry_with_same_idempotency_key`; the rest are conditional): - `code`: machine-readable, stable across versions. Branch your logic on this, never on `message`. - `message`: human-readable, may change between versions. Do not parse it. - `type`: coarse telemetry category (`auth_error`, `billing_error`, `validation_error`, `not_found_error`, `state_error`, `rate_limit_error`, `server_error`). - `request_id`: identifies the operation/result represented by the body. `X-Request-Id` identifies the current HTTP attempt. `X-Coasty-Request-Id` normally matches it, but on an exact replay that header and/or the stored body can retain the original logical operation id. Log every distinct value. - `suggestion`: a concrete next step (auto-filled per code). LLM agents can act on this to self-recover. - `retryable` (boolean): `true` when retrying the *same* call may succeed — transient server failures and back-pressure. `false` for deterministic client errors (bad input, missing scope, not found) that will fail again unchanged. See the `retryable` column in the catalog below. - `retry_with_same_idempotency_key` (boolean): reuse the same key and identical body **only** when this field is `true` on the concrete response and the original operation is one of the exact 18 generic reserve-and-replay operations in the Idempotency section. A retryable error does not by itself make an operation idempotent, and support cannot be added retroactively after the first attempt. A CUA `BILLING_UNAVAILABLE` caused by an unconfirmed refund overrides the general catalog policy to `false` unless a shared refund checkpoint was confirmed. A confirmed refunded CUA failure may remain `retryable: true` while setting this field to `false`: retry with a **new** key. Always follow the fields on the concrete response. - `docs_url`: deep link to the matching docs anchor (also sent as `Link: ; rel="help"`). - `support`: `founders@coasty.ai`, attached only on 5xx and a few ambiguous 4xx. - Context extras: code-specific fields such as `required_scope`, `current_scopes`, `required`, `balance`, `retry_after`, `valid_options`, `examples`, `details`, `current_state`, `allowed_from`. Use these to auto-correct. (`retry_after` accompanies `retryable: true` back-pressure codes; `examples` carries machine-readable limits on `PAYLOAD_TOO_LARGE` / `INVALID_SCREENSHOT`, see below.) Every Coasty application error uses this catalogued envelope, including application gateway / `5xx` / timeout paths. A CDN or network intermediary such as Cloudflare can fail **before** the request reaches Coasty and return non-JSON/HTML instead. Handle that edge case with the state-aware fallback below. For canonical JSON, branch on `code` and the retry booleans, never on `message` or HTTP status alone. ### Operational error catalog The table below covers every retry-sensitive family plus the deterministic codes SDKs most commonly branch on. The backend's canonical registry contains every emitted code; automated AST tests require every literal route/service code to have a type, suggestion, and documentation anchor before it can ship. The `Retryable` column mirrors the envelope's `retryable` field: **yes** means retrying the same call may succeed (transient server failures and back-pressure); **no** means the call is deterministic and will fail again unchanged. The `Retryable` column does not imply same-key replay. Reuse the original key only when the concrete response sets `retry_with_same_idempotency_key: true` and the original operation belongs to the exact 18-operation generic set above or the separate external-enrollment replay domain. | Status | Code | Retryable | Cause | Fix | | --- | --- | --- | --- | --- | | 401 | `INVALID_API_KEY` | no | Key missing, malformed, revoked, or `Bearer ` pasted into `X-API-Key`. Also sends `WWW-Authenticate`. | Send a raw `sk-coasty-live-`/`sk-coasty-test-` key in `X-API-Key`, or `Authorization: Bearer `. | | 403 | `INSUFFICIENT_SCOPE` | no | Key is valid but lacks the scope this route needs. Body has `required_scope` + `current_scopes`. | Re-mint the key with the missing scope, or call an endpoint your scopes allow. | | 402 | `INSUFFICIENT_CREDITS` | no | Prepaid USD wallet can't cover this request. Body has `required` + `balance`. | Top up at https://coasty.ai/credits, or use a `sk-coasty-test-` key (free). | | 402 | `WALLET_EXHAUSTED` | no | Wallet ran dry mid-run; the run stopped at the step in `message`. Completed steps were already billed. | Top up, then start a new run. | | 422 | `VALIDATION_ERROR` | no | A request field failed validation. `error.details` (loc) names the field path + expected type. | Fix the named field and retry. | | 422 | `INVALID_SCREENSHOT` | no | `screenshot` is not decodable as raw base64 or an exact `data:image/png;base64,` / `data:image/jpeg;base64,` URI, contains whitespace, or is not a static PNG/JPEG. `error.examples` carries the machine-readable limits. | Send raw base64 or one of the two exact supported data-URI prefixes, with no whitespace. | | 413 | `PAYLOAD_TOO_LARGE` | no | An individual screenshot exceeds 10,485,760 base64 characters, or the complete ordinary JSON request exceeds 15 MiB. `error.examples` carries image limits. | Downscale/JPEG-compress frames; for long histories use a stateful session instead of attaching many full frames. | | 400 | `INVALID_LIMIT` | no | A `limit` query param is outside `1..200`. Body has `actual`, `min`, `max`. | Pass `1 <= limit <= 200` (default 50), or omit the param. | | 400 | `INVALID_STATUS_FILTER` | no | A `status` filter value is not a recognized state. Body lists `valid_options`. | Use a value from `valid_options` or omit `?status=`. | | 400 | `INVALID_EVENT_CURSOR` | no | A cursor param is negative: `after_step` on `GET /v1/runs/{id}/log`, or an equivalent event cursor. Body carries `actual`. | Pass `>= 0`, or omit it to start from the beginning. | | 404 | `NOT_FOUND` / `MACHINE_NOT_FOUND` / `RUN_NOT_FOUND` / `WORKFLOW_NOT_FOUND` / `SESSION_NOT_FOUND` | no | Id does not exist in this key's namespace. Ids are mode-isolated: a test key cannot see live resources and vice-versa. | Verify the id with the matching `GET` listing endpoint, using a key of the same kind. | | 409 | `NOT_AWAITING_HUMAN` | no | You tried to resume a run that is not in `awaiting_human`. | Re-GET the run; resume only while `status == "awaiting_human"`. | | 409 | `RESUME_CONFLICT` | no | Another resume/cancel/timeout won the race. | Re-GET the run to read its current status, then retry. | | 422 | `IDEMPOTENCY_KEY_REUSED` | no | Same `Idempotency-Key` sent with a different operation, canonical body, or effective BYOK provider/model/key identity. | Resend every original bound input to get the cached result, or use a new key. | | 409 | `IDEMPOTENCY_ALREADY_REFUNDED` | no | This key's stable wallet debit has both a usage transaction and a compensating refund, so it cannot authorize new work. This database guard remains effective even if the idempotency cache is unavailable. | Use a new `Idempotency-Key` for a new execution. Reusing the refunded key always fails before model/provider work. | | 409 | `IDEMPOTENCY_IN_FLIGHT` | yes (`retry_with_same_idempotency_key: true`) | The original request with this key is still executing after the wait-and-return window. Carries `Retry-After`. | Retry with the **same** `Idempotency-Key` after `Retry-After`. | | 409 | `INVALID_STATE` | no | A lifecycle action is illegal in the resource's current state. Body has `current_state` + `allowed_from`. | Check the state first (actions need `running`; provisioning is async), then retry. | | 409 | `FRAME_PRECONDITION_REQUIRED` | no | A mutating external-machine action omitted the latest accepted `frame_id`. | Capture a screenshot, plan exactly one action against it, and submit that id as `precondition_frame_id`. | | 409 | `FRAME_PRECONDITION_MISMATCH` | no | The supplied frame is no longer authoritative, or a terminal device result did not exactly echo its command envelope (including null). | Capture a fresh screenshot and re-plan. Never replay the stale input blindly. | | 400 | `FEATURE_NOT_AVAILABLE` | no | The requested option is not shipped on this API surface. Note that `system_prompt` / `instructions` are **not** tier-gated: they are available on every tier including free, so this code never means "upgrade to use custom prompts". | Remove the option or use a supported surface. | | 503 | `SETTLEMENT_INCOMPLETE` | only with the original key | A provider/session operation crossed an irreversible boundary but exact final persistence is incomplete. A durable completion can still be replayed; a `started`-only crash is outcome-unknown and cannot reconstruct the response or token counts. | If the request had an `Idempotency-Key`, retry the identical body with that same key; Coasty never repeats the provider call for that operation identity. Without one, another HTTP request is a new operation that may call and bill the provider again: do not auto-retry, and reconcile provider usage plus observed machine state first. | | 422 | `LLM_KEY_NOT_CONFIGURED` | no | BYOK requested (`llm.provider` = `anthropic`/`openai`) but no usable key was supplied. The request never runs on Coasty's platform keys. Under test auth the stored-key path is unavailable, so direct BYOK without an explicit header returns "Stored provider keys are unavailable for test API keys. Send X-LLM-Api-Key explicitly for direct BYOK." | With live auth, store a key with `PUT /v1/llm/keys/{provider}` or send the header. With test auth, send `X-LLM-Api-Key` (+ `X-LLM-Provider`) explicitly on predict, ground, or session create. | | 422 | `LLM_KEY_INVALID` | no | The supplied BYOK key is unusable: empty, malformed, the wrong provider's format, or a stored key that could not be decrypted. This code is **only** about the credential. A key-**store** outage is `503 DB_UNAVAILABLE` with `Retry-After`, never this. | Check the key matches the provider (`sk-ant-...` for anthropic) and re-store it. Do not rotate a working key in response to a 503. | | 422 | `LLM_MODEL_INVALID` | no | A BYOK or legacy top-level Run model id is empty, exceeds 256 characters, contains unsupported characters, or looks like a credential (for example `sk-*`, bearer/authorization, API-key, or secret assignment). The rejection does not reflect the supplied value. | Start with a letter or number, then use only letters, numbers, dot, underscore, colon, slash, plus, at-sign, or hyphen. Put credentials only in `X-LLM-Api-Key`. Provider rejection of a syntactically valid but unavailable model is a separate upstream failure. | | 404 | `LLM_KEY_NOT_FOUND` | no | `DELETE /v1/llm/keys/{provider}` found no stored key for that provider. | List stored keys with `GET /v1/llm/keys`. | | 422 | `LLM_PROVIDER_UNSUPPORTED` | no | `llm.provider` / `X-LLM-Provider` is unsupported, an `X-LLM-Api-Key` arrived without an Anthropic/OpenAI provider, a header key was combined with body provider `managed`, you tried to store a key for `managed`, or a test-auth Run, Workflow, or Schedule carried BYOK intent. The async-test message is "BYOK is unavailable for synthetic test runs, workflows, and schedules. Use managed mode or a live Coasty API key." | Use a supported provider/header pair for direct CUA BYOK. Keep synthetic test Tasks, Workflows, and Schedules managed, or use a live Coasty key for async BYOK. | | 401 | `LLM_PROVIDER_AUTH_FAILED` | no | YOUR Anthropic/OpenAI account rejected the key (their 401/403). BYOK is never retried on platform keys. | Rotate the key in your provider console, then `PUT /v1/llm/keys/{provider}`. | | 429 | `LLM_PROVIDER_RATE_LIMITED` | yes | YOUR provider account is rate-limiting (their 429). Carries `Retry-After`. | Honor `Retry-After`, raise your provider tier, or reduce volume. | | 402 | `LLM_PROVIDER_QUOTA_EXCEEDED` | no | YOUR provider account is out of credits/quota — this is your provider balance, not the Coasty wallet. | Top up your Anthropic/OpenAI billing; BYOK never falls back to platform keys. | | 502 | `LLM_PROVIDER_ERROR` | yes | YOUR provider returned a server error (their 5xx). | Retry with backoff; if it persists, check the provider's status page. | | 429 | `RATE_LIMIT_EXCEEDED` / `RATE_LIMITED` / `TOO_MANY_RUNS` / `TOO_MANY_WORKFLOW_RUNS` | yes | Back-pressure: per-key/per-user request rate or a concurrency cap. Carries `Retry-After`. | Honor `Retry-After`, then retry with backoff. | | 500 | `INTERNAL_ERROR` | yes | An unexpected server-side failure. | Retry; if it persists, file a ticket with the `request_id`. | | 503 | `SNAPSHOT_OUTCOME_UNKNOWN` | no | Snapshot dispatch may have created the machine image, but the API could not confirm the final result. The original charge is retained and the keyed result is terminal. | Do not retry automatically or use a new key blindly. Contact support with the `request_id` so the existing machine image and tracking row can be reconciled. | | 503 | `DB_UNAVAILABLE` / `DB_ERROR` / `SERVICE_UNAVAILABLE` / `BILLING_UNAVAILABLE` / `SESSION_STORE_UNAVAILABLE` / `RATE_LIMIT_UNAVAILABLE` / `ENCRYPTION_UNAVAILABLE` / `RUNS_API_DISABLED` / `WORKFLOWS_API_DISABLED` | yes, except uncheckpointed refund uncertainty | A backing service (database, billing, shared sessions, shared rate limits, encryption, or a feature subsystem) is briefly unavailable. For `BILLING_UNAVAILABLE`, inspect the credit headers and do not assume an unconfirmed refund completed. `DB_UNAVAILABLE` is also what you get from `GET /v1/runs/{id}/log` on an event-store failure, from `GET`/`DELETE /v1/keys` and `GET`/`DELETE /v1/llm/keys` on a key-store outage, from the BYOK stored-key resolve path, and from `GET /v1/schedules`, `GET /v1/schedules/{id}`, and `GET /v1/schedules/{id}/runs/{run_id}`, each of which previously returned a bare 500. | Follow the concrete response's retry fields. Reuse the original key/body only when `retry_with_same_idempotency_key: true`; an unkeyed or uncheckpointed CUA/snapshot refund returns `false` and must go to support instead. | | 500 | `PREDICTION_FAILED` / `GROUNDING_FAILED` | yes | The billed model call failed. A refund is submitted; only `X-Credits-Refunded` confirms completion. | If refunded, use a **new** idempotency key for a new attempt; the old key only replays the refunded failure. If not refunded, follow the returned `BILLING_UNAVAILABLE` retry fields. For grounding, send a clearer or higher-resolution screenshot. | | 502 | `SCREENSHOT_FAILED` | yes | A free managed/external machine screenshot capture failed; no Developer API wallet debit or refund applies. | Confirm the managed VM is `running` or the external driver is connected, honor retry metadata, then capture again. | | 500 | `CREATE_FAILED` / `RUN_CREATE_FAILED` / `WORKFLOW_RUN_CREATE_FAILED` / `WORKFLOW_CREATE_FAILED` / `WORKFLOW_UPDATE_FAILED` / `WORKFLOW_DELETE_FAILED` / `UPDATE_FAILED` / `SESSION_CREATE_FAILED` / `RUN_FAILED` / `DISPATCH_FAILED` | yes | A transient server-side failure while creating / updating / dispatching a resource. | If the original operation is in the 18-operation generic set or separate enrollment replay domain, was sent with a key, and the response says `retry_with_same_idempotency_key: true`, retry the identical request with that key. Otherwise inspect resource state before retrying; idempotency cannot be added retroactively. | | 504 | `UPSTREAM_TIMEOUT` | yes | An upstream operation timed out. | Follow the response retry fields. Same-key retry is duplicate-safe only for an original request in the documented generic or external-enrollment replay domain; other mutations provide no duplicate-suppression guarantee. | | 503 | `UPSTREAM_UNAVAILABLE` / `UPSTREAM_ERROR` / `UPSTREAM_AUTH_FAILED` | yes | An upstream service is briefly unavailable or rejected the call. | Retry with backoff; check https://status.coasty.ai. | Normal non-streaming JSON responses for backend-built `retryable: true` errors carry a `Retry-After` header and a `retry_after` body field. In opt-in Predict or Session SSE mode the stream headers are already committed; read `retry_after` from the terminal `event: error` envelope instead of expecting a late HTTP header. An edge-normalized or intermediary response may lack either form, so clients also need the bounded jitter fallback below. Common retryable examples include transient-server (`INTERNAL_ERROR`, `DB_UNAVAILABLE`, `DB_ERROR`, `SERVICE_UNAVAILABLE`, `BILLING_UNAVAILABLE`, `SESSION_STORE_UNAVAILABLE`, `RATE_LIMIT_UNAVAILABLE`, `ENCRYPTION_UNAVAILABLE`, `UPSTREAM_TIMEOUT`, `UPSTREAM_UNAVAILABLE`, `UPSTREAM_ERROR`, `UPSTREAM_AUTH_FAILED`, `PREDICTION_FAILED`, `GROUNDING_FAILED`, `SCREENSHOT_FAILED`, `CREATE_FAILED`, `RUN_CREATE_FAILED`, `WORKFLOW_RUN_CREATE_FAILED`, `WORKFLOW_CREATE_FAILED`, `WORKFLOW_UPDATE_FAILED`, `WORKFLOW_DELETE_FAILED`, `UPDATE_FAILED`, `SESSION_CREATE_FAILED`, `RUN_FAILED`, `DISPATCH_FAILED`, `RUNS_API_DISABLED`, `WORKFLOWS_API_DISABLED`, `LLM_PROVIDER_ERROR`) and back-pressure (`RATE_LIMIT_EXCEEDED`, `RATE_LIMITED`, `TOO_MANY_RUNS`, `TOO_MANY_WORKFLOW_RUNS`, `IDEMPOTENCY_IN_FLIGHT`, `LLM_PROVIDER_RATE_LIMITED`). Per-response safety overrides can make a catalogued code non-retryable: specifically, CUA or machine-snapshot refund uncertainty sets `BILLING_UNAVAILABLE` to `retryable: false` when no shared checkpoint was confirmed. Treat the response's `error.retryable` field as authoritative; additional catalog codes can also be retryable. ### Official 503/504 handling ```text 503 / 504 / transport loss -> canonical JSON? yes -> error.retryable? no -> stop; follow code/suggestion yes -> GET/HEAD, or original mutation explicitly allows same-key replay? yes -> wait, then bounded retry no -> check execution state before retrying no -> retry reads; keyed replay-capable mutation may exact-replay; otherwise inspect authoritative state before any resend ``` #### 1. Read the response, do not retry by status alone For a canonical error read: - `error.code` - `error.retryable` - `error.retry_with_same_idempotency_key` - `error.retry_after` and the `Retry-After` header - `error.suggestion` A 503 such as `SNAPSHOT_OUTCOME_UNKNOWN` is terminal. A retryable 504 does not make an unsupported mutation duplicate-safe. Per-response fields override the catalog defaults. #### 2. Honor Retry-After, or use bounded full jitter Parse `Retry-After` as either integer delta-seconds or an IMF-fixdate HTTP-date. Use the largest valid server-provided delay. If none exists, use full jitter: ```text delay = random(0, min(30 seconds, 1 second * 2^retry_index)) ``` The recommended automatic client budget is **four total attempts** (initial send plus three retries) and a **two-minute elapsed budget after the first failure**, whichever ends first. This is the recommended client safety budget, not a server protocol guarantee or an automatic behavior you should assume an SDK provides. Always honor a larger `Retry-After`. If that delay cannot fit the foreground budget, stop and requeue instead of retrying early. #### 3. Retry reads; replay only explicitly safe mutations | Original request | Safe client behavior | | --- | --- | | `GET` / `HEAD` | Retry within the bounded budget. | | Mutation whose concrete error says `retry_with_same_idempotency_key:true` | Resend the identical method, path, canonical body, effective BYOK provider/model/key identity, and the **same Idempotency-Key**. | | Mutation with same-key permission false/absent | Do not auto-resend. Check execution state before retrying, then follow `code` and `suggestion`. | | `IDEMPOTENCY_IN_FLIGHT` | Stop repeatedly submitting the mutation. Use the delay from the original response for the first `GET /v1/idempotency/{key}` poll. A `processing` lookup does not currently add its own `Retry-After`, so continue with bounded backoff; cap ordinary foreground reconciliation at ten minutes, then surface pending/manual reconciliation. | | Non-JSON/HTML Cloudflare or network response | Retry reads. Exact-replay a mutation only if the original request already used a valid key on a documented replay-capable endpoint; otherwise inspect state first. | Never add an idempotency key retroactively, switch to a new key during recovery, or alter the request body. A changed screenshot, instruction, model, provider, or provider-key identity is a new operation. A keyed prediction replay can return the same action list; it deduplicates model work and billing, **not** caller-executed keyboard/mouse input. Journal each action index and never execute the same cached input twice. #### 4. Reconcile execution state before unsafe resends - Generic keyed operation result: `GET /v1/idempotency/{key}` (same concrete Coasty credential and live/test mode). `completed` returns the stored response, `processing` means wait, and 404 can mean never reserved, released after failure, or expired. - Task: `GET /v1/runs/{id}` - Workflow run: `GET /v1/workflows/runs/{id}` - Machine: `GET /v1/machines/{id}`, then capture a fresh screenshot before further UI input - Session: `GET /v1/sessions/{id}` Run resume/cancel, workflow update/delete/cancel/resume, machine start/stop/restart/update/delete, and session reset/delete are state-sensitive, not generic reserve-and-replay mutations. Re-read the resource before deciding whether another request is needed. #### 5. Log correlation without confusing the two identifiers `request_id` and `Idempotency-Key` are different: - The **client** chooses one Idempotency-Key for the logical operation and reuses it only for an identical replay. - The **server** puts the current attempt id in `X-Request-Id`. - `X-Coasty-Request-Id` normally matches it. An exact replay can preserve the original operation id in that header and/or the replayed body `request_id`; log every distinct value. - If an edge response contains no Coasty request id, log UTC time, method, path, and `CF-Ray` when present. Never copy a request id into the `Idempotency-Key` header. **Machine-readable screenshot limits.** `PAYLOAD_TOO_LARGE` (413) and `INVALID_SCREENSHOT` (422) attach an `error.examples` object so a client can self-correct without hard-coding the numbers: ```json { "max_base64_bytes": 10485760, "max_mb": 10, "min_base64_chars": 100, "formats": ["png", "jpeg"] } ``` So a screenshot's base64 must be **100 chars to 10,485,760 characters** and a `png` or `jpeg` — and those exact limits are readable straight off the error. For `POST /v1/predict`, the current screenshot, every trajectory screenshot, and all other JSON together must also fit the ordinary **15 MiB (15,728,640-byte) request-body cap**. The per-image limit does not multiply the aggregate cap. ### Per-tier features API tiers are derived from your subscription. Every `cua_version` (`v1` / `v3` / `v4` / `v5`, default `v5`) is available on all tiers. The developer API is **prepaid**: you have already bought credits, and the credit wallet is the only thing that decides how much you may do. Every tier therefore resolves to the same policy, pinned to the wire schema's own maximum, so a tier check can never reject a request the request model already accepted. | Tier | `max_system_prompt_chars` | `max_instruction_chars` | | --- | --- | --- | | free | 32,000 | 32,000 | | starter | 32,000 | 32,000 | | professional | 32,000 | 32,000 | | enterprise | 32,000 | 32,000 | Custom prompts (`system_prompt` and `instructions`) are available on **every tier, including free**. There is no tier at which they are unavailable, and the old per-tier ladder (2000 / 4000 / 16000) no longer exists. ### Scopes Scopes are deny-by-default; each route asserts the scope it requires. Naming is `:` (`read` / `write` / `exec`). There are **23 scopes** in the vocabulary. **20 of them are granted by default** on a newly minted key, so you can reach every ordinary product surface without having to discover a scope list first. The remaining **3 are opt-in**, because each is a genuine privilege escalation rather than a product tier. | Scope | Default? | Grants | | --- | --- | --- | | `predict` | granted | `POST /v1/predict`. | | `session` | granted | All `/v1/sessions` endpoints. | | `ground` | granted | `POST /v1/ground`. | | `parse` | granted | `POST /v1/parse`. | | `usage` | granted | Read the usage summary. | | `runs:read` | granted | List, get, stream events of, and read the log and screenshots of your runs. | | `runs:write` | granted | Start, cancel, and resume (human takeover) runs. | | `workflows:read` | granted | List/get workflows and workflow runs. | | `workflows:write` | granted | Create/update/delete workflows and start workflow runs. | | `machines:read` | granted | List, get, status, screenshot of machines. | | `machines:write` | granted | Provision, start, stop, terminate machines. | | `actions:exec` | granted | `POST /actions`, `/actions/batch`, browser ops. | | `terminal:exec` | granted | `POST /terminal` (arbitrary shell on your own machine). | | `files:read` | granted | File read/list/exists. | | `files:write` | granted | File write/edit/append/delete. | | `snapshots:write` | granted | Create + delete snapshots. | | `schedules:read` | granted | List/get schedules, run history, and triggers. | | `schedules:write` | granted | Create/update/delete/pause/resume/run-now schedules. | | `triggers:write` | granted | Add/remove webhook + chain triggers. | | `llm_keys` | granted | With a live key, store, list, and delete your own BYOK LLM keys (`/v1/llm/keys`). Sandbox keys cannot access the production credential store. | | `keys` | **opt-in** | **Mint** new Coasty API keys (`POST /v1/keys`) as well as list (`GET /v1/keys`) and revoke (`DELETE /v1/keys/{key_id}`) them. A key holding this scope can mint further keys, so treat it as account-level authority. | | `browser:execute` | **opt-in** | `browser_execute` (arbitrary JavaScript in the VM's browser session). | | `connection:read` | **opt-in** | Returns plaintext connection secrets: SSH key + VNC password. | **Default scopes on a new key (all 20):** `predict`, `session`, `ground`, `parse`, `usage`, `machines:read`, `machines:write`, `actions:exec`, `terminal:exec`, `files:read`, `files:write`, `snapshots:write`, `schedules:read`, `schedules:write`, `triggers:write`, `runs:read`, `runs:write`, `workflows:read`, `workflows:write`, `llm_keys`. `terminal:exec`, `files:write`, `snapshots:write` and `machines:write` are **not** opt-in. They ship on every default key: they act only on machines you already own and pay for, and withholding them would only make the first hour of integration harder without making anything safer. **Opt-in scopes (exactly 3):** `keys`, `browser:execute`, `connection:read`. Request them explicitly at key creation. ### Pricing (USD) 1 credit = 1 cent = $0.01, exactly. Direct metered API calls debit your prepaid developer wallet; scheduled runtime is the explicit exception and uses subscription credits. Metered calls reserve funds before execution. Conclusive recoverable failures submit a refund; documented outcome-unknown post-dispatch operations retain the debit for reconciliation instead of blindly refunding or repeating a possible side effect. Treat a refund as complete only when `X-Credits-Refunded` confirms it. Test keys (`sk-coasty-test-*`) never debit Coasty. An explicit provider key can still execute and bill on predict, ground, and session predict; session create only configures that inherited provider key. Test-key Tasks, Workflows, and schedules stay deterministic sandbox executions and do not call the provider. Keep provider secrets out of sandbox and CI requests. **Per-request (inference)** | Endpoint | Cost | Note | | --- | --- | --- | | `POST /v1/predict` | $0.05 base (5 cr) | Stateless prediction. Published surcharges below apply. | | `POST /v1/sessions` | $0.10 (10 cr) | One-time at creation; no surcharges. | | `POST /v1/sessions/{id}/predict` | $0.04 (4 cr) | Each step inside a session. Surcharges below apply. | | `POST /v1/ground` | $0.03 (3 cr) | Coordinate grounding; +$0.01 if the image is HD. | | `POST /v1/parse` | Free | Deterministic, no model call. | | Session reset / get / list / delete | Free | Sessions have no per-minute cost. | | `GET /v1/models`, `GET /v1/usage`, `/v1/keys` | Free | | **Surcharges** (exact amounts): - Predict and Session Predict: +$0.02 (2 cr) per provider-visible trajectory screenshot beyond the current one. - Predict and Session Predict: +$0.01 (1 cr) per HD current or provider-visible trajectory image. Ground: the same fee can apply to its current image only. Width > 1280 **or** height > 720 is HD; exactly 1280x720 is not. - Predict and Session Predict: +$0.03 (3 cr) on `v1`; `v3`, `v4`, and `v5` add $0. - Predict and Session Predict: +$0.01 (1 cr) when `len(system_prompt) + len(instructions.strip())` exceeds 500. Exactly 500 is free, and the task `instruction` is not counted. Session create has no surcharges. **Runs & workflows (per agent step)** | Item | Cost | Note | | --- | --- | --- | | Managed Run step on `v3` / `v4` / `v5` | $0.05/step (5 cr) | Billed after each completed step; no trajectory/HD/prompt surcharges on run steps. | | Managed Run step on `v1` | $0.08/step (8 cr) | 5 cr base + 3 cr v1 engine surcharge. | | BYOK Run or Workflow `task` step | Free on Coasty (0 cr) | Live-key execution records provider tokens billed by Anthropic/OpenAI. Test-auth BYOK intent is rejected with `422 LLM_PROVIDER_UNSUPPORTED` before execution; managed-mode test work remains deterministic sandbox. No wallet gate or workflow budget reservation for live BYOK. | | Managed Workflow `task` step | Same as a managed run step | $0.05 on v3/v4/v5, $0.08 on v1; total capped by `budget_cents`. | | Workflow control-flow steps (`if`, `assert`, `loop`, `parallel`, `retry`, `human_approval`, `succeed`, `fail`) | Free | Only `task` steps bill. | Starting a managed run requires your wallet to cover at least one step ($0.05, or $0.08 on `v1`) — otherwise `402 INSUFFICIENT_CREDITS`. If the wallet runs dry mid-run, the run fails with `WALLET_EXHAUSTED`; completed steps stay billed. BYOK runs bypass this gate and debit zero. **Managed machines (runtime — metered per minute, hourly rates)** | State | Cost | Note | | --- | --- | --- | | Running — Linux | $0.05/hr (5 cr/hr) | Also billed while starting / stopping / restarting. | | Running — Windows | $0.09/hr (9 cr/hr) | | | Stopped / suspended | $0.01/hr (1 cr/hr) | Storage-only rate, any OS. | | Creating / error / terminated | Free | Provisioning time is never billed. | | `POST /v1/machines/{id}/snapshot` | $0.01 (1 cr) default | One-time and operator-configurable; conclusive rejection submits a refund (confirmed by `X-Credits-Refunded`), ambiguous post-dispatch outcome is not refunded. | | Actions, batches, terminal, browser ops, files, screenshots, start/stop/restart, connection, list/get/delete | Free per call | Covered by the runtime rate. | | External-machine enrollment, runtime, direct actions, and frame transport | Free (0 cr) | Caller-owned compute is not metered. Managed Task/Workflow inference keeps normal prices; BYOK inference is 0 Coasty credits. | Runtime is billed in whole credits, rounded down in your favor (partial credits are never billed). Provisioning requires a wallet balance of at least $0.20 (20 credits) — a gate, not a fee. An empty wallet **stops** the machine (never destroys it) and flags it `suspended_for_billing`; top up and start it again. The live price table is also served at `GET /v1/machines/pricing`. **Schedules & triggers** | Item | Cost | Note | | --- | --- | --- | | Managed create schedule / run-now / webhook fire | Free — gate only | Published default gate: $0.20 (20 cr) in the API wallet; there is no per-fire fee. | | Managed scheduled execution | Published default: 10 Coasty credits per minute | Uses subscription credits, not the API wallet; default 20-credit start minimum and 6-hour timeout. | | BYOK schedule dispatch and execution | Free on Coasty (0 cr) | No API-wallet gate, billing session, or subscription-credit debit for live BYOK. Live-key execution is provider-billed. Test-auth BYOK intent is rejected with `422 LLM_PROVIDER_UNSUPPORTED`; managed-mode test schedules remain deterministic sandbox. | | Test schedules (`sch_test_*`) | Free | Synthetic runs; `credits_charged: 0`. | The wallet is a prepaid USD balance; top up in the developer dashboard. ### MCP server Connect Coasty to an MCP-capable client (for example, Claude or an IDE agent) with the official server: ```bash npx -y @coasty/mcp ``` Set `COASTY_API_KEY` in the environment; the MCP server exposes the same endpoints documented above as tools. --- ## 7. Machines API A machine is either a managed cloud VM or an external driver you operate. Both kinds use the same `machine_id` in runs, workflows, and schedules. Managed VMs can be provisioned, driven with low-level actions, snapshotted, and terminated; external drivers provide observations and execute fenced commands through the device-token pull protocol documented in [Bring your own machine](#external-machines-bring-your-own-screen-and-action-executor). A machine id is either a UUID (live machines) or `mch_test_<8-32 hex>` (sandbox machines from a test key). Ids are mode-isolated: a test key never sees live machines and a live key never sees test machines. **Sandbox shortcut.** A test key (`sk-coasty-test-`) returns a mock VM **instantly** with no cloud provisioning, no wallet billing, and an `mch_test_*` id. Use it to build and test the full action surface for free. Live provisioning needs the `machines:write` scope and a minimum wallet balance of $0.20 (20 credits) — a pre-flight gate, not a fee. **Managed runtime billing.** A live managed VM bills your API wallet by state, metered per minute and always rounded down in your favor: | State | Rate | | --- | --- | | Running — Linux (incl. starting/stopping/restarting) | $0.05/hr (5 credits/hr) | | Running — Windows | $0.09/hr (9 credits/hr) | | Stopped / suspended (any OS — storage only) | $0.01/hr (1 credit/hr) | | Creating / error / terminated | Free | Every per-call operation on a machine — actions, batches, terminal, browser ops, files, screenshots, start/stop/restart, connection details — is **free**; you pay only the hourly runtime rate (plus $0.01 one-time for a snapshot). If your wallet runs dry the machine is **stopped, never destroyed**, and flagged `suspended_for_billing`; top up and start it again. To bound spend, set `ttl_minutes` at provision time (5 minutes to 7 days): the initial `auto_destroy_at` is `created_at + ttl_minutes`. A later `PATCH /v1/machines/{id}` replaces the deadline with `now + ttl_minutes`; send `0` to clear it. Auto-termination ends runtime billing. The same numbers are served machine-readably at `GET /v1/machines/pricing`. That response also includes `external_machines`: enrollment, runtime per hour, direct actions, and frame transport are all `0` credits. Managed Task and Workflow steps use the selected CUA version's normal rate; BYOK steps are 0 Coasty credits. **Per-machine `billing` object.** Each API-provisioned machine in a `GET /v1/machines` response carries a `billing` object describing how it is metered: | Field | Type | Notes | | --- | --- | --- | | `rate_cents_per_hour` | int | The hourly rate applied in the machine's current state (running vs stopped). | | `running_credits_per_hour` | int | Rate while running (5 Linux / 9 Windows). | | `stopped_credits_per_hour` | int | Rate while stopped/suspended (storage only, 1). | | `accrued_cents` | int | Credits owed for the **current metering segment so far** (since the last state change). | | `projected_daily_cents` | int | `rate_cents_per_hour * 24` — a full day at the current rate. | | `since` | string\|null | ISO-8601 timestamp when the current metering segment started. | | `total_credits_billed` | int | Lifetime credits this machine has billed. | | `suspended_for_billing` | bool | `true` if it was stopped because the wallet ran dry. | For a fleet-wide "what is billing me right now" view across every machine at once, use the `/v1/billing/active` endpoint (documented below). ### Machine endpoints + scopes | Method + path | Scope | Description | | --- | --- | --- | | `POST /v1/machines` | `machines:write` | Provision a VM. Honors `Idempotency-Key`. | | `POST /v1/machines/external` | `machines:write` | Enroll your machine. `Idempotency-Key` is required; the 201 no-store response contains its device token. | | `GET /v1/machines` | `machines:read` | List your machines (`limit`, 1-200, default 50). | | `GET /v1/machines/pricing` | `machines:read` | The runtime + one-time price table (machine-readable). | | `GET` `/v1/billing/active` | `machines:read` | What is metering your wallet **right now** across the whole fleet. | | `GET /v1/machines/{id}` | `machines:read` | Get one machine. | | `DELETE /v1/machines/{id}` | `machines:write` | Terminate a managed VM or delete/revoke an external registration and its command leases; caller-owned host/storage are untouched. | | `POST /v1/machines/{id}/start` | `machines:write` | Managed power-on; external logical dispatch start (new fence, pending commands cancelled). | | `POST /v1/machines/{id}/stop` | `machines:write` | Managed power-off; external logical dispatch stop (new fence, pending commands cancelled). | | `POST /v1/machines/{id}/restart` | `machines:write` | Managed reboot; external logical dispatch restart (new fence, pending commands cancelled). | | `PATCH /v1/machines/{id}` | `machines:write` | Update resource expiry (`ttl_minutes`: 5-10080 from now, 0 clears): managed destroy or external registration/access revoke. | | `POST /v1/machines/{id}/snapshot` | `snapshots:write` | Managed only; external returns `400 UNSUPPORTED_MACHINE_KIND`. Honors `Idempotency-Key`. | | `GET /v1/machines/{id}/screenshot` | `machines:read` | Capture the screen as base64. | | `GET /v1/machines/{id}/connection` | `connection:read` | Managed SSH/VNC credentials; external returns `409 INVALID_STATE`. | | `POST /v1/machines/{id}/actions` | varies by command | Run one action (click, type, scroll, terminal, file, browser). | | `POST /v1/machines/{id}/actions/batch` | varies by command | Run up to 50 actions in order. | | `POST /v1/machines/{id}/browser/{op}` | `actions:exec` (`browser:execute` for raw JS) | Browser convenience wrapper. | | `POST /v1/machines/{id}/terminal` | `terminal:exec` | Run a shell command (PowerShell on Windows, bash on Unix). | | `POST /v1/machines/{id}/files/{op}` | `files:read` or `files:write` | File operations. | | `GET /v1/machines/{id}/commands` | device bearer token | Long-poll commands after an exclusive cursor. | | `POST /v1/machines/{id}/observations` | device bearer token | Submit a monotonic PNG/JPEG screenshot observation. | | `POST /v1/machines/{id}/commands/{command_id}/results` | device bearer token | Submit an idempotent fenced command result and optional post-action frame. | | `POST /v1/machines/{id}/heartbeat` | device bearer token | Renew liveness with protocol version and fencing token. | Per-command scopes on `/actions`: `terminal_*` needs `terminal:exec`; `file_read`/`file_exists`/`directory_list`/`file_download`/`file_list_downloads` need `files:read`; `file_write`/`file_edit`/`file_append`/`file_delete`/`directory_delete` need `files:write`; `browser_execute` (arbitrary JS) needs `browser:execute`; everything else needs `actions:exec`. ### POST /v1/machines (provision) **Request body** | Field | Type | Req | Default | Notes | | --- | --- | --- | --- | --- | | `display_name` | string | yes | - | 1-64 chars. Shown in dashboards. | | `os_type` | string | no | `linux` | `linux` or `windows`. | | `desktop_enabled` | bool | no | false | Install XFCE + VNC for a GUI desktop. | | `cpu_cores` | int\|null | no | null | 1-16, capped to your tier. | | `memory_gb` | int\|null | no | null | 1-64, capped to your tier. | | `storage_gb` | int\|null | no | null | 8-500. | | `restore_from_snapshot` | bool\|null | no | false | Restore your latest snapshot (Linux only). | | `ttl_minutes` | int\|null | no | null | 5-10080 (5 min - 7 days). At creation, auto-terminate at `created_at + ttl_minutes`; a later PATCH starts a new countdown from that request, and 0 clears it. | | `metadata` | object\|null | no | null | Free-form string tags (max 16 entries). | Pass `Idempotency-Key: ` so a retried provision does not create a second VM (deduped for 24h). **No-TTL warning.** If you provision **without** a `ttl_minutes`, the machine will run (and bill the hourly runtime rate) until you explicitly destroy it. To make that machine-observable, the response carries an HTTP `Warning: 199 - "..."` header noting the machine has no auto-stop — set `ttl_minutes` at provision time, or `PATCH /v1/machines/{id}` later, to bound the spend. **curl** ```bash BASE=https://coasty.ai/v1 AUTH="X-API-Key: $COASTY_API_KEY" curl -s "$BASE/machines" -H "$AUTH" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: provision-bot-001" \ -d '{"display_name":"invoice-bot","os_type":"linux","desktop_enabled":true}' ``` **Python** ```python import os, requests BASE = "https://coasty.ai/v1" HEADERS = {"X-API-Key": os.environ["COASTY_API_KEY"]} m = requests.post( f"{BASE}/machines", headers={**HEADERS, "Idempotency-Key": "provision-bot-001"}, json={"display_name": "invoice-bot", "os_type": "linux", "desktop_enabled": True}, timeout=60, ).json() machine_id = m["machine"]["id"] print(machine_id, m["machine"]["status"]) ``` **Response** ```json { "machine": { "id": "mch_test_a1b2c3d4", "display_name": "invoice-bot", "status": "running", "os_type": "linux", "desktop_enabled": true, "cpu_cores": 2, "memory_gb": 4.0, "storage_gb": 20, "public_ip": "203.0.113.7", "is_test": true, "created_at": "2026-06-01T12:00:00Z", "metadata": {} }, "connection": { "public_ip": "203.0.113.7", "ssh_port": 22, "ssh_username": "ubuntu", "vnc_port": 5900, "websocket_port": 8080, "has_ssh_key": true, "has_vnc_password": true }, "request_id": "req_8f2c1e9a" } ``` The provision response NEVER includes the SSH key or VNC password. Fetch those from `GET /v1/machines/{id}/connection` (gated by `connection:read`); it returns `ssh_private_key_pem`, `vnc_password`, `websocket_url`, and `devtools_url`. Treat that response as a secret (it is sent with `Cache-Control: no-store`). ### Lifecycle: start / stop / delete / snapshot `POST /v1/machines/{id}/start`, `/stop`, and `DELETE /v1/machines/{id}` return `{ machine_id, status, message, request_id }`. `POST /v1/machines/{id}/snapshot` returns `{ machine_id, snapshot_id, name, created_at, credits_charged, request_id }`. A snapshot defaults to **$0.01 (1 credit)** one-time (the deployed value can be configured), charged up front. The response body reports the original charge; `X-Credits-Charged` reports the net cost of this HTTP attempt and is `0` on a replay. A conclusive rejection is refunded; only `X-Credits-Refunded` confirms that credit. If dispatch times out, returns a `5xx`, or yields an incomplete post-dispatch result, the image may already exist: the API returns terminal `503 SNAPSHOT_OUTCOME_UNKNOWN`, does not refund, and does not automatically re-execute. Contact support with the `request_id`. Start, stop, restart, and delete are free per call — they only switch which hourly runtime rate applies ($0.05-0.09/hr running, $0.01/hr stopped, $0 after termination). ### GET /v1/billing/active Answers "**what is billing me right now?**" — it lists every API-billed machine that is **currently metering** your wallet, whether `running` or `stopped` (a stopped machine still meters at the storage-only rate; only `creating`, `error`, and `terminated` machines cost nothing). Scope: `machines:read`. Auth: `X-API-Key` (or `Authorization: Bearer`). 1 credit = 1 cent. ```bash curl -s "$BASE/billing/active" -H "$AUTH" ``` ```json { "active": [ { "machine_id": "...", "display_name": "...", "status": "running", "os_type": "linux", "rate_cents_per_hour": 5, "running_credits_per_hour": 5, "stopped_credits_per_hour": 1, "accrued_cents": 12, "since": "2026-06-13T19:00:00Z", "total_credits_billed": 120, "suspended_for_billing": false, "auto_destroy_at": null, "ttl_minutes": null } ], "current_run_rate_cents_per_hour": 5, "request_id": "req_..." } ``` Each entry mirrors the per-machine `billing` object: `rate_cents_per_hour` is the rate in the machine's current state, `accrued_cents` is what this metering segment has cost so far, and `since` is when that segment started. `auto_destroy_at` / `ttl_minutes` reflect any TTL you set. `current_run_rate_cents_per_hour` is the **summed instantaneous burn rate** across the whole `active` list — your total cents/hour right now. Test-mode keys (`sk-coasty-test-`) return an **empty fleet** (`"active": []`, `"current_run_rate_cents_per_hour": 0`) because mock `mch_test_*` machines are never billed. ### GET /v1/machines/{id}/screenshot ```bash curl -s "$BASE/machines/$MACHINE_ID/screenshot" -H "$AUTH" ``` ```json { "machine_id": "mch_test_a1b2c3d4", "image_b64": "", "mime_type": "image/jpeg", "width": 1280, "height": 720, "captured_at": "2026-06-01T12:00:05Z", "frame_id": "6e5ab4c4-5e56-4524-bce3-bcd8845b5679", "request_id": "req_8f2c1e9a" } ``` The `image_b64` is pure base64 with any `data:image/...;base64,` prefix already stripped, so you can feed it straight back into `/v1/predict`. `frame_id` is an opaque UUID for the exact accepted external-machine observation (null for a managed machine). Do not synthesize or reuse it after the visible screen changes. ### POST /v1/machines/{id}/actions **Request body** | Field | Type | Req | Default | Notes | | --- | --- | --- | --- | --- | | `command` | string | yes | - | A name from the action allowlist (e.g. `click`, `type`, `scroll`, `screenshot`). | | `parameters` | object | no | {} | Command-specific params, e.g. `{ "x": 512, "y": 340 }` for `click`. | | `timeout_ms` | int\|null | no | null | 1000-120000. Defaults to the command's tuned timeout. | | `precondition_frame_id` | UUID\|null | external mutations | null | Exact `frame_id` whose pixels the action was planned against. Stale frames fail closed. Managed machines ignore it. | | `action_policy` | object\|null | no | null | Checked server-side before this direct action dispatch. | `parameters` is not a pass-through object. It is a strict discriminator selected by `command`: unknown keys, incomplete alias pairs, mixed mutually exclusive vocabularies, non-JSON values, and objects over 1,000,000 UTF-8 JSON bytes are rejected before dispatch. `GET /v1/models` exposes the complete runtime command list as `machine_action_commands`; the OpenAPI `ActionRequest.oneOf` is the machine-readable parameter catalog. | Command(s) | Exact parameter contract | Scope | | --- | --- | --- | | `screenshot`, `list_windows` | `{}` | `actions:exec` | | `click` | `{x:0..100000, y:0..100000, button?:left/right/middle, clicks?:1..3}` | `actions:exec` | | `double_click` | `{x, y, button?}` | `actions:exec` | | `click_with_modifiers` | click params plus one of `hold_keys?` / `modifiers?` (max 8 keys, each 1-64 chars) | `actions:exec` | | `type` | `{text:string<=1,000,000 chars, interval?:0..10 seconds}` | `actions:exec` | | `key_press` | exactly one of `{key:string}` or `{keys:string[1..100]}` | `actions:exec` | | `key_combo` | `{keys:string[2..8]}` | `actions:exec` | | `scroll` | exactly one of signed nonzero `clicks:-100..100` or `amount:1..100`; direction is vertical/horizontal/up/down/left/right; x/y are an optional pair | `actions:exec` | | `drag` | `{x1,y1,x2,y2,button?,hold_keys?:string[0..8]}` | `actions:exec` | | `switch_to_window` | `{window:string<=512}` | `actions:exec` | | `close_window`, `minimize_window`, `maximize_window`, `restore_window` | at most one of `window_title?:string<=512` / `window_id?:string<=128` | `actions:exec` | | `arrange_windows` | `{arrangement?:tile/cascade/minimize_all/show_desktop/restore_all}` | `actions:exec` | | `move_window` | `{x:-100000..100000,y:-100000..100000,window_title? xor window_id?,width?/height? paired}` | `actions:exec` | | `terminal_connect` | `{cwd?:string<=4096}` | `terminal:exec` | | `terminal_execute` | `{command:string<=8192,wait_for_output?:bool,timeout?:1..120 seconds,session_id?:string<=128,cwd?:string<=4096}` | `terminal:exec` | | `terminal_read`, `terminal_clear`, `terminal_close` | `{session_id?:string<=128}` | `terminal:exec` | | `file_read`, `file_download` | `path` or `filepath` (equal if both), plus `encoding?:auto/utf-8/base64` | `files:read` | | `file_exists` | `path` or `filepath` (equal if both; max 4096 chars) | `files:read` | | `directory_list` | optional `path` / `dirpath` alias (equal if both; default `.`) | `files:read` | | `file_list_downloads` | directory alias plus `recursive?:bool`, `max_files?:1..1000` | `files:read` | | `file_write`, `file_append` | required path alias plus `content:string` | `files:write` | | `file_edit` | required path alias plus exactly one complete pair: `find/replace` or `old_text/new_text`; `all` may only be true | `files:write` | | `file_delete` | required `path` / `filepath` alias | `files:write` | | `directory_delete` | required `path` / `dirpath` alias | `files:write` | | `browser_open`, `browser_open_tab` | `{url?:string<=8192}` | `actions:exec` | | `browser_navigate` | `{url:string<=8192}` | `actions:exec` | | `browser_click` | exactly one target: `selector:string<=4096`, `text:string<=4096`, or paired `x/y` | `actions:exec` | | `browser_type` | `{text:string<=1,000,000,selector?:string<=4096,clear?:bool}` | `actions:exec` | | `browser_get_dom`, `browser_get_clickables`, `browser_state`, `browser_info`, `browser_close`, `browser_list_tabs` | `{}` | `actions:exec` | | `browser_scroll` | `{direction?:up/down/left/right,amount?:1..100000}` | `actions:exec` | | `browser_screenshot` | `{selector?:string<=4096}` | `actions:exec` | | `browser_wait` | at most one of `selector?` / `text?`, plus `timeout?:1..120000 ms` | `actions:exec` | | `browser_close_tab` | at most one of `tab_index?:0..10000` / `index?:0..10000` | `actions:exec` | | `browser_switch_tab` | exactly one of `tab_index` / `index` | `actions:exec` | | `browser_execute` | exactly one of `script:string<=100000` / `code:string<=100000` | opt-in `browser:execute` | ```bash curl -s "$BASE/machines/$MACHINE_ID/actions" -H "$AUTH" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: action-$(uuidgen)" \ -d '{"command":"click","parameters":{"x":512,"y":340},"precondition_frame_id":"6e5ab4c4-5e56-4524-bce3-bcd8845b5679"}' ``` ```python import uuid frame = requests.get( f"{BASE}/machines/{machine_id}/screenshot", headers=HEADERS, timeout=60 ).json() res = requests.post( f"{BASE}/machines/{machine_id}/actions", headers={**HEADERS, "Idempotency-Key": str(uuid.uuid4())}, json={ "command": "click", "parameters": {"x": 512, "y": 340}, "precondition_frame_id": frame["frame_id"], }, timeout=60, ).json() print(res["success"], res["frame_id"], res["observation_available"]) ``` ```json { "machine_id": "mch_test_a1b2c3d4", "command": "click", "success": true, "result": { "success": true, "x": 512, "y": 340 }, "error": null, "duration_ms": 84, "screenshot": "data:image/png;base64,", "frame_id": "408673ce-6884-4f04-b3df-9ec5fd8d2a48", "observation_available": true, "request_id": "req_8f2c1e9a" } ``` For external control, the post-action observation above is the next turn's input: send its pixels to `/v1/predict`, then send the returned action with `precondition_frame_id: "408673ce-..."`. If a successful response has a `frame_id` but `observation_available: false`, the mutation is committed but the pixels are unavailable; capture a fresh screenshot and re-plan. Never repeat the mutation merely to recover its screenshot. ### POST /v1/machines/{id}/actions/batch Run an ordered list of actions in one round-trip. Body: `{ "steps": [ ActionRequest... ], "stop_on_error": true, "action_policy": {...} }` (max 50 steps; `stop_on_error` aborts on the first failure, shell `&&`-style). The optional top-level policy checks the complete batch atomically before step one; each ActionRequest may also carry its own policy. Returns `{ machine_id, results, completed_count, failed_count, aborted, request_id }`. On an external GUI, prefer single-action observe → plan → act turns. Every successful mutation creates a new `frame_id`, so the caller cannot safely bind a later coordinate action to an unknown future frame while constructing one batch. External batch steps with an omitted or stale precondition fail closed; the service never silently rebinds them to whatever happens to be on screen. ```bash curl -s "$BASE/machines/$MACHINE_ID/actions/batch" -H "$AUTH" \ -H "Content-Type: application/json" \ -d '{ "steps": [ {"command": "click", "parameters": {"x": 512, "y": 340}}, {"command": "type", "parameters": {"text": "you@example.com"}}, {"command": "key_press", "parameters": {"key": "enter"}} ], "stop_on_error": true, "action_policy": { "blocked_keys": ["escape"], "block_window_close": true } }' ``` ### POST /v1/machines/{id}/browser/{op} A convenience wrapper over browser commands. `op` is one of: `open`, `navigate`, `click`, `type`, `dom`, `clickables`, `state`, `info`, `scroll`, `close`, `screenshot`, `wait`, `list-tabs`, `open-tab`, `close-tab`, `switch-tab`. Body: `{ "parameters": {...}, "timeout_ms": null }`. Arbitrary JS (`browser_execute`) is intentionally NOT a browser op; send it through `/actions` with the `browser:execute` scope. ```bash curl -s "$BASE/machines/$MACHINE_ID/browser/navigate" -H "$AUTH" \ -H "Content-Type: application/json" \ -d '{"parameters":{"url":"https://example.com"}}' ``` ### POST /v1/machines/{id}/terminal Run a shell command. Requires `terminal:exec`. Output is truncated VM-side to 5000 chars; the hard timeout cap is 120s. **Request body** | Field | Type | Req | Default | Notes | | --- | --- | --- | --- | --- | | `command` | string | yes | - | 1-8192 chars. PowerShell on Windows, bash on Unix. | | `timeout_ms` | int | no | 30000 | 1000-120000. | | `session_id` | string\|null | no | null | Reuse a persistent terminal session. | | `cwd` | string\|null | no | null | Initial working directory. | ```bash curl -s "$BASE/machines/$MACHINE_ID/terminal" -H "$AUTH" \ -H "Content-Type: application/json" \ -d '{"command":"ls -la /tmp","timeout_ms":15000}' ``` ### POST /v1/machines/{id}/files/{op} File operations. `op` is one of: `read`, `exists`, `list`, `list-directory`, `download`, `list-downloads` (need `files:read`) or `write`, `edit`, `append`, `delete`, `delete-directory` (need `files:write`). Body: `{ "parameters": {...} }` where the params depend on the op (e.g. `{ "path": "..." }` for read, `{ "path": ..., "content": ... }` for write). ```bash # Read a file curl -s "$BASE/machines/$MACHINE_ID/files/read" -H "$AUTH" \ -H "Content-Type: application/json" \ -d '{"parameters":{"path":"/home/ubuntu/report.txt"}}' # Write a file (needs files:write) curl -s "$BASE/machines/$MACHINE_ID/files/write" -H "$AUTH" \ -H "Content-Type: application/json" \ -d '{"parameters":{"path":"/home/ubuntu/out.txt","content":"hello"}}' ``` --- ## 8. Schedules & Triggers A schedule fires an agent task against a machine on a cron/preset cadence, or in response to an inbound trigger (an HMAC-signed webhook, or when another schedule completes). Scopes: `schedules:read` (list/get/runs) and `schedules:write` (create/update/delete/pause/resume/run-now); adding or removing triggers needs `triggers:write`. A schedule id is a UUID (live) or `sch_test_<8-32 hex>` (sandbox). Test keys get mock schedules that never bill, capped at 10. A trigger id matches `trg_<8-32 hex>`. **Pricing.** Managed schedule defaults require at least $0.20 (20 credits) in the API wallet for create, run-now, and webhook fire — a gate, not a fee; there is no per-fire or per-trigger charge. Managed non-Unlimited execution uses the consumer subscription-credit balance at 10 credits per minute, with a 20-credit minimum to start and a 6-hour timeout. Unlimited bypasses that managed consumer meter but retains managed API-wallet eligibility. BYOK schedules bypass the wallet and subscription-credit gates, open no Coasty billing session, and record zero credits. Live-key fires can call and bill the selected provider. Managed-mode test-key fires remain deterministic sandbox executions and make no provider call; BYOK headers or provider metadata return `422 LLM_PROVIDER_UNSUPPORTED` before execution without reading a stored key. Concurrency, schedule, token, and abuse safeguards remain. Those are the published defaults; `GET /v1/models` → `pricing.schedules` returns the running deployment's separate create/run-now and webhook wallet gates, rate, start minimum, rounding policy, billing-session ceiling, and scheduler timeout. A fire that cannot meet the managed balance gate records a run with status `insufficient_credits`. BYOK and test schedules never bill Coasty (`credits_charged: 0`). ### Schedule endpoints | Method + path | Scope | Description | | --- | --- | --- | | `POST /v1/schedules` | `schedules:write` | Create a schedule. Honors `Idempotency-Key`. | | `GET /v1/schedules` | `schedules:read` | List schedules (`limit`, 1-200, default 50). | | `GET /v1/schedules/{id}` | `schedules:read` | Get one schedule. | | `PATCH /v1/schedules/{id}` | `schedules:write` | Update fields (at least one required). | | `DELETE /v1/schedules/{id}` | `schedules:write` | Delete a schedule. | | `POST /v1/schedules/{id}/run` | `schedules:write` | Fire once now (optional overrides). | | `POST /v1/schedules/{id}/pause` | `schedules:write` | Pause (stop firing). | | `POST /v1/schedules/{id}/resume` | `schedules:write` | Resume a paused schedule. | | `GET /v1/schedules/{id}/runs` | `schedules:read` | List run history (`cursor`, `status`, `limit`). | | `GET /v1/schedules/{id}/runs/{run_id}` | `schedules:read` | Get one schedule run. | | `GET /v1/schedules/{id}/triggers` | `schedules:read` | List a schedule's triggers. | | `POST /v1/schedules/{id}/triggers` | `triggers:write` | Add a webhook/chain trigger. | | `DELETE /v1/schedules/{id}/triggers/{tid}` | `triggers:write` | Remove a trigger. | | `POST /v1/triggers/webhook/{id}` | NONE (HMAC-signed) | Public fire endpoint hit by external systems. | | `GET /v1/triggers/health` | NONE | Liveness of the trigger service: `{"status":"ok","service":"public_triggers"}`. | | `GET /v1/schedules/health` | NONE | Liveness of the schedule service. | Triggers are **attached to a schedule**. There is no top-level `POST /v1/triggers` create endpoint: to add a webhook trigger you POST to `/v1/schedules/{schedule_id}/triggers`. The one-time HMAC secret comes back on that response as **`webhook_secret`** (there is no `signing_secret` field). ### POST /v1/schedules (create) Provide exactly one of `frequency` (a recurring preset) or `run_at` (a one-shot UTC timestamp). With `frequency: "custom"` you must also supply a raw `cron`. **Request body** | Field | Type | Req | Default | Notes | | --- | --- | --- | --- | --- | | `name` | string | yes | - | 1-128 chars. | | `machine_id` | string | yes | - | Target managed or connected external machine, owned by your key's user. | | `task_prompt` | string | yes | - | 1-8000 chars. The agent's instructions each fire. | | `frequency` | string\|null | no | null | `every_15_minutes`, `every_30_minutes`, `hourly`, `every_6_hours`, `every_12_hours`, `daily`, `weekly`, `monthly`, `custom`. | | `cron` | string\|null | no | null | Raw 5-or-6-field cron. Required when `frequency = "custom"`. | | `time` | string\|null | no | null | `HH:MM`, 24-hour. **Valid only for `daily`, `weekly`, `monthly`.** Rejected with 422 on every sub-daily frequency and on `custom`. See "Timing selectors" below. | | `timezone` | string | no | `UTC` | IANA timezone, e.g. `America/New_York`. | | `day_of_week` | int\|null | no | null | 0=Mon..6=Sun. **Valid only when `frequency: "weekly"`.** 422 otherwise. | | `day_of_month` | int\|null | no | null | 1-28. **Valid only when `frequency: "monthly"`.** 422 otherwise. | | `run_at` | string\|null | no | null | ISO-8601 UTC for a one-shot schedule. Mutually exclusive with `frequency`. | | `max_consecutive_failures` | int | no | 5 | 1-50. Circuit breaker: auto-pause after N failures. | | `metadata` | object\|null | no | null | String tags (max 16). | | `llm` | object\|null | no | managed | Non-secret BYOK provider/model-role preference. For live BYOK, store the provider key first; a header key is validation-only and must match it. | | `action_policy` | object\|null | no | null | Immutable policy inherited by every firing, retry, recovery, and nested CUA delegation. | Schedule creation accepts `action_policy` and fixes it for the schedule's lifetime. PATCH intentionally cannot change it; create a replacement schedule when the safety boundary must change. #### Timing selectors: `time`, `day_of_week`, `day_of_month` These three refine a preset. A refinement the chosen `frequency` **cannot express** is now a loud `422 VALIDATION_ERROR`, never a silent no-op and never a silent reinterpretation. All three used to be accepted and quietly dropped (or worse, quietly applied), so code written against the old behaviour may start seeing 422s. That is the point: the old behaviour was giving you a schedule you did not ask for. | Frequency | Preset cron | `time` | `day_of_week` | `day_of_month` | | --- | --- | --- | --- | --- | | `every_15_minutes` | `*/15 * * * *` | **422** | 422 | 422 | | `every_30_minutes` | `*/30 * * * *` | **422** | 422 | 422 | | `hourly` | `0 * * * *` | **422** | 422 | 422 | | `every_6_hours` | `0 */6 * * *` | **422** | 422 | 422 | | `every_12_hours` | `0 */12 * * *` | **422** | 422 | 422 | | `daily` | `0 9 * * *` | allowed | 422 | 422 | | `weekly` | `0 9 * * 1` | allowed | **allowed** | 422 | | `monthly` | `0 9 1 * *` | allowed | 422 | **allowed** | | `custom` | your `cron` | 422 | 422 | 422 | **Why `time` is rejected on sub-daily frequencies.** Applying a time-of-day to a recurring preset overwrites its minute and hour fields, which destroys the recurrence. `{"frequency":"hourly","time":"09:30"}` turned `0 * * * *` into `30 09 * * *`, a **daily** schedule. You asked for 24 fires a day and silently got one. Same for `every_15_minutes`, `every_30_minutes`, `every_6_hours`, and `every_12_hours`. The 422 body carries `valid_options` listing the frequencies that do accept a time. **Why they are rejected on `custom`.** With `frequency: "custom"` the cron **is** the schedule; there is nowhere for a separate time or day selector to go. Encode the timing in the cron expression itself. Whether a preset can carry a time is derived from the preset's own cron (both the minute and hour field must be fixed literals), not from a hand-kept list. Note also that the public contract for `day_of_week` is **0=Monday..6=Sunday**. Cron's own numbering (0=Sunday) is translated at the API boundary and never leaks into your request. ```bash # OK: daily at 14:30 New York time curl -s "$BASE/schedules" -H "$AUTH" -H "Content-Type: application/json" \ -d '{"name":"Nightly","machine_id":"m_9f2c","task_prompt":"...", "frequency":"daily","time":"14:30","timezone":"America/New_York"}' # 422 VALIDATION_ERROR: hourly fires more than once a day curl -s "$BASE/schedules" -H "$AUTH" -H "Content-Type: application/json" \ -d '{"name":"Hourly","machine_id":"m_9f2c","task_prompt":"...", "frequency":"hourly","time":"09:30"}' # -> "time is not supported for frequency='hourly', which fires more than once a # day. Applying a time-of-day would silently collapse it to a single daily run." # 422 VALIDATION_ERROR: day_of_week only applies to weekly curl -s "$BASE/schedules" -H "$AUTH" -H "Content-Type: application/json" \ -d '{"name":"Wrong","machine_id":"m_9f2c","task_prompt":"...", "frequency":"daily","day_of_week":2}' # 422 VALIDATION_ERROR: custom carries its timing in the cron curl -s "$BASE/schedules" -H "$AUTH" -H "Content-Type: application/json" \ -d '{"name":"Custom","machine_id":"m_9f2c","task_prompt":"...", "frequency":"custom","cron":"*/5 9-17 * * 1-5","time":"09:00"}' ``` ```bash BASE=https://coasty.ai/v1 AUTH="X-API-Key: $COASTY_API_KEY" curl -s "$BASE/schedules" -H "$AUTH" \ -H "Content-Type: application/json" \ -d '{ "name": "Daily invoice sweep", "machine_id": "mch_test_a1b2c3d4", "task_prompt": "Open the billing page and download every new invoice as PDF", "frequency": "daily", "time": "09:00", "timezone": "America/New_York", "action_policy": { "blocked_keys": ["escape"], "block_window_close": true, "max_actions": 80 } }' ``` A schedule (`ScheduleResponse`) returns `{ id, name, machine_id, task_prompt, enabled, frequency, cron, timezone, next_run_at, last_run_at, run_count, consecutive_failures, paused_reason, is_test, created_at, metadata, llm }`. `llm` is a credential-free provider/model-role preference plus key fingerprint, or null for managed mode. It is returned by create, get, list, PATCH, pause, and resume, never by schedule run-history records. The immutable `action_policy` is intentionally not echoed; retain the submitted policy or a hash in your audit records. `PATCH /v1/schedules/{id}` accepts any subset of `name`, `task_prompt`, `frequency`, `cron`, `timezone`, `time`, `day_of_week`, `day_of_month`, `max_consecutive_failures`, `enabled`, `metadata` (an empty body is a 400 `EMPTY_UPDATE`). It deliberately rejects `machine_id`, `run_at`, `llm`, and `action_policy`. Delete and recreate the schedule to change the target machine, one-shot time, BYOK provider/model-role preference, or safety policy. Rotating the separately stored provider key takes effect on the next fire without recreating the schedule. The schedule's displayed fingerprint remains the creation-time reference; per-fire usage records the actual key. #### PATCH preserves timing you do not restate **A PATCH that does not mention `time`, `day_of_week`, or `day_of_month` keeps the stored ones.** Previously it did not: a schedule row persists only `frequency`, `cron`, and `timezone`, so re-expanding the bare preset discarded the timing you originally sent. A PATCH that changed nothing but the timezone silently moved a "daily at 14:30" job back to the preset default of 09:00. The stored cron is the surviving record of that timing, so it is now read back out and merged. You only need to restate a selector when you want to change it. ```bash # A schedule created as daily @ 14:30 America/New_York. # Change ONLY the timezone: curl -s -X PATCH "$BASE/schedules/$SCHEDULE_ID" -H "$AUTH" \ -H "Content-Type: application/json" \ -d '{"timezone":"Europe/London"}' # -> still fires at 14:30, now in London time. (Before: reset to 09:00.) # Change ONLY the time: curl -s -X PATCH "$BASE/schedules/$SCHEDULE_ID" -H "$AUTH" \ -H "Content-Type: application/json" \ -d '{"time":"08:15"}' ``` Inheritance is applied only where it is **legal for the target frequency**, so a harmless PATCH cannot turn into a 422: - `time` is inherited only when the target frequency accepts a time. - `day_of_week` is inherited only when the target frequency is `weekly`. - `day_of_month` is inherited only when the target frequency is `monthly`. - Nothing is inherited when the target frequency is `custom`. So a PATCH from `daily` (at 14:30) to `hourly` succeeds and drops the time, rather than inheriting 14:30 and then rejecting itself. A PATCH that explicitly restates an illegal selector still gets the 422 from the table above. #### Read errors `GET /v1/schedules`, `GET /v1/schedules/{id}`, and `GET /v1/schedules/{id}/runs/{run_id}` return the proper typed envelope rather than a bare 500: | Status | Code | When | | --- | --- | --- | | 404 | `NOT_FOUND` | No such schedule in this key's namespace. The body echoes `schedule_id` and `key_kind`. | | 404 | `RUN_NOT_FOUND` | The schedule exists but has no such run. | | 503 | `DB_UNAVAILABLE` | Storage outage. Carries `Retry-After`. Retry; nothing has changed. | ### Run now / pause / resume `POST /v1/schedules/{id}/run` fires immediately; body (all optional): `{ "task_prompt_override": "...", "triggered_context": { ... } }`. It returns `{ schedule_id, run_id, status, message, request_id }`. `/pause` and `/resume` flip the schedule's `enabled` flag. ### Run history `GET /v1/schedules/{id}/runs` lists past fires: `{ data: [ { id, schedule_id, status, trigger, duration_seconds, credits_charged, error, executed_at } ], next_cursor, has_more, request_id }`. Filter with `?status=` (one of `completed`, `failed`, `skipped`, `cancelled`, `running`, `insufficient_credits`). `GET /v1/schedules/{id}/runs/{run_id}` returns a single run. Run-history records deliberately omit `llm`, provider credentials, prompts, screenshots, and provider-token totals. Read the schedule itself for its non-secret configured preference and the usage/export surfaces for attribution. Here, `credits_charged` is the consumer subscription-credit quantity used by managed scheduled execution, not a Developer API wallet cent field: it is 0 for BYOK, test, Unlimited-bypass, and other non-billable runs, and has no fixed USD conversion. ### Triggers `POST /v1/schedules/{id}/triggers` adds a trigger. `kind` is one of: - `webhook`: returns a public `webhook_url` plus a create-response-only `webhook_secret`. Optional `rate_limit_per_minute` (1-600, default 60). - `chain`: fires this schedule when `source_schedule_id` completes. Optional `event` (`on_complete` / `on_failure` / `on_any`, default `on_complete`) and `pass_output` (default true). Chain depth is capped at 5. The webhook `webhook_secret` appears only in a successful creation response, including an exact bounded Idempotency-Key replay (the response carries `Cache-Control: no-store`). It is encrypted at rest for signature verification and replay recovery; GET/list never expose it, so save it now. ### POST /v1/triggers/webhook/{id} (unauthenticated, HMAC-signed) External systems (Stripe, Linear, a CRM) fire a schedule by POSTing to the webhook URL. There is NO API key: the request is authenticated by an HMAC-SHA256 signature instead. Send the signature in the `Coasty-Signature` header as `t=,v1=`, where the signed payload is `"." + raw_request_body`. Published defaults allow 5 minutes of absolute timestamp skew and deduplicate identical `(webhook_id, raw_body)` fires for 60 seconds. Read the effective `webhook_replay_window_seconds`, `webhook_dedup_window_seconds`, `webhook_default_rate_limit_per_minute`, and `webhook_max_body_bytes` from `GET /v1/models` → `pricing.schedules`; sign with the current time rather than depending on the full replay window. Webhook fires are free — there is no routing fee. Managed schedules use the published $0.20 owner-wallet gate; BYOK schedules bypass it. Read `GET /v1/models` → `pricing.schedules.webhook_minimum_wallet_balance_cents` for the effective deployed gate. ```python import hashlib, hmac, json, os, time, requests BASE = "https://coasty.ai/v1" HEADERS = {"X-API-Key": os.environ["COASTY_API_KEY"]} SCHEDULE_ID = "sch_test_a1b2c3d4" # 1. Add a webhook trigger. Create/exact-replay responses return webhook_url + webhook_secret. trig = requests.post( f"{BASE}/schedules/{SCHEDULE_ID}/triggers", headers=HEADERS, json={"kind": "webhook"}, timeout=30, ).json() webhook_url = trig["webhook_url"] # https://coasty.ai/v1/triggers/webhook/whk_... webhook_secret = trig["webhook_secret"] # persist securely; absent from GET/list # 2. Sign and fire the webhook the way an external system would. body = json.dumps({"event": "invoice.created", "id": "inv_4821"}).encode() ts = str(int(time.time())) signed = ts.encode() + b"." + body sig = hmac.new(webhook_secret.encode(), signed, hashlib.sha256).hexdigest() res = requests.post( webhook_url, headers={ "Content-Type": "application/json", "Coasty-Signature": f"t={ts},v1={sig}", }, data=body, timeout=30, ).json() print(res["received"], res.get("run_id")) # {"received": true, "run_id": "...", ...} ``` The fire response is `{ received, schedule_id, run_id, deduplicated, message, request_id }`. A bad/missing/expired signature returns `401 INVALID_SIGNATURE`; a paused schedule returns `SCHEDULE_INACTIVE`; exceeding the per-webhook rate limit returns `429 RATE_LIMITED` (honor `Retry-After`). --- ## Links - Human docs: https://coasty.ai/docs - Manage API keys: https://coasty.ai/developers/keys - Site-wide LLM doc: https://coasty.ai/llms-full.txt