# API reference

> Every public operation of the Percia API, by group, with its scopes, parameters and body fields.

Page: https://percia.ai/docs/api. Index of all docs pages: https://percia.ai/docs/llms.txt

# API reference

Base URL: `https://playground.percia.ai/api`. The API has 171 operations in 17 groups (OpenAPI 3.1, document version 1.0.0). The live document is [playground.percia.ai/api/openapi.json](https://playground.percia.ai/api/openapi.json): download it into Postman, Insomnia or a code generator. This page is a snapshot of it.

## Authentication

Send a key or an OAuth token as a bearer token:

```bash
curl -sS https://playground.percia.ai/api/whoami -H "Authorization: Bearer pk_live_..."
```

- **API key** (`pk_live_...`): create it on the API keys page of the app. It carries scopes.
- **OAuth 2.1** with PKCE and dynamic client registration, for apps and agents. Discovery: `/.well-known/oauth-authorization-server`. Access tokens last one hour.
- A session cookie works from the web app only.

| Scope | Allows |
|---|---|
| `watches:read`, `watches:write` | Read watches, plan and usage; create and change watches, test a delivery, set the spend cap |
| `watches:delete` | Delete watches, agents, sites and connections, rotate a secret |
| `events:read` | Events, keyframes, metrics, the event stream |
| `cameras:read`, `cameras:write` | List cameras; add and remove cameras, create pairing links, upload video files |
| `integrations:read`, `integrations:write` | List connected tools; ask for a connect link, change defaults |
| `hooks:write` | REST hooks for Zapier, Make, n8n (opt-in) |
| `devices:write` | Push registration for the Percia Camera app |
| `context:write`, `signals:write` | Advanced features (opt-in) |

A missing scope answers `403 insufficient_scope` and names it. Creating API keys, adding a card, billing checkout and finishing a connect link need a signed-in person: a key cannot do them. See [Errors](https://percia.ai/docs/errors.md) for every status.

## Conventions

- JSON in and out. Times are ISO 8601 in UTC.
- Lists return newest first with a `nextCursor`; pass it back as `cursor`.
- Every response carries `x-percia-request-id`. Quote it in support requests.

## Reading what the engine sees

Seven read routes show what Percia is judging on a watch, beyond the events it sent. They need the scope `watches:read` and work on your own watches only (another account's watch answers `404`).

| Route | Returns |
|---|---|
| `GET /api/watches/{id}/capabilities` | Which features this watch's engine offers: `{engine, release, capabilities: [{name, available, reason?}]}` |
| `GET /api/watches/{id}/state` | The live state of each condition in the goal: `{available, reason?, asOf, stale, rows}` |
| `GET /api/watches/{id}/statistics` | Counts over the time Percia observed, with observed and unobserved seconds. A number over a gap means "at least": `{available, reason?, asOf, stale, rows}` |
| `GET /api/watches/{id}/gaps` | Time Percia could not check: `{available, reason?, asOf, stale, gaps}` |
| `GET /api/watches/{id}/episode` | The "tell me once" episode state: `{available, reason?, episode}` |
| `GET /api/watches/{id}/proofs` | The proofs of the watch's requirements: `{available, reason?, proofs, unprovable}` |
| `GET /api/watches/{id}/events/{eventId}/proof` | The proof behind one event. Empty lists when no requirement covers it |

A watch whose engine cannot report one of these answers `200` with `available: false` and a `reason` (`not_supported_on_engine` or `no_report_yet`). It is never an error, so check `available` before you read the rest.

## Operations

Click an operation to see its scopes, parameters and body fields. Request and response schemas are in the OpenAPI document.


## watches

- `POST /api/watches/owned` (watches:write): Create a watch as the signed-in user (email or webhook; no Turnstile). sourceUrl may be percia-cam://<cameraId> for one of your own paired or bridge cameras; a private address (192.168.x.x, an NVR) is refused: the person installs the Percia bridge (https://github.com/percia-ai/percia-bridge) to push that camera. Send `goal`, or `agentId` (+ optional `agentVersion`; omitted = follow the latest) to deploy a published agent: its concerns are what the watch judges, and a version a watch cannot run (more than 8 concerns, zones, excludeZones, minConfidence, rearmS, recheckS, cooldownS, a non-default budget, or a concern text plus ignore list over 2000 characters) answers 422 `agent_deploy_unavailable` with `error.field` naming the setting, and creates nothing. Percia reads the goal through its intelligence layer (see POST /watches/draft). Send `draftId` (a ready draft from POST /watches/draft, with `acknowledgeUnsupported: true` when it left parts out) instead of `goal`; the draft holds the conditions. A create with a `goal` is read by Percia's layer first. A clear goal creates the watch as before. An unclear one creates nothing and answers 422 `clarification_needed` with `draftId`, `question` and `options` (and `guidance`): ask the person, answer with POST /watches/draft/{draftId}/answer {text}, then create with {sourceUrl, draftId}; or send a clearer goal. Parts that cannot be watched answer 409 `unsupported_not_acknowledged` (tell the person, then repeat with `acknowledgeUnsupported: true`). Per-watch tuning knobs from older versions are refused with 422 `invalid_request` naming the field in `error.field` (cooldownS, kind, rearmS, recheckS, minConfidence, notWhen, zones, concerns, judgeKey, interpret, runtime): the goal and the draft say everything.
- `POST /api/watches/draft` (watches:write): Start a watch the clarifying way (Percia). Send the plain ask and the camera (`cameraId` of one of your cameras, or a public `sourceUrl`). Percia's intelligence layer reads it and answers with a draft: `status` clarifying (ask the person `question`; `options` are numbered meanings they may pick by number or replace with their own words), ready (conditions understood: create the watch with POST /watches/owned {draftId, sourceUrl}), or refused (nothing visible is left to watch). `unsupported` lists parts that cannot be watched (audio, several cameras, who someone is: `refused` true); when `needsAcknowledgement` is true tell the person, then create with `acknowledgeUnsupported: true`. Nothing is created yet.
- `GET /api/watches/draft/{id}` (watches:read): Read a clarify draft (your own): its status, question, options, conditions and the conversation so far.
- `POST /api/watches/draft/{id}/answer` (watches:write): Answer the draft's question: `text` is the number of one of the options ("2") or the person's own words. Only a draft that is still clarifying takes an answer; a draft that became a watch is closed (a running watch is never questioned). Returns the updated draft (a new question, or ready). When the layer cannot use the words, they are joined to the first ask and read again as one new ask (`restated: true`).
- `GET /api/watches/{id}` (watches:read): Get one of the signed-in user's watches
- `PATCH /api/watches/{id}` (watches:write): Update a watch. `status: "active"` with `testRun: true` starts a 30-minute live test run (events are marked test events); `status: "active"` alone goes live, also from a running test, with no restart. A new `goal` is read by Percia as on create, before anything changes: a running watch judges the new conditions within seconds, a paused one stays paused, and the answer carries `understanding`. If the goal cannot be accepted, nothing in the request is applied and the watch keeps its earlier goal: 422 `clarification_needed` (`question`, `options`; send the PATCH again with the answer in `goal`), 409 `unsupported_not_acknowledged` (leave that part out, or add `acknowledgeUnsupported: true`), 422 `draft_refused` or `draft_multi_watch`, 503 `layer_unavailable`, `layer_unconfigured` or `layer_budget`, 429 `rate_limited`. Earlier events are not rewritten. On a watch made with `advanced` conditions the goal only renames it. `agentId` (+ `agentVersion`, null = follow latest) deploys an agent and the watch restarts on its concerns; `agentVersion` alone re-pins; a new `goal` detaches the agent. A version the watch cannot run answers 422 `agent_deploy_unavailable` naming the setting in `error.field`, and changes nothing.
- `DELETE /api/watches/{id}` (watches:write, watches:delete): Delete a watch
- `POST /api/watches/{id}/secret/rotate` (watches:write, watches:delete): Rotate the webhook signing secret (the old one stops working at once)
- `POST /api/watches/{id}/test-delivery` (watches:write): Send a signed goal.test event to the watch's webhook and report the response
- `GET /api/watches/mine` (watches:read): List the signed-in user's watches
- `GET /api/watches/{id}/events` (events:read): Page through a watch's events, newest first
- `GET /api/watches/{id}/capabilities` (watches:read): Which engine features this watch's engine line offers
- `GET /api/watches/{id}/state` (watches:read): Live state of each condition
- `GET /api/watches/{id}/statistics` (watches:read): Counts over observed time
- `GET /api/watches/{id}/gaps` (watches:read): Time the engine could not check
- `GET /api/watches/{id}/episode` (watches:read): Tell-me-once episode state
- `GET /api/watches/{id}/proofs` (watches:read): Proofs of the watch's requirements
- `GET /api/watches/{id}/events/{eventId}/proof` (watches:read): The proof behind one event

## events

- `GET /api/events` (events:read): List events across all your watches, newest first
- `GET /api/events/stream` (events:read): Developer event feed: server-sent events of your account, for local development
- `GET /api/events/sample` (events:read): One example event in the shape of the feed

## cameras

- `GET /api/cameras` (cameras:read): List your cameras, newest first
- `POST /api/cameras` (cameras:write): Create a camera. For a camera on a private network (ONVIF, RTSP, Frigate, Home Assistant, NVR) the person installs the Percia bridge (https://github.com/percia-ai/percia-bridge), which registers the cameras itself. Default (a paired phone, tablet or computer; its deviceKind is set when it opens the link): returns a pairing link (single use, 10 minutes). With kind:"push" (cameras on a private network, a connector pushes WHIP): returns whipUrl and a publish `token` shown once, no pairing; send externalId (or an Idempotency-Key header) so a re-registering connector gets the same camera back (200, token null, existing true). 404 while cameras are switched off.
- `POST /api/cameras/link` (cameras:write): Make a camera from a public video link (rtsp, rtsps, http or https). Percia pulls it on its media host while a watch on it is active, so the camera then works like any other: use percia-cam://<id> as a watch's sourceUrl. The same link returns the same camera (200, existing true). A watch created with the link itself as sourceUrl does this for you. A private address (192.168.x.x, 10.x.x.x, localhost, an ONVIF/RTSP/Frigate/Home Assistant camera on a home network) is refused with 400 and a pointer to the Percia bridge. 404 unless link cameras are on.
- `POST /api/cameras/{id}/pair` (cameras:write): Issue a new pairing link; any unused earlier link stops working (no request body; phone, tablet and computer cameras)
- `POST /api/cameras/bulk` (cameras:write): Register up to 10 push cameras at once (an NVR connector). Each needs name and externalId and is idempotent by externalId (existing ones come back with token null). All or nothing against the 10-camera limit (429 camera_limit, nothing created).
- `GET /api/cameras/{id}/status` (cameras:read): Poll one camera: state waiting (never published), online, offline or revoked, lastSeenAt, secondsSinceSeen and a hint with the likely reason and next step. Online means a heartbeat or allowed publish under 60 s ago. Codec, resolution and bitrate are not available (media server API is off).
- `POST /api/cameras/{id}/token` (cameras:write, watches:delete): Rotate the publish token of a push camera (no request body); the old one stops working at once. Returns the new token once. Phone, tablet and computer cameras: 409 wrong_kind (pair again).
- `DELETE /api/cameras/{id}/token` (cameras:write, watches:delete): Revoke the publish token of a push camera: publishing stops at once, the camera stays. Rotate to publish again.
- `POST /api/cameras/pair/check` (cameras:write): Check that a pairing token belongs to one of your cameras and has not expired. show_link does this for you
- `PATCH /api/cameras/{id}` (cameras:write): Rename a camera (any kind); its pairing, token and watches are unchanged
- `DELETE /api/cameras/{id}` (cameras:write, watches:delete): Remove a camera; its token stops working at once
- `POST /api/cameras/{id}/live` (cameras:read, events:read): Live view of one camera, before or without a watch (paired and push cameras): a WHEP address and a 10 minute viewer token for that camera only
- `POST /api/cam/claim`: Pair a camera: exchange the single-use pairing token for the camera token (returned once). Public, rate limited per IP.
- `GET /api/cam/whip`: Where this camera publishes right now. Authorization: Bearer <camera token>. Returns {whipUrl}: the camera's home relay host while it is up, else another up relay. Ask on every (re)connect so a relay failure moves the camera by itself; a client that stored the URL stays on that relay. 401 for a wrong or revoked token, 404 when cameras are switched off.
- `POST /api/cam/site-token/revoke`: End the website hand-off's publish session of this camera (no request body). Authorization: Bearer <camera token, or the website's publish token>. Every token of the session stops working; a stream already open runs until it is closed.
- `POST /api/cam/stopped`: The camera says it stopped sending (no request body). Authorization: Bearer <camera token>. It shows offline at once instead of after the heartbeat window; the next heartbeat or allowed publish shows it online again.
- `POST /api/cam/heartbeat`: Camera is alive (no request body). Authorization: Bearer <camera token>: a paired camera's token or a push camera's publish token. Send it every 20 s while publishing; online = under 60 s since the last heartbeat or allowed publish. 401 for a wrong, rotated or revoked token or a deleted camera.

## uploads

- `GET /api/uploads` (cameras:read): List your video files, newest first
- `POST /api/uploads` (cameras:write): Start uploading a video file (mp4, mov, webm, mkv) as a watch source. Declare name and size; refused here (400 unsupported_type, 413 too_large, 429 upload_limit) before any byte moves. Returns the id, `partSize` and `parts`: send each part with PUT /uploads/{id}/parts/{n}, then POST /uploads/{id}/complete. 404 while video files are off.
- `POST /api/uploads/from-url` (cameras:write): Make a video file from a public https URL (for MCP agents, which cannot send bytes). Percia fetches it itself, one request: public https only (no IP addresses, private or internal names, user names or odd ports; each redirect is checked again), content type must be a video (mp4, mov, webm, mkv) or a generic binary with a video file name, and the same size and length limits as an upload apply (400 invalid_url, 400 unsupported_type, 400 fetch_failed, 413 too_large, 400 too_long, bad_container, bad_codec, 429 upload_limit). Returns the ready upload: `uploadId` (= `id`) and `source` (`percia-file://<uploadId>`), which you pass as `sourceUrl` to POST /watches/owned. 404 while video files are off.
- `POST /api/uploads/link` (cameras:write): Make a short-lived upload page for a video file on the person's own device (for MCP agents, which cannot send bytes). No body. Returns `uploadUrl` (valid 30 minutes, no sign-in needed on it): show it to the person with show_link, never as plain text. They pick the file on that page and it uploads and is checked. When they say it is done, GET /uploads and take the newest file with `status: ready` and `createdAt` after the link's `createdAt`: its `source` (`percia-file://<id>`) is the `sourceUrl` for POST /watches/owned. 404 while video files are off.
- `PUT /api/uploads/{id}/parts/{n}` (cameras:write): Send part n (1-based) as the raw request body (application/octet-stream). Every part but the last is exactly `partSize` bytes. Returns the etag to give to /complete. A part may be sent again. Needs a client that can send bytes: MCP agents cannot, a person uses the app.
- `POST /api/uploads/{id}/complete` (cameras:write): Finish the upload with the part etags. The file is read back and checked: container, codec (H.264, H.265, VP8, VP9, AV1) and length (over the limit = too_long). A refused file is deleted at once (400 bad_container, bad_codec, too_long). Returns the upload; `source` is its watch source.
- `GET /api/uploads/{id}` (cameras:read): One video file
- `DELETE /api/uploads/{id}` (cameras:write, watches:delete): Delete a video file (or stop an upload). The file also goes with the last watch that uses it, with the account, and after its retention period.
- `GET /api/uploads/{id}/play` (cameras:read): A short-lived (15 minutes) signed address for playing the file in a video element. A credential: do not store or share it.
- `GET /api/files/{id}`: The signed, ranged read of a video file (query exp and sig). Used by the pool and the player; the signature is the credential. Never cached.

## integrations

- `GET /api/integrations/services` (integrations:read): Services a watch can reach. available is false when Percia has no app for that service yet.
- `GET /api/integrations` (integrations:read): List your connected destinations
- `POST /api/integrations/connect` (integrations:write): Create a single-use link for a person to connect a service. Only a person can add a destination: an agent shows the link and waits to be told it is done.
- `GET /api/integrations/connect/{token}`: What a connect link can do, for the connect page (session only)
- `POST /api/integrations/connect/{token}/start`: The person pressed Connect: returns the page to send them to (the service's approval page, or the Telegram bot) (session only)
- `POST /api/integrations/connect/{token}/url`: Finish a Home Assistant, Microsoft Teams or webhook connect with a public https URL (session only). Teams takes only a Workflows webhook address (logic.azure.com or environment.api.powerplatform.com).
- `POST /api/integrations/connect/{token}/key`: Finish an IFTTT connect (Webhooks key and event) or a PagerDuty connect (Events API v2 integration key and severity info|warning|error|critical, default warning) (session only)
- `POST /api/integrations/connect/{token}/twilio`: Finish an SMS or WhatsApp connect with the person's own Twilio credentials (session only)
- `GET /api/integrations/callback/{service}`: Where Slack and Discord return the browser (session only). Redirects to /integrations?connected=<service> or ?connect_error=<code>.
- `POST /api/integrations/telegram/webhook`: Telegram bot updates (authenticated by X-Telegram-Bot-Api-Secret-Token)
- `PATCH /api/integrations/{id}` (integrations:write): Make a destination a default (attached to every new watch automatically) or stop doing so. applyToExisting also adds it to the watches you already have.
- `DELETE /api/integrations/{id}` (integrations:write, watches:delete): Disconnect a destination and remove its rules. Past delivery results stay until they age out (30 days).
- `POST /api/integrations/{id}/test` (integrations:write): Send one labelled test alert ("Percia test: ignore") to one of your connected destinations, to check it works. No event or delivery is recorded and the connection is not changed. At most 5 an hour per connection (2 for SMS and WhatsApp).
- `GET /api/watches/{id}/integrations` (watches:read): The connected destinations this watch sends to when its goal is met
- `PUT /api/watches/{id}/integrations` (watches:write): Replace the watch's rules (at most 5). They add to its notify and agent actions; an empty list removes them all.

## hooks

- `GET /api/hooks` (hooks:write): List your REST hooks
- `POST /api/hooks` (hooks:write): Register a REST hook that receives each event, signed
- `DELETE /api/hooks/{id}` (hooks:write): Remove a REST hook (idempotent)
- `POST /api/hooks/{id}/test` (hooks:write): Send one signed goal.test event to the hook and report the answer

## billing

- `POST /api/stripe/webhook`: Stripe webhook receiver (signed by Stripe)
- `POST /api/billing/checkout`: Start a Stripe checkout (403 selling_disabled while paid plans are not on sale; 409 already_subscribed when the account already has a subscription: use the portal)
- `PATCH /api/billing/cap` (watches:write): Set your monthly spend cap in cents ($5 to $10,000; default $200). When this month's camera time reaches it, watches pause (only while billing is enforced). Change it only when the person asks.
- `POST /api/billing/redeem` (watches:write): Redeem a credit code for camera-minutes (credits are minutes of watching, used before the free minutes and before the card). A code is shown to its owner once: pass it in the body, never in a URL. Needs a card on file while billing is on sale: without one it answers 402 card_required with addCardUrl (the Billing page; only a person can add a card) and the code is not checked or used. Unknown, disabled and expired codes all answer 404 code_invalid; a code with no redemption left is 409 code_fully_claimed; the same person redeeming twice is 409 code_already_redeemed; too many tries is 429 rate_limited with Retry-After.
- `GET /api/billing/credits` (watches:read): Your credit grants (minutes, remaining, source, expiry) and your last 20 redemptions. Never returns a code.
- `POST /api/billing/pay-invoice`: Retry paying the open failed invoice with the stored payment method (session only; allowed while blocked). To change the card use the portal.
- `POST /api/billing/portal`: Open the Stripe customer portal (also the way to update a failed payment method)
- `POST /api/billing/card/replace`: Replace your card: a Stripe setup Checkout that adds a new card and charges nothing (a card must stay on file: it can be replaced, never removed). 404 when no card was added yet.
- `POST /api/billing/card/finish`: After a replace: the newest card becomes the default and older cards are detached; the last card is never detached. Safe to repeat.
- `GET /api/usage` (watches:read): Daily usage (UTC days): active watch-hours, camera-minutes (what is priced), events, model calls and action calls
- `GET /api/usage/cameras` (watches:read): This UTC month's camera minutes per camera (a Percia camera by its name, a video link by its host), priced at the list price. `costCents` is list price, not what was charged: free and credit minutes are used first (see /plan). `unattributedMinutes` are minutes metered before per-camera counting began.
- `GET /api/plan` (watches:read): Your plan (free, or pro shown as Pay as you go), its limits and your current counts. Limits count active watches only and bind only when `enforced` is true; when it is false they are just reported, so never ask the user to pause or delete anything because of them. `selling` says whether paid plans are on sale (false during the free preview). Pricing: $0.50 per camera-hour per camera (`pricing`), up to 10 active watches per camera (always enforced); `freeMinutesLeft` of the free camera-minutes, `monthToDate` camera-minutes and cost in cents, the spend cap `capCents`; watches pause for billing only when `billingEnforced` is true.

## identity

- `GET /api/auth/{path}`: Sign-in, session and OAuth endpoints (GET /auth/oauth2/authorize; see /docs/automation-platforms.md)
- `POST /api/auth/{path}`: Sign-up, sign-in, sign-out and OAuth endpoints (POST /auth/oauth2/token, /auth/oauth2/register, /auth/oauth2/revoke; see /docs/automation-platforms.md)
- `GET /api/whoami`: Who the credential belongs to (connection test)
- `GET /api/me`: Current user and subscription
- `GET /api/me/sign-in-methods`: How this account signs in: the linked providers (Google, GitHub, Apple) with when they were linked, and whether it has an email and password. Session only; never a token or provider id.
- `POST /api/me/delete`: Delete your account and all its data (session, or an OAuth token with account:delete; never an API key). Body {confirm: <account email>}. The sign-in must be under 15 minutes old.
- `GET /api/keys`: List your API keys (prefix, scopes, created, last used, revoked). Never the key itself.
- `POST /api/keys`: Create an API key (session only). The full key is returned once.
- `DELETE /api/keys/{id}`: Revoke an API key immediately
- `GET /api/connected-apps`: List OAuth apps (MCP clients) you approved: name, permissions, last used (session only)
- `DELETE /api/connected-apps/{clientId}`: Revoke an OAuth app immediately (session only)
- `GET /api/session-hint`: Is this browser signed in? Reads the session cookie only and answers {signedIn} (no user data). For the website (the Worker's SITE_URL): CORS with credentials for its origins and the privacy center only; any failure is {signedIn:false}.

## evidence

- `GET /api/watches/{id}/events/{eventId}/keyframe` (events:read): The decrypted keyframe (JPEG) of an event. Needs events:read with an API key.
- `GET /api/cameras/{id}/thumbnail` (cameras:read, events:read): The latest snapshot (JPEG) of one of your cameras, cut from its recording: the picture on watch cards and camera tiles. 404 when the camera never sent video. Needs cameras:read and events:read with an API key.
- `GET /api/watches/{id}/events/{eventId}/keyframe/link` (events:read): A 10 minute link to the event's keyframe that needs no credential (for viewers that can only load a URL, such as the MCP event card). Needs events:read with an API key.
- `GET /api/watches/{id}/events/{eventId}/clip` (events:read): The event's clip (video/mp4, H.264, no audio): from about 10 seconds before the event to 6 seconds after it, cut from the camera's recording. Supports `Range` requests. Needs events:read with an API key.
- `GET /api/watches/{id}/events/{eventId}/clip/link` (events:read): A 10 minute link to the event's clip (or its keyframe with `?kind=keyframe`) that needs no credential: hand it to a person or a viewer that can only load a URL. Needs events:read with an API key.
- `GET /api/evidence/{token}`: The clip (video/mp4, ranges supported) or keyframe (JPEG) a signed link names. Public: the token is the credential, it names one event and expires (24 hours for links in email, integrations and webhook bodies; 10 minutes for links minted for the app and agents). 404 for anything else, always the same answer.
- `GET /api/img/{token}`: The image a signed link names (JPEG). Public: the token is the credential; 404 once it expires (10 minutes for the app and agents; a link sent to a connected service does not expire by itself) or the keyframe is gone (deleted after its retention days, or with its watch).
- `POST /api/watches/{id}/live` (watches:write): Live view of a watch. Paired and push cameras get a WHEP address and a 10 minute viewer token; other sources get the latest keyframe.
- `GET /api/watches/{id}/misses` (watches:read): The misses reported on a watch, newest first, with what the engine did with each
- `POST /api/watches/{id}/misses` (watches:write): Report a miss: the watch should have alerted in this window and did not. The window is at most 600 seconds, not in the future, not older than 30 days. On a running Percia watch it goes to the engine as a `missed` report (recall evidence); otherwise it is only recorded. `concernId` is needed only when the watch has several conditions.
- `GET /api/watches/{id}/quality` (watches:read): How right one watch is. `marks` are exact counts of your own Correct / False alarm / Partly / Missed marks (`rightShare` is null until 3 events are rated). `engine` is the running engine's own estimate (precision and recall of its champion and floor with 90% intervals and n, or the reason when there is nothing to estimate), as last reported; null for other engines. Estimates, never ground truth.
- `GET /api/quality` (watches:read): How right all your watches are: totals from your marks, events still to review (unmarked alerts of the last 14 days), one row per watch, and a coaching tip when your marks give a real basis
- `POST /api/watches/{id}/events/{eventId}/feedback` (watches:write): Mark an event correct, a false alarm, or partly right (`partly` needs the correction in `note`). With a keyframe a correct or false alarm becomes (or updates) a test case with the image pinned. Leave `note` out to keep the note already stored; send an empty string to clear it. On a Percia event the mark also goes to the watch's running engine: `engine` says whether it was applied or only recorded, and why.
- `GET /api/agents/{id}/tests` (watches:read): The agent's test cases (pinned examples), newest first
- `GET /api/agents/{id}/tests/runs` (watches:read): Latest test runs of the agent (20), newest first
- `POST /api/agents/{id}/tests/run` (watches:write): Judge every test case (at most 50) against a version of the agent, or its draft, and store the run
- `DELETE /api/tests/{caseId}` (watches:write, watches:delete): Delete a test case and its pinned image
- `GET /api/tests/{caseId}/image` (events:read): The pinned image (JPEG) of a test case
- `GET /api/tests/{caseId}/image/link` (events:read): A 10 minute link to the test case image that needs no credential (see /img/:token). Needs events:read with an API key.
- `GET /api/metrics` (watches:read): Per watch and per agent: events per day, feedback counts, false-alarm rate and the last test pass rate

## agents

- `GET /api/deployments` (watches:read): List your watches that run an agent, with agent, version (pinned or latest), status and last event
- `GET /api/agents` (watches:read): List your agents, newest first
- `POST /api/agents` (watches:write): Create an agent with this config as its draft (at most 50 per user)
- `POST /api/agents/build` (watches:write): Describe what to watch for in plain words; the builder creates an agent (draft) and explains it. 30 builder calls per user per hour.
- `GET /api/agents/{id}` (watches:read): Get one of your agents: draft, published config and versions
- `PATCH /api/agents/{id}` (watches:write): Update the name and/or the draft (published versions never change)
- `DELETE /api/agents/{id}` (watches:write, watches:delete): Delete an agent and its versions
- `POST /api/agents/{id}/publish` (watches:write): Freeze the draft as the next version. Deployments following the latest version move to it.
- `GET /api/agents/{id}/versions/{version}` (watches:read): One frozen version of an agent
- `POST /api/agents/{id}/chat` (watches:write): Ask the builder to change the draft in plain words. It sees the draft and the last 20 messages.
- `GET /api/agents/{id}/messages` (watches:read): The builder conversation for this agent, oldest first (last 100)
- `POST /api/agents/{id}/actions/{index}/test` (watches:write): Run one action of the draft against a sample event (counts toward 60 action calls per hour)

## sites

- `GET /api/sites` (watches:read): List your sites with watchCount and memoryUpdatedAt
- `POST /api/sites` (watches:write): Create a site (at most 20 per user). Watches join it with siteId on create or PATCH.
- `GET /api/sites/{id}` (watches:read): Get a site: notes, memory (brief, entities), memoryRev and its watches
- `PATCH /api/sites/{id}` (watches:write): Update the name and/or notes. A notes change updates the context of every watch in the site.
- `DELETE /api/sites/{id}` (watches:write, watches:delete): Delete a site. Its watches keep working without context.
- `POST /api/sites/{id}/memory/clear` (watches:write, watches:delete): Reset the brief and entities (notes stay)
- `PATCH /api/sites/{id}/memory` (watches:write): Correct the memory: brief and/or entities (at most 30)
- `POST /api/sites/{id}/ask` (watches:read): Ask Percia a question about the site; answers from the memory, notes and the last 200 events. 30 per user per hour. API keys need only watches:read.
- `GET /api/sites/{id}/timeline` (watches:read): Page through the events of all watches in the site, newest first

## tests

- `GET /api/quality/tests` (watches:read): The test side of Quality: ground-truth clips (total and across how many watches), tests started in the last 7 days, and per watch its clip count and the scores of its last finished test (`caught`, `falseAlarms` as value/of, or null when unmeasured).
- `GET /api/watches/{id}/dataset` (watches:read): The watch's dataset: clips labelled should_match, should_not or counterfactual. They are the ground truth tests score against.
- `POST /api/watches/{id}/dataset` (watches:write): Upload one clip to the dataset: multipart/form-data with `file` (MP4 or MOV, up to 32 MB and 120 s), `label` (should_match, should_not, counterfactual) and an optional `note` (up to 120 characters).
- `GET /api/watches/{id}/dataset/near-misses` (watches:read): Moments worth labelling: close calls (alerts the judge was barely sure of), false alarms you marked (events with a stored clip) and the misses you reported (windows, cut from the recording when you keep them), none of them in the dataset yet. Offered, never added by themselves: label an event with POST .../dataset/from-event and a reported miss with POST .../dataset/from-miss.
- `POST /api/watches/{id}/dataset/from-event` (watches:write): Keep an event's clip in the dataset with a label. An event already in the dataset only has its label changed. Marking an event Correct or False alarm does this by itself (should_match / should_not).
- `POST /api/watches/{id}/dataset/from-miss` (watches:write): Keep a miss you reported (POST /watches/{id}/misses) as a dataset clip with a label: the footage of the first 100 seconds of the window you reported is cut from the camera's recording (the last 14 days) and stored sealed. The moment's start inside the clip is unknown, so a clip from a miss has no delay. A miss already in the dataset only has its label changed.
- `POST /api/watches/{id}/dataset/from-link` (watches:write): Keep a video from a pasted link as a dataset clip: {url, label, note?}. Percia fetches the link once (a public https link straight to an MP4 or MOV, up to 32 MB and 120 s; no address numbers, no password in the link, at most three redirects, each checked again), stores the video sealed and does not keep the link. 20 links an hour per user.
- `PATCH /api/watches/{id}/dataset/{clipId}` (watches:write): Change a clip's label or note.
- `DELETE /api/watches/{id}/dataset/{clipId}` (watches:write, watches:delete): Delete a clip and its stored video. The dataset also goes with the watch and with the account.
- `GET /api/watches/{id}/dataset/{clipId}/thumb` (events:read): A clip's thumbnail (the event's keyframe), decrypted for the owner. 404 for an uploaded clip (it has none).
- `GET /api/watches/{id}/tests` (watches:read): The watch's test runs, newest first, and the latest finished one with its scores. A test replays the watch on recorded video and scores it; nothing is delivered.
- `POST /api/watches/{id}/tests` (watches:write): Start a test. JSON {source: "recent", minutes?: 1..10} replays the camera's last minutes, {source: "window", from, minutes?: 1..10} an earlier time (up to 14 days back, ending at least a minute ago; the host's recording for about two hours, the sealed archive beyond that), {source: "dataset"} replays the dataset clips (the newest 40) and scores them: Caught = should_match clips the judge said yes on, False alarms = should_not and counterfactual clips it said yes on. Or multipart/form-data with `file` tests one uploaded clip (deleted afterwards; no labels, so no scores, only what it would alert on). Uses the pool's judge at half the camera's hourly cap. 10 tests an hour per user, one at a time per watch.
- `GET /api/watches/{id}/tests/{testId}` (watches:read): One test run. While it runs, `status` is running and there are no scores; when it ends, `scores` has Caught, False alarms, Avg delay and Verdict (each a figure with its total, or null with a note saying why it is unmeasured), the clips' outcomes, the alerts a window test found, coverage and the per-condition capability report.
- `GET /api/test-clips/{testId}/{clipId}`: The signed, short-lived read of one dataset or uploaded clip for a running test, or (clipId arc-<n>) of one five minute range of the camera's archive for an earlier-time test (query exp and sig). Used by the pool's test job; the signature is the credential. Never cached.

## advanced

- `GET /api/sites/{id}/context` (watches:read): Read the site's context and its open context requests (advanced)
- `PUT /api/sites/{id}/context` (context:write): Replace the site's context (SiteContext): calibration, facts, zones, named_zones, signal declarations (advanced)
- `GET /api/sites/{id}/zones` (watches:read): List the named zones of a site: id, name, per-camera polygons, and whether the engine has seen them (advanced)
- `POST /api/signals` (signals:write): Send timed machine signals (Signal) for a camera or site (advanced)
- `GET /api/watches/{id}/actions` (events:read): The typed recommendations (ActionEvent) the engine made for an advanced watch, newest first

## devices

- `GET /api/devices` (devices:write): List your registered phones (the push token is never returned)
- `POST /api/devices` (devices:write): Register this phone for push alerts (Percia Camera app). Upserts by Expo push token: a token registered by someone else moves to you. Alerts carry only the watch goal, 'Goal met' and the time.
- `DELETE /api/devices/{token}` (devices:write): Stop push alerts to one phone (your own Expo push token, URL-encoded). Needs only devices:write

## voice

- `POST /api/talk/mic/token`: Voice input in Talk to Percia: a speech token for one recording (session only; a person at the screen)
- `POST /api/talk/mic/end`: Voice input: report that a recording ended, so unused seconds are given back (session only)
- `POST /api/talk/chat`: Talk to Percia: one chat message, the reply streamed as server-sent events (session only; a person at the screen)
- `POST /api/talk/chat/confirm`: Talk to Percia: run the action of a card the person tapped (session only). One use, ten minutes
- `POST /api/talk/speak`: Talk to Percia: speak a sentence or two of a reply (session only). Counted in characters per day
- `POST /api/talk/handsfree/start`: Talk to Percia: a speech token for one hands-free conversation (session only). Its whole length is held against the chat's spend caps
- `POST /api/talk/handsfree/end`: Talk to Percia: report that a hands-free conversation ended, so unused time is given back to the caps (session only)

## platform

- `GET /api/health`: Liveness check
- `GET /api/config`: Public client configuration
- `GET /api/status`: Public status of each alert destination
- `GET /api/openapi.json`: This document

## live

- `GET /api/live/sessions` (watches:read): Your recent Live sessions, newest first.
- `POST /api/live/sessions` (watches:write): Start a Live (Beta) session on one of your cameras: ask it questions and get alerts. Caps for every account: a session lasts at most 600 s and USD 10 (the engine currently ends a session at USD 5.00, so read `endedReason` and `spendUsd`), ends after 120 s without a question or poll, USD 50 a day per account; 5 open sessions per account, 20 open in all. Free during the Beta: `billedMinutes` is 0. Cameras only in this version (paired, push or link cameras that are online); the browser-frames source ("this device's camera") stays in the app. `alertWhen` is the alert condition ("tell me when ..."). The session starts in the background: an ask in the first 90 seconds can answer 503 `live_starting`. Stop it with POST /live/sessions/{id}/stop.
- `GET /api/live/sessions/{id}` (watches:read): One Live session: `status`, `caps`, `spendUsd`, `billedMinutes` and, once it ended, `endedReason`. Reads still work while Live is switched off.
- `GET /api/live/sessions/{id}/events` (watches:read): What happened in a session after `after` (0 = from the start): answers, alerts with a keyframe and clip link, and `live.ended`. Poll every 2 seconds while open; each poll counts as activity for the idle timeout. After the end it answers one `live.ended` event.
- `POST /api/live/sessions/{id}/ask` (watches:write): Ask a question about what the camera sees now. Answers in a few seconds with the picture it looked at. Counts as activity.
- `POST /api/live/sessions/{id}/stop` (watches:write): Stop a session now. Safe to repeat. Always stop a session you are done with: it frees the account's open-session slot.
