# Percia documentation (all pages) # Percia documentation > Percia watches a camera or a video for something you describe in plain words, and tells you or your app when it happens. Page: https://percia.ai/docs/. Index of all docs pages: https://percia.ai/docs/llms.txt # Percia documentation Percia looks at a camera for you. You say what to watch for ("a person is at the front door", "the gate is open", "more than 3 cars are in the loading bay"). When it happens, Percia sends an alert: an email, a message in Slack or Discord, or a signed webhook to your own server or AI agent, with a picture of the moment. You can use it three ways, and they all do the same thing: - **The app.** Sign in at [playground.percia.ai](https://playground.percia.ai), add a camera, describe the goal, pick where the alert goes. - **The API, SDKs and CLI.** Everything the app does is an HTTP call. There are a JavaScript SDK, a Python SDK and a command line tool. - **An AI agent.** Connect Percia to Claude, ChatGPT, Cursor or any MCP client and ask in words. > **Tip**: Using a coding agent? Give it this page as Markdown: [/docs/index.md](/docs/index.md), or the whole docs in one file: [/docs/llms-full.txt](/docs/llms-full.txt). ![How Percia works: a camera or video, a goal you write in words, Percia watches, then an alert with a picture to email, Slack, Discord, a webhook or an AI agent](https://percia.ai/docs/img/how-it-works.svg) ## Start here - **[Quickstart](https://percia.ai/docs/quickstart.md)**: sign in, add a camera or a video file, create a watch, get an alert. About five minutes, with curl, JavaScript, Python and CLI tabs. - **[Concepts](https://percia.ai/docs/concepts.md)**: cameras, watches, events, keyframes and integrations in one page. - **[Cameras](https://percia.ai/docs/cameras.md)**: a phone or laptop, a camera link, a video file, or a camera on your home network through the bridge. - **[Events and webhooks](https://percia.ai/docs/webhooks.md)**: the alert body, how to verify the signature, retries. - **[API reference](https://percia.ai/docs/api.md)**: all 171 operations, by group. - **[SDKs and CLI](https://percia.ai/docs/sdks.md)**: install, sign in, examples. - **[Limits, pricing and credits](https://percia.ai/docs/limits.md)**: camera-minutes, the free minutes, the price, rate limits. ## What a watch looks like ```json { "sourceUrl": "percia-cam://3f9c2a10-...", "goal": "A person is standing at the front door", "notify": { "type": "webhook", "target": "https://example.com/hooks/percia" } } ``` and what your server gets when the goal becomes true: ```json { "id": "dec_01J...", "watchId": "w_abc", "type": "goal.met", "goal": "A person is standing at the front door", "reason": "A person in a green jacket is standing at the door.", "confidence": 0.93, "at": "2026-11-01T09:30:00Z", "eventId": "6f1c2a52-0d9e-5b43-9a1e-2f7d6c1b8e40" } ``` ## What Percia is not - It does not identify people by their face, and a goal that asks it to is refused. - It cannot read a camera on a private network directly. A small program, the [bridge](https://percia.ai/docs/cameras.md#cameras-on-a-private-network), runs on your network and pushes the camera to Percia. No router changes. - It is not a recorder you download from. You get keyframes and short clips of the events, kept for a limited time (see [Limits](https://percia.ai/docs/limits.md)). - A goal is about what a camera can see. Sound and feelings are not watched. --- # Quickstart > Add a video, create a watch, get an alert. Five minutes, with curl, JavaScript, Python and CLI. Page: https://percia.ai/docs/quickstart. Index of all docs pages: https://percia.ai/docs/llms.txt # Quickstart You will give Percia a video, tell it what to look for, and read the alert it sends. You need a Percia account and one short video file at a public https address (or a phone or laptop to use as a camera). > **Tip**: Using a coding agent? Paste this into it: `Read https://percia.ai/docs/quickstart.md and set up a Percia watch for me.` In the app the same three steps look like this. If you prefer clicks to code, you can stop here and use the app. ![The three steps in the Percia app: 1 add a camera, 2 describe the goal, 3 get an alert with a picture](https://percia.ai/docs/img/app-steps.svg) The rest of this page does the same with the API. ## 1. Sign in and make an API key 1. Sign in at [playground.percia.ai](https://playground.percia.ai) (email, Google, GitHub or Apple). Every account gets 10 free camera-minutes a month, no card. 2. Open the **API keys** page in the app, create a key with the scopes `watches:read`, `watches:write`, `events:read` and `cameras:write`, and copy it. It is shown once. Keys look like `pk_live_...`. ```bash export PERCIA_API_KEY=pk_live_... export BASE=https://playground.percia.ai/api curl -sS "$BASE/whoami" -H "Authorization: Bearer $PERCIA_API_KEY" ``` `whoami` answers with the account the key belongs to. A `401` means the key is wrong. > **Warning**: The key is a secret. Keep it in an environment variable, never in browser code or a repository. ## 2. Pick a source :::tabs ```bash Video file # Percia fetches a public https video (mp4, mov, webm or mkv) itself. curl -sS -X POST "$BASE/uploads/from-url" -H "Authorization: Bearer $PERCIA_API_KEY" \ -H 'content-type: application/json' \ -d '{"url":"https://example.com/clip.mp4"}' # -> {"uploadId":"...","source":"percia-file://", ...} ``` ```bash Phone or laptop # A device becomes a camera. Open pairUrl on it (single use, 10 minutes), allow the camera, press Start. curl -sS -X POST "$BASE/cameras" -H "Authorization: Bearer $PERCIA_API_KEY" \ -H 'content-type: application/json' -d '{"name":"Hall camera"}' # -> {"camera":{"id":"",...},"pairUrl":"https://.../cam/"} # the source is percia-cam:// ``` ```bash Camera link # A public rtsp://, rtsps://, http:// or https:// video address works as it is. # Nothing to create: use it as the source in step 3. ``` ::: Keep the value you get: `percia-file://`, `percia-cam://`, or your public link. That is the `sourceUrl`. A video file plays once and the watch ends when the video does. ## 3. Create a watch Leave `notify` out and the alert goes to your account email. To send it to your own server, add `"notify": {"type":"webhook","target":"https://..."}` (see [Events and webhooks](https://percia.ai/docs/webhooks.md)). :::tabs ```bash curl curl -sS -X POST "$BASE/watches/owned" -H "Authorization: Bearer $PERCIA_API_KEY" \ -H 'content-type: application/json' \ -d '{"sourceUrl":"percia-file://UPLOAD_ID","goal":"A person is walking in the frame"}' ``` ```js JavaScript // npm install @percia/sdk import { createClient } from "@percia/sdk"; const percia = createClient({ apiKey: process.env.PERCIA_API_KEY }); const watch = await percia.watches.create({ sourceUrl: "percia-file://UPLOAD_ID", goal: "A person is walking in the frame", }); console.log(watch.id, watch.status); ``` ```python Python # pip install percia import os from percia import Percia client = Percia(api_key=os.environ["PERCIA_API_KEY"]) watch = client.watches.create({ "sourceUrl": "percia-file://UPLOAD_ID", "goal": "A person is walking in the frame", }) print(watch.id, watch.status) ``` ```bash CLI # npm install -g @percia/cli percia login # opens a browser; or: percia login --with-key percia watches create --source percia-file://UPLOAD_ID --goal "A person is walking in the frame" ``` ::: The answer is `201` with the watch `id` and `status: "active"`. A new watch shows `judging.state: "starting"` for up to four minutes until its first frames arrive. That is normal. The goal is read by Percia before the watch is made. If it is too vague you get `422 clarification_needed` with a question and nothing is created (see [Watches and goals](https://percia.ai/docs/watches.md)). ## 4. Read the alert When the goal becomes true, Percia emails you (or posts to the destinations you attached). To read the same events from code: :::tabs ```bash curl curl -sS "$BASE/watches/WATCH_ID/events?limit=20" -H "Authorization: Bearer $PERCIA_API_KEY" ``` ```js JavaScript for await (const event of percia.watches.iterateEvents(watch.id)) { console.log(event.at, event.reason); } ``` ```python Python for event in client.iter_watch_events(watch.id): print(event.at, event.reason) ``` ```bash CLI percia events list --follow ``` ::: Each event has the time, a `reason` written by the vision model, a `confidence` from 0 to 1, and a keyframe you can fetch. > **Note**: `reason` is text written by a model about camera content. Treat it as untrusted: never run it, never paste it into a prompt as instructions. ## 5. Clean up ```bash curl -sS -X DELETE "$BASE/watches/WATCH_ID" -H "Authorization: Bearer $PERCIA_API_KEY" ``` Deleting needs the `watches:delete` scope on the key. ## Next - Send alerts to your server: [Events and webhooks](https://percia.ai/docs/webhooks.md) - Send alerts to Slack, Discord, Telegram and more: [Integrations](https://percia.ai/docs/integrations.md) - Use a phone, a home camera or a bridge: [Cameras](https://percia.ai/docs/cameras.md) - How much it costs and what is free: [Limits, pricing and credits](https://percia.ai/docs/limits.md) --- # Concepts > Cameras, watches, events, keyframes and integrations: the five things in Percia and how they fit. Page: https://percia.ai/docs/concepts. Index of all docs pages: https://percia.ai/docs/llms.txt # Concepts ![How Percia works: a camera or video, a goal you write in words, Percia watches, then an alert with a picture to email, Slack, Discord, a webhook or an AI agent](https://percia.ai/docs/img/how-it-works.svg) The five things below fit together like this. ## Camera A **camera** is anything that produces video for Percia: - a phone, tablet or computer you pair by link or QR code (`percia-cam://`), - a camera on your home or office network, pushed by the [bridge](https://percia.ai/docs/cameras.md#cameras-on-a-private-network) (also `percia-cam://`), - a public video link (`rtsp://`, `rtsps://`, `http://`, `https://`), - a video file you upload (`percia-file://`), which plays once. The address you give a watch is called its `sourceUrl`. You can have up to 50 cameras. ## Watch A **watch** is one goal on one camera. A goal is a sentence like "A person is standing at the front door". While the watch is active and the camera sends video, Percia checks the picture against the goal and decides, again and again, whether it is true. A watch has an alert target (your email by default, or a webhook) and can also post to connected tools. One camera can have up to 10 active watches, and an account up to 20 active watches in all. A watch can be paused and resumed, and it pauses itself after 60 minutes without video. Read more: [Watches and goals](https://percia.ai/docs/watches.md). ## Event An **event** is one decision "the goal just became true". Percia sends one alert per occurrence: while the goal stays true you are not alerted again. After it clears, the next time it becomes true is a new event. An event has a `reason` (written by a vision model), a `confidence`, the time, and a keyframe. Events are kept and can be listed with `GET /api/watches/{id}/events` or, across all watches, `GET /api/events`. ## Keyframe and evidence A **keyframe** is the still picture at the moment the goal was met. New watches keep keyframes by default (set `media: "off"` to store nothing). Keyframes are kept for 1, 3, 7, 14 or 30 days (3 days in the EU, EEA, UK and Switzerland, 7 elsewhere, unless you choose). Percia also cuts short clips for some alerts. Details are in [Limits](https://percia.ai/docs/limits.md#what-is-kept-and-for-how-long). ## Integration An **integration** (or *connection*) is a place alerts can go: Slack, Discord, Telegram, Home Assistant, IFTTT, Microsoft Teams, PagerDuty, SMS, WhatsApp or a webhook. A person connects each one once, and a *rule* says that a watch posts to it. Read more: [Integrations](https://percia.ai/docs/integrations.md). ## How a decision is made ![How a decision is made: a camera or video goes into Percia, which reads your goal once, splits it into conditions and judges the video; a match becomes an event with a keyframe picture that is delivered by email, webhook, Slack, Discord or to an AI agent](https://percia.ai/docs/img/decision-flow.svg "Percia reads your goal once, splits it into conditions, judges the video, and sends an event with a keyframe to your delivery targets.") Percia reads your goal once when the watch is created: is it something that *happens* ("a car pulls in") or something that *stays true* ("the gate is open"), what is the visible evidence, and what look-alikes to ignore. A broad goal ("the baby is in danger") is split into several concrete conditions. ## Accounts, keys and scopes Everything belongs to an account. The API takes a key (`pk_live_...`) or an OAuth token. A key has **scopes** (for example `watches:read`, `watches:write`, `events:read`); a call without the scope answers `403 insufficient_scope` naming it. Billing, API keys and adding a destination always need a person signed in: a key cannot do them. ## Billing in one line Percia charges for camera time: $0.50 per camera-hour, billed by the exact minute, with 10 free minutes every month. See [Limits, pricing and credits](https://percia.ai/docs/limits.md). --- # Cameras > Use a phone or laptop, a camera link, a video file, or a camera on your home network through the bridge. Page: https://percia.ai/docs/cameras. Index of all docs pages: https://percia.ai/docs/llms.txt # Cameras Pick the row that matches what you have. | You have | Use | Source address | |---|---|---| | A spare phone, tablet or laptop | [Pair it by link or QR](#phone-tablet-or-computer) | `percia-cam://` | | A camera with a public RTSP or https address | [Camera link](#camera-link) | the link itself | | A video file | [Upload](#video-files) | `percia-file://` | | A camera on your home or office network (ONVIF, RTSP, Frigate, Home Assistant, NVR) | [The bridge](#cameras-on-a-private-network) | `percia-cam://` | ## Phone, tablet or computer :::tabs ```bash curl # 1. Create the camera. pairUrl is single use and valid for 10 minutes. curl -sS -X POST "$BASE/cameras" -H "Authorization: Bearer $PERCIA_API_KEY" \ -H 'content-type: application/json' -d '{"name":"Hall camera"}' # {"camera":{...},"pairUrl":"https://.../cam/","pairExpiresAt":"..."} # 2. Open pairUrl on the device that will be the camera (copy the link or scan the QR code). # Allow the camera and press Start. The page shows "Percia is watching". # 3. Wait until status is "online". curl -sS "$BASE/cameras" -H "Authorization: Bearer $PERCIA_API_KEY" # 4. Watch it. curl -sS -X POST "$BASE/watches/owned" -H "Authorization: Bearer $PERCIA_API_KEY" \ -H 'content-type: application/json' \ -d '{"sourceUrl":"percia-cam://CAMERA_ID","goal":"A person is at the door"}' ``` ```js JavaScript const { camera, pairUrl } = await percia.cameras.create("Hall camera"); console.log("Open on the camera device:", pairUrl); // later, once it is online: await percia.watches.create({ sourceUrl: `percia-cam://${camera.id}`, goal: "A person is at the door" }); ``` ```python Python res = client.cameras.create("Hall camera") print("Open on the camera device:", res.pair_url) ``` ```bash CLI percia cameras add "Hall camera" # prints the link and a QR code percia watches create --source percia-cam://CAMERA_ID --goal "A person is at the door" ``` ::: - The device sends video only, no audio. Keep the screen on; on an iPhone the page must stay open. - A camera is `online` while its last sign of life is under 60 seconds old, otherwise `offline` (or `never` if it never connected). - A watch with no video for 60 minutes pauses itself and emails you. Resume it when the camera is back. - A new pairing link (`POST /api/cameras/{id}/pair`) cancels an unused older one. Deleting a camera that has watches answers `409 camera_in_use`. - Up to 50 cameras per account, camera links included (`429 camera_limit`). ## Camera link A public `rtsp://`, `rtsps://`, `http://` or `https://` video address works as the `sourceUrl` directly. It must be reachable from the internet: Percia refuses `localhost`, `192.168.x.x`, `10.x.x.x`, `172.16-31.x.x`, `169.254.x.x` and names ending in `.local` or `.internal`. If the address has a user name and password (`rtsp://user:pass@host/...`), Percia keeps them for judging only and removes them from every API answer and email. ## Video files A video file is useful to try Percia without a camera. It plays once and the watch ends (`pausedReason: "file_done"`). - **From a public https address:** `POST /api/uploads/from-url {"url":"https://example.com/clip.mp4"}`. Percia fetches the file itself (mp4, mov, webm or mkv, public https only) and answers `uploadId` and `source`. - **From a person's device:** `POST /api/uploads/link` returns `uploadUrl`, a page valid for 30 minutes where the person picks the file. Then `GET /api/uploads` and take the newest file with `status: "ready"`. - **In the app:** New watch, then Video file. Use the upload's `source` (`percia-file://`) as the watch's `sourceUrl`. Both API routes need the `cameras:write` scope and answer 404 while video files are switched off for your host. ## Cameras on a private network Percia never connects to a private address, and you should not open ports on your router. Instead the **Percia bridge** runs on an always-on computer in the same network as your cameras, reads each camera once, and pushes it to Percia over an outbound connection. The camera then appears in your Percia camera list and a watch uses `percia-cam://`. - Repository: [github.com/percia-ai/percia-bridge](https://github.com/percia-ai/percia-bridge) - Docker image: `ghcr.io/percia-ai/percia-bridge` - Finds ONVIF cameras, reads RTSP, Frigate and Home Assistant; there is a Home Assistant add-on. - Needs an API key with the scopes `cameras:read`, `cameras:write` and `watches:delete`. ### Build your own connector If you run an NVR or your own software, register a push camera and send video to it over WHIP: ```bash curl -sS -X POST "$BASE/cameras" -H "Authorization: Bearer $PERCIA_API_KEY" \ -H 'content-type: application/json' \ -d '{"name":"Garage","kind":"push","externalId":"nvr-7-cam-3"}' # 201 {"camera":{"id":"","kind":"push",...},"whipUrl":"https://.../cam//whip","token":"pc_..."} ``` - `token` is shown once and can publish to this one camera only. Registering the same `externalId` again returns the same camera with `token: null`. `POST /api/cameras/{id}/token` makes a new token. - Publish with ffmpeg 7.1 or newer (it needs the `whip` muxer), OBS 30 or newer (Service: WHIP, Server: the `whipUrl`, Bearer token: the token), or the CLI: `percia cameras push run --rtsp rtsp://user:pass@192.168.1.20/stream1`. - Always use the `whipUrl` Percia returns, never one you remember: Percia may move a camera to another relay, so ask for the address again each time you start publishing (`GET /api/cameras/{id}/status`). - `POST /api/cameras/bulk` registers up to 10 cameras at once. - **Send a heartbeat about every 20 seconds**: `curl -fsS -X POST -H "Authorization: Bearer $PERCIA_CAMERA_TOKEN" "$BASE/cam/heartbeat"` (answers 204; no body). Without it a push camera shows offline about 60 seconds after it connects, even while it keeps publishing, and starting a [Live](https://percia.ai/docs/live.md) session on it answers `409 camera_offline`. `percia cameras push run` does this for you. ```bash export PERCIA_CAMERA_TOKEN='pc_...' ffmpeg -rtsp_transport tcp -i rtsp://USER:PASS@LAN-CAMERA/stream -an -c:v copy \ -f whip -authorization "$PERCIA_CAMERA_TOKEN" "" ``` The camera needs to send H.264 without B-frames. If it does not, re-encode it to H.264 baseline, 720p, 10 fps with no B-frames and no audio, for example `ffmpeg ... -an -vf "scale=-2:'min(ih,720)',fps=10,format=yuv420p" -c:v libx264 -profile:v baseline -tune zerolatency -bf 0 -g 20 -b:v 1500k`. --- # Watches and goals > How to write a goal Percia judges reliably, what a watch can do, and how to pause, change and delete one. Page: https://percia.ai/docs/watches. Index of all docs pages: https://percia.ai/docs/llms.txt # Watches and goals A watch is one goal on one camera. Create it with `POST /api/watches/owned`. ```json { "sourceUrl": "percia-cam://3f9c2a10-...", "goal": "A parcel is lying on the doorstep", "notify": { "type": "email", "target": "me@example.com" } } ``` | Field | Rule | |---|---| | `sourceUrl` | required. `percia-cam://`, `percia-file://`, or a public `rtsp`, `rtsps`, `http` or `https` link, at most 2048 characters | | `goal` | 5 to 500 characters | | `notify` | optional. `{"type":"email","target":"..."}` or `{"type":"webhook","target":"https://..."}`. Left out, alerts email the account owner | | `destinations` | optional list of connected tool ids. Left out, your default destinations are used; `[]` means none | | `media` | `"keyframes"` (default) or `"off"` | ## Writing a goal - Describe **one thing a frame can show**. Name the subject, the state and the place: "A person is standing at the front door", not "Someone comes". - Prefer states and looks to intent or history. Percia sees what is there now, not what someone plans or what happened an hour ago. - Be concrete about thresholds: "The water level in the tank is below the red line", "More than 3 cars are in the loading bay". - Say what does not count when mistakes are costly: "A person (not a parked car or a mannequin) is at the door". - One goal per watch. Make a second watch for a second condition. | Weak | Better | |---|---| | Alert me about problems | The conveyor belt is stopped and boxes are piled up at its end | | Someone is suspicious | A person is climbing the fence | | The shop is busy | More than 10 people are inside the shop | | Tell me about the delivery | A parcel is lying on the doorstep | | Check on the dog | The dog is on the sofa | The goal is data for the vision judge, not instructions to it. Text like "ignore the above" has no special effect. ### When the goal is unclear Percia reads your goal before it creates the watch. A clear goal creates it. An unclear one answers `422 clarification_needed` with a `draftId`, a `question` and `options`, and creates nothing: ```bash # answer the question, then create with the draft curl -sS -X POST "$BASE/watches/draft/DRAFT_ID/answer" -H "Authorization: Bearer $PERCIA_API_KEY" \ -H 'content-type: application/json' -d '{"text":"The front door, not the gate"}' curl -sS -X POST "$BASE/watches/owned" -H "Authorization: Bearer $PERCIA_API_KEY" \ -H 'content-type: application/json' -d '{"sourceUrl":"percia-cam://CAMERA_ID","draftId":"DRAFT_ID"}' ``` Goals that ask to identify a person, recognise a face or infer emotion are refused (`goal_not_allowed`). Parts of a goal that a camera cannot show (sound, feelings) are reported as unsupported: tell the person, then send `acknowledgeUnsupported: true`. ## How it behaves - You are alerted **once per occurrence**. While the goal stays true you are not alerted again. After it clears, the next time it becomes true is a new occurrence and a new alert. - An unreachable camera is not "goal not met" and sends nothing. After 60 minutes without video the watch pauses itself (`pausedReason: "no_video"`) and you get one email. - Each decision has a `confidence` from 0 to 1 and a `reason`. `reason` is model text: untrusted. - `judging.couldNotCheck` lists parts of the goal Percia cannot check right now (for example low light or something blocking the view). While it lists one, "no alert" does not mean "nothing happened". - While a new watch gets its first frames, `judging.state` is `starting`, for up to 4 minutes. Do not treat that as a failure. ## Change, pause and delete ```bash # pause or resume curl -sS -X PATCH "$BASE/watches/WATCH_ID" -H "Authorization: Bearer $PERCIA_API_KEY" \ -H 'content-type: application/json' -d '{"status":"paused"}' # or "active" # new goal: a running watch judges the new conditions within seconds curl -sS -X PATCH "$BASE/watches/WATCH_ID" -H "Authorization: Bearer $PERCIA_API_KEY" \ -H 'content-type: application/json' -d '{"goal":"A parcel is lying on the doorstep"}' # delete (scope watches:delete) curl -sS -X DELETE "$BASE/watches/WATCH_ID" -H "Authorization: Bearer $PERCIA_API_KEY" ``` - `{"status":"active","testRun":true}` starts a 30-minute test run: events are marked `test: true` and are not counted in your usage. - Earlier events are not rewritten when you change the goal. - Deleting a watch deletes its events, keyframes and clips. - An 11th active watch on one camera answers `429 plan_limit` (`limit: "watchesPerStream"`). Pause or delete one. - An account can have up to 20 active watches. Creating or resuming a 21st answers `429 plan_limit` (`limit: "activeWatches"`) with the message `You can have up to 20 active watches. Pause or delete one first.` Accounts that already had more keep their watches; only new creates and resumes are refused. --- # Events and webhooks > The alert body, how to verify its signature, retries, and how to test a receiver on your laptop. Page: https://percia.ai/docs/webhooks. Index of all docs pages: https://percia.ai/docs/llms.txt # Events and webhooks When a goal becomes true Percia records an **event**. For a watch with a webhook target it also sends one `POST` to your `https` address. This page is the whole contract. ![Signed webhook flow: Percia sends a signed POST to your server, your server verifies the signature and answers 2xx, otherwise Percia retries](https://percia.ai/docs/img/webhook-flow.svg) ## 1. Create a webhook watch :::tabs ```bash curl curl -sS -X POST "$BASE/watches/owned" -H "Authorization: Bearer $PERCIA_API_KEY" \ -H 'content-type: application/json' \ -d '{"sourceUrl":"percia-cam://CAMERA_ID","goal":"A person is standing at the front door","notify":{"type":"webhook","target":"https://example.com/hooks/percia"}}' # 201 {"id":"...","status":"active","webhookSecret":"whsec_...", ...} ``` ```js JavaScript const watch = await percia.watches.create({ sourceUrl: "percia-cam://CAMERA_ID", goal: "A person is standing at the front door", notify: { type: "webhook", target: "https://example.com/hooks/percia" }, }); console.log(watch.webhookSecret); // shown once: store it ``` ```python Python watch = client.watches.create({ "sourceUrl": "percia-cam://CAMERA_ID", "goal": "A person is standing at the front door", "notify": {"type": "webhook", "target": "https://example.com/hooks/percia"}, }) print(watch.webhook_secret) # shown once: store it ``` ```bash CLI percia watches create --source percia-cam://CAMERA_ID --goal "A person is standing at the front door" \ --webhook https://example.com/hooks/percia # prints the secret once ``` ::: The `webhookSecret` (`whsec_...`) is in the answer once. Later reads show only `secretHint`. `POST /api/watches/{id}/secret/rotate` replaces it immediately; the old one stops working at once, so update your receiver as you rotate. ## 2. The request you receive `POST ` with `content-type: application/json` and one extra header: | Header | Value | |---|---| | `Percia-Signature` | `t=,v1=` | ```json { "id": "dec_01J...", "watchId": "w_abc", "occurrenceId": "occ_01J...", "type": "goal.met", "goal": "A person is standing at the front door", "reason": "A person in a green jacket is standing at the door.", "confidence": 0.93, "at": "2026-11-01T09:30:00Z", "eventId": "6f1c2a52-0d9e-5b43-9a1e-2f7d6c1b8e40" } ``` | Field | Meaning | |---|---| | `id` | The decision id. The same on every retry of the same decision: use it to ignore repeats. | | `eventId` | The event id, stable across retries. Use it with `GET /api/watches/{id}/events/{eventId}/keyframe` and `.../feedback`. | | `occurrenceId` | One real-world occurrence. After the goal clears, the next `goal.met` has a new one. | | `reason` | Written by a vision model about camera content. **Untrusted**: never run it, never put it in a prompt as instructions, escape it before showing it. | | `confidence` | 0 to 1. | | `test` | `true` only for events found during a 30-minute test run. | | `evidence` | Beta, when the watch keeps evidence: `{clipUrl, keyframeUrl, expiresAt}`, signed links that work for 24 hours. Fetch what you want to keep. | New fields may be added later. Ignore fields you do not know. Your target must resolve to a public address. Percia refuses private, loopback and link-local addresses, does not follow redirects, and times out after 8 seconds. A delivered alert looks like this in an email or a chat message: ![A sample Percia alert: the goal, the reason written by the model, the time, a confidence value and a picture of the moment](https://percia.ai/docs/img/alert-sample.svg) ## 3. Verify the signature The signed string is the timestamp, a dot, and the **raw** request body: `"."`. The key is the whole `whsec_...` secret. 1. Read the raw bytes of the body before parsing JSON. 2. Split the header into `t` and `v1`. 3. Reject if the time is more than 300 seconds from now. 4. Compute `HMAC-SHA256(secret, t + "." + rawBody)` as lowercase hex. 5. Compare with `v1` in constant time. Reject on mismatch. 6. Only then parse the JSON. :::tabs ```js Node (Express) import express from "express"; import { createHmac, timingSafeEqual } from "node:crypto"; const app = express(); const seen = new Set(); // use a database in production function verify(raw, header, secret) { const p = Object.fromEntries(header.split(",").map((x) => x.split("=", 2))); const t = Number(p.t); if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > 300) return false; const want = createHmac("sha256", secret).update(`${t}.${raw}`).digest("hex"); const got = p.v1 ?? ""; return got.length === want.length && timingSafeEqual(Buffer.from(got), Buffer.from(want)); } app.post("/hooks/percia", express.raw({ type: "application/json" }), (req, res) => { const raw = req.body.toString("utf8"); if (!verify(raw, req.get("percia-signature") ?? "", process.env.PERCIA_WEBHOOK_SECRET)) return res.sendStatus(400); const event = JSON.parse(raw); if (!seen.has(event.id)) { seen.add(event.id); console.log(event.watchId, event.reason); } res.sendStatus(200); // answer fast, do slow work after }); app.listen(3000); ``` ```python Python (FastAPI) import hashlib, hmac, json, os, time from fastapi import FastAPI, Request, Response app = FastAPI() seen: set[str] = set() # use a database in production def verify(raw: bytes, header: str, secret: str) -> bool: try: parts = dict(p.split("=", 1) for p in header.split(",")) t = int(parts["t"]) except (KeyError, ValueError): return False if abs(time.time() - t) > 300: return False want = hmac.new(secret.encode(), f"{t}.".encode() + raw, hashlib.sha256).hexdigest() return hmac.compare_digest(parts.get("v1", ""), want) @app.post("/hooks/percia") async def hook(request: Request): raw = await request.body() if not verify(raw, request.headers.get("percia-signature", ""), os.environ["PERCIA_WEBHOOK_SECRET"]): return Response(status_code=400) event = json.loads(raw) if event["id"] not in seen: seen.add(event["id"]) print(event["watchId"], event["reason"]) return Response(status_code=200) ``` ```js JavaScript SDK import { verifyWebhookSignature } from "@percia/sdk"; // rawBody: the exact bytes you received. It returns a Promise. const ok = await verifyWebhookSignature(rawBody, req.headers, process.env.PERCIA_WEBHOOK_SECRET); if (!ok) return res.sendStatus(400); ``` ```python Python SDK from percia import verify_webhook_signature # raw_body: the exact bytes you received. It returns a bool. if not verify_webhook_signature(raw_body, request.headers, os.environ["PERCIA_WEBHOOK_SECRET"]): return Response(status_code=400) ``` ::: > **Warning**: Never put the secret in browser code or a repository. Do the duplicate check and the side effect in one database transaction. Ready-made receivers for Express, Cloudflare Workers, FastAPI, Go and Ruby, with shared test vectors, are in [percia-sdks/examples](https://github.com/percia-ai/percia-sdks/tree/main/examples). ## 4. Test it **Send a signed test event, no camera needed:** ```bash curl -sS -X POST "$BASE/watches/WATCH_ID/test-delivery" -H "Authorization: Bearer $PERCIA_API_KEY" ``` Percia sends a signed `goal.test` event to your target and reports what your server answered. **Test on your laptop with no public URL.** Webhooks need a public https address. While you build, read your events from a stream and let the CLI forward them to localhost, signed with your watch's secret exactly like a real delivery: ```bash export PERCIA_WEBHOOK_SECRET=whsec_... percia listen --forward-to http://localhost:3000/hooks/percia ``` Or just print them: `percia listen --print --type goal.met`. The stream is for development: it has no retries, ends after 10 minutes (the CLI reconnects), and allows 2 streams per account. Production uses a webhook. ## 5. Retries and failures Answer with any `2xx` to acknowledge. A non-2xx answer, a timeout or a connection error is a failed attempt. Percia retries after about 2 seconds, then 8 seconds, then every 15 minutes, up to 5 attempts. Deliveries are **at least once**, so deduplicate on `id`. After the last attempt the event is marked `deliveryStatus: "failed"` and the watch shows "needs attention". A failed delivery never stops the watch. Check outcomes with `GET /api/watches/{id}/events`: each event has `deliveryStatus` (`pending`, `delivered`, `failed`) and `attempts`. ## Read events without a webhook - `GET /api/watches/{id}/events?limit=50`: newest first. Pass `nextCursor` back as `cursor`. - `GET /api/events`: across all your watches, with filters `watchId`, `type`, `since`. - `GET /api/watches/{id}/events/{eventId}/keyframe`: the picture (JPEG). ## Connect Zapier, Make or n8n Automation platforms use REST hooks (`POST /api/hooks`, scope `hooks:write`) that receive the same signed events. The Percia app for Zapier is not published yet: until it is, use the platform's webhook or HTTP step with a webhook watch. The hook routes are in the [API reference](https://percia.ai/docs/api.md#hooks). --- # Integrations > Send alerts to Slack, Discord, Telegram, Home Assistant and other tools, and how connections and rules work. Page: https://percia.ai/docs/integrations. Index of all docs pages: https://percia.ai/docs/llms.txt # Integrations An alert always goes to the watch's own target (your email, or a signed webhook). On top of that a watch can post to **connected tools**. Supported services: Slack, Discord, Telegram, Home Assistant, IFTTT, Microsoft Teams, PagerDuty, SMS, WhatsApp and a custom webhook. Which of them you can connect depends on what is switched on for your account: ask the API. ```bash curl -sS "$BASE/integrations/services" -H "Authorization: Bearer $PERCIA_API_KEY" # one entry per service, with "available": true or false ``` ## Connect a tool (a person does this) Only a person can approve a new destination: an API key can never finish a connection. 1. In the app open **Integrations**, pick the service and follow the steps. Slack and Discord ask you to approve and pick a channel; Telegram opens the Percia bot; Home Assistant and webhooks ask for a URL; IFTTT asks for a key and an event name; SMS and WhatsApp ask for a number. 2. Or from code: `POST /api/integrations/connect {"service":"slack"}` returns a `connectUrl` (single use, 15 minutes). Give it to the person and wait for them to finish. Do not poll. 3. Press **Send test** on the connection (`POST /api/integrations/{id}/test`). It sends one message labelled "Percia test: ignore" and records nothing. To connect one, open Integrations in the [app](https://playground.percia.ai) and choose the service. ## Attach it to a watch A **rule** says that a watch posts to a connection. ```bash # send every event of this watch to a connection curl -sS -X PUT "$BASE/watches/WATCH_ID/integrations" -H "Authorization: Bearer $PERCIA_API_KEY" \ -H 'content-type: application/json' \ -d '{"rules":[{"connectionId":"CONNECTION_ID","on":"*"}]}' ``` `PUT` replaces all of a watch's rules, so read them first (`GET /api/watches/{id}/integrations`) and keep the ones that should stay. **Default destinations.** Mark a connection as a default (`PATCH /api/integrations/{id} {"default":true}`, or the tick box in the app) and Percia attaches it to every new watch you create. `POST /api/watches/owned` takes `destinations`: left out means your defaults, `[]` means none, a list of ids means exactly those. ## Good to know - A watch can have up to 5 rules and an account up to 20 connections. Delivery to connections is limited to 120 attempts an hour. - Alerts from a connection carry a signed picture link (`imageUrl`) when the event has a keyframe. Anyone with the link can open the image, so treat alert channels as private. - Links in the model's `reason` text are replaced by `[link removed]` when an alert goes to a connection. - If the service says the destination is gone (the Slack app was removed, the Telegram bot was blocked, a webhook answered 410) the connection becomes `broken`: Percia stops sending there, emails the owner once, and events keep being recorded. Connect the same destination again and the rules move over by themselves. - A `webhook` connection is signed like a watch webhook, with its own secret shown once. Home Assistant deliveries are not signed: the URL is the secret. --- # Use Percia from AI agents > Connect Claude, ChatGPT, Cursor or any MCP client to Percia, or give a coding agent the docs. Page: https://percia.ai/docs/agents. Index of all docs pages: https://percia.ai/docs/llms.txt # Use Percia from AI agents Percia is built so an agent can set up a watch end to end. There are three ways in. ![AI agents such as Claude, ChatGPT and Cursor connect through MCP to Percia, which watches your cameras](https://percia.ai/docs/img/mcp-connect.svg) ## Every address | Address | What it is | Sign-in | |---|---|---| | `https://playground.percia.ai/api` | REST API; schemas at `/api/openapi.json` | `pk_live_` key or OAuth | | `https://playground.percia.ai/mcp` | Code mode, your account: tools `search`, `execute`, `docs`, `whoami`, `view_image`, `show_link` | API key or OAuth | | `https://playground.percia.ai/mcp/directory` | The directory edition (Claude): separate `read`, `write` and `delete` tools | OAuth | | `https://playground.percia.ai/mcp/chatgpt` | The ChatGPT edition: 19 named tools, one per action | OAuth | | `https://playground.percia.ai/mcp/docs` | Docs only: `search_docs`, `get_page` | none | | [`/llms.txt`](https://percia.ai/docs/llms.txt), [`/llms-full.txt`](https://percia.ai/docs/llms-full.txt) | This documentation as text and Markdown | none | Which one: a coding agent (Claude Code, Cursor) or your own agent uses `/mcp`. A person adding Percia to Claude.ai uses `/mcp` as a custom connector. An app that needs fixed, named tools uses `/mcp/chatgpt`. Docs only: `/mcp/docs`. Everything an MCP tool does is also a REST route, with the same permissions. ## Connect your agent Create an API key in the app under Settings > API keys and give it only the permissions the job needs (the scopes). Put it in `PERCIA_API_KEY`; never paste it into a repository. Without a key, every client below can sign in with OAuth instead. ### Claude Code ```bash claude mcp add --transport http percia https://playground.percia.ai/mcp --header "Authorization: Bearer $PERCIA_API_KEY" ``` Without a key, sign in with OAuth instead. Run this, then `/mcp` inside Claude Code and choose Authenticate: ```bash claude mcp add --transport http percia https://playground.percia.ai/mcp ``` ### Claude.ai Settings > Connectors > Add custom connector. Name it Percia and use this URL. You sign in and choose what to allow: ```text https://playground.percia.ai/mcp ``` ### Cursor Add this to `.cursor/mcp.json` (project) or `~/.cursor/mcp.json` (all projects): ```json { "mcpServers": { "percia": { "url": "https://playground.percia.ai/mcp", "headers": { "Authorization": "Bearer ${env:PERCIA_API_KEY}" } } } } ``` ### ChatGPT Use the ChatGPT edition, `https://playground.percia.ai/mcp/chatgpt`. Add it as an MCP server or connector in ChatGPT and sign in. ### Any other MCP client Add the MCP URL `https://playground.percia.ai/mcp` and sign in. The CLI can also write the config for some clients: `percia mcp setup claude-code` (or `cursor`, `claude-desktop`). ### Docs only (no key) ```bash claude mcp add --transport http percia-docs https://playground.percia.ai/mcp/docs ``` Cursor and Claude.ai take the same URL. It also offers the task skills as `skill:///SKILL.md` resources. ![Connecting an AI agent: 1 add the Percia MCP server in the client, 2 approve access in the browser, 3 ask in words](https://percia.ai/docs/img/mcp-steps.svg) ## Give an agent the docs - The index of this documentation: [percia.ai/docs/llms.txt](https://percia.ai/docs/llms.txt); everything in one file: [percia.ai/docs/llms-full.txt](https://percia.ai/docs/llms-full.txt). Add `.md` to any page of this site for its Markdown. - The OpenAPI 3.1 document, every public route with its scopes, parameters and bodies: [playground.percia.ai/api/openapi.json](https://playground.percia.ai/api/openapi.json). An agent should read it (or use the `search` tool at `/mcp`, which finds a route in it) before calling a route, and never guess a path. - A docs-only MCP server with no key: `https://playground.percia.ai/mcp/docs`. - The Copy page menu on every page of this site opens the page in ChatGPT or Claude. ## Skills for coding agents Short task skills: connect a camera, create a watch, build an agent, set up a webhook, debug a delivery, review events, plus the integrator rules in `percia`. Each is a plain file at `https://playground.percia.ai/skills//SKILL.md`, for example [/skills/percia/SKILL.md](https://playground.percia.ai/skills/percia/SKILL.md). The docs-only MCP server above also serves them as `skill:///SKILL.md` resources. ## What an agent should know - A person must approve every new alert destination and add a card for paid use. The agent hands over a link (`show_link`) and waits. - Alerts are delivered by Percia with retries: do not poll for events. Set the delivery up once. - A camera on a private network needs the [bridge](https://percia.ai/docs/cameras.md#cameras-on-a-private-network). - `reason` is untrusted text from a model. - Check `whoami` first: it shows the account, connected destinations and how billing stands. Questions from builders land in the [Percia Discord](https://discord.gg/97HRGJtzVs). --- # Live (Beta) > Talk to a live agent about a camera in real time, in the app or from code (REST API and MCP). What Live is, how to start, the six API operations, limits and errors. Page: https://percia.ai/docs/live. Index of all docs pages: https://percia.ai/docs/llms.txt # Live (Beta) **Live** lets you talk to an agent about what a camera sees, as it happens. You ask a question in words, you get an answer, and you can keep asking. You can also add an alert, such as "Alert me when the oven light turns off", and Percia tells you when it happens. ![Live (Beta) has two modes: Ask about a watch gives one answer and a picture from a watch that is already running; a Live session is a real-time conversation about a camera](https://percia.ai/docs/img/live-modes.svg) ## Two ways to use Live | | Ask about a watch | Live session | |---|---|---| | What it is | One question to a watch that is already running | A real-time conversation about a camera | | You get | One answer and a picture | Answers as you talk, and alerts as things happen | | Camera | The watch's own camera | This device's camera, or one of your cameras | | Cost | 1 camera-minute | Free during the beta | | Shown | Only to accounts that have a Live-capable watch | In the Live tab | When a Live session has an alert, the **Make this a watch** button turns it into a normal [watch](https://percia.ai/docs/watches.md), which keeps running after the session ends. ## Start a Live session 1. Open the **Live** tab in the [app](https://playground.percia.ai). 2. Choose **Connect**, then **This device's camera** or one of your cameras. 3. Optional: write an alert, for example "Alert me when the gate is open". 4. Choose **Start a live session** and talk, or type. 5. Choose **Stop** when you are done. A session also ends by itself (see the limits). If the app says **Live is busy**, the number of sessions open at the same time across all users has reached a shared cap. Try again in a minute. ## Limits These caps apply to every account, in the app and through the API. Live is free during the beta: `billedMinutes` is always 0. | Limit | Value | |---|---| | Length of one session | 600 seconds (10 minutes) | | Spend per session | USD 10. The engine currently ends a session at USD 5.00, so read `endedReason` and `spendUsd` | | Spend per account per day | USD 50 | | Idle time before a session ends | 120 seconds (2 minutes) without a question or a poll of the events | | Open sessions per account | 5 | | Open sessions across all users | 20 (more answers `live_busy`, try again in a minute) | ## Use Live from code You can start and drive a Live session from the REST API or from an AI agent over MCP. A session on a camera is one conversation: start it, ask questions, read answers and alerts, stop it. The session is time-boxed (see the limits) and nothing keeps running after it ends. ### What you need - **A key or a login.** An [API key](https://percia.ai/docs/quickstart.md) with the scopes `watches:write` (start, ask, stop) and `watches:read` (read sessions and events), or the MCP login. A key with only `cameras:read` cannot call these operations. - **A camera of yours that is online.** These work: a paired phone or laptop, a push camera (for example one the [bridge](https://percia.ai/docs/cameras.md) pushes), and a link camera. The camera must be sending video, or the start answers `camera_offline`. See [Cameras](https://percia.ai/docs/cameras.md) for how to create one. You need the camera's id (`GET /cameras`). - **Not available through the API:** "This device's camera" (browser frames) and the "Ask about a watch" source stay in the app. A start on anything but a camera answers `invalid_request`. ### Walk-through with curl The flow is: start, ask until you get an answer, read the events, stop. ```bash export PERCIA_API_KEY=pk_live_... export BASE=https://playground.percia.ai/api AUTH="Authorization: Bearer $PERCIA_API_KEY" # 1. Find your camera id curl -sS "$BASE/cameras" -H "$AUTH" # 2. Start a session. alertWhen is optional: "tell me when ..." curl -sS -X POST "$BASE/live/sessions" -H "$AUTH" -H 'content-type: application/json' \ -d '{"source":{"cameraId":""},"alertWhen":"a person is at the front door"}' # -> 201 {"sessionId":"ls_...","status":"open","caps":{...},"capabilities":[...],"alertClips":true,"startedAt":"..."} export SID=ls_... # the sessionId # 3. Ask until you get a 200. The session needs 10 to 15 seconds to start: until then the ask # answers 503 live_starting or 503 live_unavailable (no frame yet). Wait 4 seconds and ask again. for i in $(seq 1 15); do CODE=$(curl -sS -o ask.json -w '%{http_code}' -X POST "$BASE/live/sessions/$SID/ask" \ -H "$AUTH" -H 'content-type: application/json' -d '{"question":"What is on the table?"}') [ "$CODE" = 200 ] && break echo "ask answered $CODE, retrying in 4 s"; sleep 4 done cat ask.json # -> {"answer":"...","keyframeId":"...","keyframeUrl":"https://...","costUsd":0.001} # 4. Read what happened: answers, alerts, the end. Pass the last seq you saw as after. curl -sS "$BASE/live/sessions/$SID/events?after=0" -H "$AUTH" # -> {"events":[{"seq":1,"type":"live.answer","at":"...","text":"..."}, ...]} curl -sS "$BASE/live/sessions/$SID/events?after=1" -H "$AUTH" # 5. Stop it. Safe to repeat. Always stop a session you are done with: it frees an open-session slot. curl -sS -X POST "$BASE/live/sessions/$SID/stop" -H "$AUTH" # -> {"ended":true,"billedMinutes":0,"spendUsd":0.002} ``` The response bodies above show the field names from the API; the values are examples. **Do not wait for the session to be "running".** `GET /live/sessions/{id}` reports `status: "open"` for the whole life of a session and never changes to `running`, so polling it tells you nothing about readiness. Call `ask` and retry on `503` instead. In real runs the first try answered `503 live_starting` after 1 second, then `503 live_unavailable` (no frame yet) at about 7 seconds, and the first `200` came 12 to 15 seconds after the start, with 3 to 4 seconds of latency per answer. An ask costs about USD 0.001, and `stop` returns the session's `spendUsd` and `billedMinutes` (0 during the beta). **Keep the session alive.** A session with no ask and no poll of the events ends after about 120 seconds with `endedReason: "idle"`. `GET /live/sessions/{id}` does **not** count as activity. An ask does, and so does polling `GET /live/sessions/{id}/events`, so a client that keeps polling the events keeps the session open until the duration or spend cap. A small loop in JavaScript (Node 18 or later) that starts, retries the ask, reads the events and stops: ```javascript const base = "https://playground.percia.ai/api"; const h = { authorization: `Bearer ${process.env.PERCIA_API_KEY}`, "content-type": "application/json" }; const sleep = ms => new Promise(r => setTimeout(r, ms)); const start = await fetch(`${base}/live/sessions`, { method: "POST", headers: h, body: JSON.stringify({ source: { cameraId: process.env.CAMERA_ID }, alertWhen: "a person is at the door" }), }).then(r => r.json()); const id = start.sessionId; // Ask until it answers 200 (503 live_starting / live_unavailable while it starts) let answer; for (let i = 0; i < 15 && !answer; i++) { const r = await fetch(`${base}/live/sessions/${id}/ask`, { method: "POST", headers: h, body: JSON.stringify({ question: "What is on the table?" }) }); if (r.status === 200) answer = await r.json(); else if (r.status === 503) await sleep(4000); else throw new Error(`ask failed: ${r.status} ${await r.text()}`); } console.log(answer?.answer, answer?.keyframeUrl); // Read the events (this also keeps the session open), then stop let after = 0; for (let i = 0; i < 10; i++) { const { events } = await fetch(`${base}/live/sessions/${id}/events?after=${after}`, { headers: h }).then(r => r.json()); for (const e of events) { after = e.seq; console.log(e.type, e.text ?? ""); } await sleep(2000); } await fetch(`${base}/live/sessions/${id}/stop`, { method: "POST", headers: h }); ``` ### Troubleshooting | You see | What it means | What to do | |---|---|---| | `409 camera_offline` on start | The camera is not online. A phone or laptop camera must have its page open and sending. A push camera must also send a heartbeat (see below) | Bring the camera online, check `GET /cameras` shows `online`, start again | | `503 live_starting` on ask | The session is still starting ("Live is still starting") | Ask again in 4 to 5 seconds. Normal for the first 12 to 15 seconds | | `503 live_unavailable` on ask, "no frame yet" | The session is up but has not received a frame from the camera yet | Ask again in 4 to 5 seconds. If it lasts more than a minute, check the camera is sending video | | `429 live_busy` | Every Live slot across all users is taken | Wait for `Retry-After` (about a minute) and start again | | Session ended with `endedReason: "idle"` | 120 seconds without an ask or a poll of the events | Start a new session. Poll `GET /live/sessions/{id}/events`, or ask; do not rely on `GET /live/sessions/{id}` | | `409 session_ended` on ask | The session is over | Read `endedReason` from `GET /live/sessions/{id}`, then start a new one | ### Push cameras need a heartbeat A push camera (a connector or your own software that publishes video to a camera you created with `kind: "push"`, see [Cameras](https://percia.ai/docs/cameras.md#cameras-on-a-private-network)) shows **offline about 60 seconds** after it connects, even while it keeps publishing. A start on an offline camera answers `409 camera_offline`. A connector must call this roughly **every 20 seconds** with the camera's own token (`pc_...`, the `token` returned when the camera was created): ```bash curl -fsS -X POST "https://playground.percia.ai/api/cam/heartbeat" \ -H "Authorization: Bearer $PERCIA_CAMERA_TOKEN" # -> 204 No Content (no body to send). 401 means the token is wrong. ``` The CLI's `percia cameras push run` sends it every 20 seconds for you, and paired phone and laptop cameras in the app send it automatically. If you wrote your own connector, add it (see [Build your own connector](https://percia.ai/docs/cameras.md#build-your-own-connector)). ### With the SDKs SDK and CLI 0.5.0 and later have the six Live operations. Install them: ```bash npm i @percia/sdk # JavaScript and TypeScript (CLI: npm i -g @percia/cli) pip install percia # Python 3.9+ ``` The operations are `startLiveSession`, `getLiveSession`, `listLiveSessions`, `listLiveSessionEvents`, `askLiveSession` and `stopLiveSession`. In JavaScript they are on `percia.api` and return `{ data, error, response }` without throwing; in Python they are in `percia._generated.api.live` and are called through the client, which raises a typed error on a non-2xx answer. :::tabs ```ts TypeScript import { createClient } from "@percia/sdk"; const percia = createClient({ apiKey: process.env.PERCIA_API_KEY }); const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); const started = await percia.api.startLiveSession({ body: { source: { cameraId: process.env.CAMERA_ID! }, alertWhen: "a person is at the door" }, }); if (!started.data) throw new Error(`start failed: ${started.response.status}`); const id = started.data.sessionId!; try { // 503 live_starting / live_unavailable while it starts: retry every 4 s for (let i = 0; i < 15; i++) { const r = await percia.api.askLiveSession({ path: { id }, body: { question: "What is on the table?" } }); if (r.data) { console.log(r.data.answer, r.data.keyframeUrl); break; } if (r.response.status !== 503) throw new Error(`ask failed: ${r.response.status}`); await sleep(4000); } } finally { const stopped = await percia.api.stopLiveSession({ path: { id } }); console.log(stopped.data); // example: { ended: true, billedMinutes: 0, spendUsd: 0.002 } } ``` ```python Python import os, time from percia import Percia, APIError from percia._generated.api.live import start_live_session, ask_live_session, stop_live_session from percia._generated.models.start_live_session_body import StartLiveSessionBody from percia._generated.models.start_live_session_body_source import StartLiveSessionBodySource from percia._generated.models.ask_live_session_body import AskLiveSessionBody client = Percia(api_key=os.environ["PERCIA_API_KEY"]) body = StartLiveSessionBody( source=StartLiveSessionBodySource(camera_id=os.environ["CAMERA_ID"]), alert_when="a person is at the door", ) session = client._call(start_live_session, body=body) sid = session.session_id try: for _ in range(15): try: r = client._call(ask_live_session, id=sid, body=AskLiveSessionBody(question="What is on the table?")) print(r.answer, r.keyframe_url) break except APIError as e: if e.status != 503: # 503 live_starting / live_unavailable: wait and ask again raise time.sleep(4) finally: stopped = client._call(stop_live_session, id=sid) print(stopped.spend_usd, stopped.billed_minutes) # example: 0.002 0 ``` ::: The response values in the comments are examples. The Python call goes through the generated module, so it uses the client's private `_call`; `client.request("POST", f"/live/sessions/{sid}/ask", json={...})` is the public escape hatch for the same route. ### The six operations | Method and path | operationId | Scope | What it does | |---|---|---|---| | `POST /live/sessions` | `startLiveSession` | `watches:write` | Start a session on one of your cameras. Body `{source: {cameraId}, alertWhen?}`. Answers 201 with `sessionId`, `status`, `caps`, `capabilities`, `alertClips`, `startedAt` | | `GET /live/sessions` | `listLiveSessions` | `watches:read` | Your recent sessions, newest first: `{sessions: [...]}` | | `GET /live/sessions/{id}` | `getLiveSession` | `watches:read` | One session: `status` (`open` or `ended`; never `running`; not counted as activity), `endedReason`, `secondsOpen`, `spendUsd`, `billedMinutes`, `caps`, `alerts` | | `GET /live/sessions/{id}/events` | `listLiveSessionEvents` | `watches:read` | Events after `after` (0 or absent = from the start): `live.answer`, `live.item`, `live.alert`, `live.budget_warning`, `live.ended`. Poll every 2 seconds; counts as activity | | `POST /live/sessions/{id}/ask` | `askLiveSession` | `watches:write` | Ask a question (`question`, 1 to 500 characters). Answers `{answer, keyframeId, keyframeUrl, costUsd}` | | `POST /live/sessions/{id}/stop` | `stopLiveSession` | `watches:write` | Stop now. Answers `{ended, billedMinutes, spendUsd}` | Event fields: `seq` (pass the last one as `after`), `type`, `at`, `text` (the answer, the alert text, or why it ended), `conditionId`, `keyframeUrl` (a picture, JPEG) and `clipUrl` (a 4 second MP4 clip on an alert). Both links are signed, valid for ten minutes, and need no credential. A session ends with `endedReason` `max_duration`, `max_spend`, `idle`, `user`, `start_failed` or `unavailable`. After the end, the events answer one `live.ended`. A session of another account answers `404 not_found`. Reads still work while Live is switched off. ### Errors Every error has the usual body (`error.code`, `error.message`; see [Errors](https://percia.ai/docs/errors.md)). | Status | Code | When | |---|---|---| | 400 | `invalid_request` | No `source.cameraId`, a source other than a camera, or a question that is not 1 to 500 characters | | 401 | | No key, or a key that is not valid | | 403 | `insufficient_scope` | The key lacks `watches:write` or `watches:read` | | 404 | `not_found` | No such session of yours | | 404 | `camera_not_found` | The camera is not one of yours | | 409 | `camera_offline` | The camera is not online. A push camera shows offline about 60 s after it connects unless it sends [heartbeats](#push-cameras-need-a-heartbeat) every 20 s | | 409 | `session_ended` | You asked in a session that is over (`endedReason` says why). Start a new one | | 429 | `live_limit` | `which`: `open_sessions` (5 open), `daily_spend` (USD 50 a day) or, on an ask, `session_spend` | | 429 | `live_busy` | Every Live slot across all users is taken. Try again in a minute (`Retry-After`) | | 503 | `live_starting` | The session is still starting ("Live is still starting"). Ask again every 4 to 5 seconds; the first answer comes after 12 to 15 s | | 503 | `live_disabled` | Live is switched off for now: start and ask are refused. Reads and stop still work | | 503 | `live_unavailable` | No frame from the camera yet (ask again in 4 to 5 s), not available on your engine line, or the engine did not start | ## How Live differs from a watch A [watch](https://percia.ai/docs/watches.md) runs continuously, on its own, and alerts you (email, webhook, Slack, ...) when its goal is met. It is billed by the camera-minute. A Live session is an interactive, time-boxed conversation: you ask, it answers from what the camera sees now, and it can alert you while the session is open. It ends by itself after at most 10 minutes. To keep an alert running after the session, make it a watch (**Make this a watch** in the app, or `POST /watches/owned`). Inside Live, **Ask about a watch** is one question to a watch that is already running (one answer and a picture, app only), and a **Live session** is the real-time conversation on a camera that the API starts. ## Use Live from an AI agent (MCP) In the full MCP, `https://playground.percia.ai/mcp`, the agent finds the Live operations by searching the API with its `search` tool (try "live session") and calls them with `execute`. You do not need to reconnect. If an agent that was already connected does not see them, start a new chat. Live is not in the Claude directory edition (`/mcp/directory`) or the ChatGPT edition (`/mcp/chatgpt`) yet. See [AI agents](https://percia.ai/docs/agents.md) for setup. A prompt that works: "Start a Live session on my front-door camera, ask what is by the door, tell me when a person arrives, and stop the session when I say so." ## Privacy During a session, frames and clips from the camera go to Google's Gemini API to be understood. They are kept like the images of other alerts. The authoritative statement is the [privacy notice](https://privacy.percia.ai/privacy/). Tell the people your camera can see that they are recorded. ## Status Live is a **beta**. Answers can be wrong, so do not use it for anything where a wrong answer could hurt someone. The Live API and MCP operations are in the beta too: the caps, the fields and the error codes can change. --- # 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:// 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:// 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 . 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 . 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 . 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 : 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://`), 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://`) 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= or ?connect_error=. - `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: }. 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-) 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. --- # SDKs and CLI > Install the JavaScript and Python SDKs and the percia command line, sign in, and see what each one covers. Page: https://percia.ai/docs/sdks. Index of all docs pages: https://percia.ai/docs/llms.txt # SDKs and CLI All three are open source (MIT), generated from the same OpenAPI document as the [API reference](https://percia.ai/docs/api.md), and live in [github.com/percia-ai/percia-sdks](https://github.com/percia-ai/percia-sdks). | | Install | Package | |---|---|---| | JavaScript and TypeScript | `npm install @percia/sdk` | [@percia/sdk](https://www.npmjs.com/package/@percia/sdk) (latest) | | Python 3.9+ | `pip install percia` | [percia](https://pypi.org/project/percia/) (latest) | | Command line | `npm install -g @percia/cli` | [@percia/cli](https://www.npmjs.com/package/@percia/cli) (latest) | ## Sign in :::tabs ```js JavaScript import { createClient } from "@percia/sdk"; const percia = createClient({ apiKey: process.env.PERCIA_API_KEY }); // pk_live_... // or an OAuth token: createClient({ oauthToken }) console.log(await percia.account.whoami()); // connection test ``` ```python Python import os from percia import Percia client = Percia(api_key=os.environ["PERCIA_API_KEY"]) # or set PERCIA_API_KEY print(client.account.whoami()) # connection test # AsyncPercia is the async version with the same methods ``` ```bash CLI percia login # browser sign-in (OAuth with PKCE) percia login --with-key # or paste an API key at a hidden prompt PERCIA_API_KEY=pk_live_... percia whoami # CI: the environment wins percia doctor # checks your setup ``` ::: The default API address is `https://playground.percia.ai`. Override it with `baseUrl` (JavaScript), `base_url` or `PERCIA_BASE_URL` (Python). ## Common jobs :::tabs ```js JavaScript // create, test, read, pause, delete const watch = await percia.watches.create({ sourceUrl: "rtsp://cam.example.com/stream", goal: "A person is standing at the front door", notify: { type: "webhook", target: "https://example.com/hooks/percia" }, }); await percia.watches.testDelivery(watch.id); for await (const e of percia.events.iterate({ type: "goal.met" })) console.log(e.at, e.reason); await percia.watches.pause(watch.id); await percia.watches.delete(watch.id); // plan and free minutes console.log(await percia.account.billing()); ``` ```python Python watch = client.watches.create({ "sourceUrl": "rtsp://cam.example.com/stream", "goal": "A person is standing at the front door", "notify": {"type": "webhook", "target": "https://example.com/hooks/percia"}, }) client.watches.test_delivery(watch.id) for e in client.iter_events(type="goal.met"): print(e.at, e.reason) client.watches.pause(watch.id) client.watches.delete(watch.id) ``` ```bash CLI percia plan # free minutes left, credits, how you are charged percia watches list percia watches create --source rtsp://cam.example.com/stream --goal "A person is at the door" --email me@example.com percia events list --follow # new events as they arrive percia cameras add "Hall phone" # link and QR; then --source percia-cam:// percia destinations connect slack # prints a link a person approves percia listen --forward-to http://localhost:3000/hook percia cameras push run --rtsp rtsp://user:pass@192.168.1.20/stream1 # needs ffmpeg 7.1+ percia mcp setup claude-code ``` ::: The CLI prints JSON with `--json`, exits with a code per kind of failure (3 not signed in or missing scope, 4 not found, 5 rate or plan limit, 6 network, 7 server), and shows each secret once. ## What they cover The SDKs include retries, typed errors, pagination, webhook signature checking and an event stream. The latest SDK and CLI releases (0.5.0 and later) cover all 171 operations in the API, including the six [Live](https://percia.ai/docs/live.md#with-the-sdks) operations, generated from the same OpenAPI document. If a call from the [API reference](https://percia.ai/docs/api.md) is missing in the version you installed, update the package or call the HTTP API directly. In JavaScript every covered operation is also available by its `operationId` as `percia.api.(options)`, which returns `{ data, error, response }` without throwing. `percia.raw` is the generated client. ## Postman and examples - A Postman collection, environment and an Insomnia export are in the repository's `postman/` folder. - `examples/` has webhook receivers (Express, Cloudflare Workers, FastAPI, Go, Ruby), a Slack script, a voice alert and a GitHub Actions example. --- # Limits, pricing and credits > What Percia costs, what is free, camera-minutes and credits, and every limit with its error. Page: https://percia.ai/docs/limits. Index of all docs pages: https://percia.ai/docs/llms.txt # Limits, pricing and credits ## Price Percia charges for **camera time**, not for watches or alerts. - **$0.50 per camera-hour**, billed by the exact minute (seconds carry over, nothing is rounded up to a block), before tax. - A camera counts while at least one of your active watches uses it and it is sending video. Ten watches on one camera cost the same as one. - Hours without video are free: a watch whose camera stopped sending pauses itself after an hour. - **10 free camera-minutes every calendar month (UTC)**, no card. Unused minutes do not roll over. - **50 bonus minutes once** when you add a card (once per card and per account; they never expire). Adding a card charges nothing. - After the free minutes and credits, the card is charged monthly for the camera time used. - A **monthly spend cap** (default $200) pauses your watches and emails you when reached. Raise it and resume. Order of use: free monthly minutes, card bonus, credits, then the card. ## Credits Credit minutes come from a redeemed code or a grant. They are used after the free minutes of the month, are not charged and do not count toward the spend cap. - Redeem a code on the **Billing** page of the app, or `POST /api/billing/redeem {"code":"..."}`. Redeeming needs a card on file (otherwise `402 card_required`, and the code is not used). - Codes work once per account. Unknown, disabled and expired codes answer `404 code_invalid`; a code with no redemptions left answers `409 code_fully_claimed`. - **Events and hackathons:** Percia can give an event its own camera-minutes, claimed with your email. They are used before other credits, need no card while they last, and expire (your plan shows `eventCreditExpiresAt`). The organisers tell you how to claim them; if something does not work, ask in the [Percia Discord](https://discord.gg/97HRGJtzVs). Read your balance: ```bash curl -sS "$BASE/plan" -H "Authorization: Bearer $PERCIA_API_KEY" # freeMinutesLeft, creditMinutes, monthToDate, capCents, pricing, billingEnforced, ... curl -sS "$BASE/usage/cameras" -H "Authorization: Bearer $PERCIA_API_KEY" # this month, per camera ``` `whoami` also carries a `billing` block (`canStartWatches`, free and credit minutes, `billingUrl`). Adding a card and the billing portal are for people only: a key cannot call them. ## What happens when you run out Creating or resuming a watch answers `429 plan_limit` with `limit: "billing"` when the free minutes and credits are used and there is no card, or the cap is reached. Watches paused for billing show `pausedReason: "needs_billing"` or `"spend_cap"`. If a card payment fails you have 48 hours of grace: everything keeps working. After that, watches pause (`payment_failed`) and writes answer `402 payment_required`; reads always work. The account recovers by itself once payment succeeds. ## Limits | Thing | Limit | |---|---| | Active watches per camera | 10 (`429 plan_limit`, `limit: "watchesPerStream"`) | | Active watches per account | 20 (`429 plan_limit`, `limit: "activeWatches"`) | | Cameras per account | 50, including camera links (`429 camera_limit`) | | Goal | 5 to 500 characters | | `sourceUrl`, webhook target | 2048 characters; public hosts only | | Connections per account, rules per watch | 20, 5 | | Connection delivery attempts | 120 per hour | | REST hooks | 20 | | Agents, concerns per agent | 50, 10 | | Sites | 20 | | Events per page | 1 to 100, default 50 | | Keyframe | JPEG, at most 256 KB | | Event stream | 2 at once, 10 connects a minute, 10 minutes each | | Alert emails | 20 per recipient per hour | | Rate limit | about 10 creating requests a minute per address and path; over it, `429` with `Retry-After` | Private, loopback and link-local addresses are refused for sources and webhook targets (`localhost`, `*.local`, `*.internal`, `10/8`, `127/8`, `172.16/12`, `192.168/16`, `169.254/16`, `::1`, `fc00::/7`, `fe80::/10`). For a camera on a private network use the [bridge](https://percia.ai/docs/cameras.md#cameras-on-a-private-network). ## What is kept, and for how long - **Keyframes** (the still at each alert): 1, 3, 7, 14 or 30 days. Default 3 days for accounts in the EU, EEA, UK and Switzerland, 7 days elsewhere. Stored encrypted per user and deleted at expiry. - **Recording:** while a camera is on, Percia records its video (no audio): the last 2 hours on Percia's video servers and 14 days in an encrypted archive. There is no endpoint to download the raw recording; you get keyframes and clips of events. Deleting a camera deletes its recordings. - **Uploaded files:** kept 14 days or until their watch is deleted. - **Deleting a watch** deletes its events, keyframes and clips. Deleting the account deletes everything. - Percia does not identify people by their face and does not train on your footage. The authoritative statement is the [privacy notice](https://privacy.percia.ai/privacy/). You must tell the people your camera can see that they are recorded, and get any consent the law requires (see the [terms](https://www.percia.ai/terms)). --- # Errors > The error body, the status codes and what to do about each. Page: https://percia.ai/docs/errors. Index of all docs pages: https://percia.ai/docs/llms.txt # Errors Errors are JSON: ```json { "error": { "code": "invalid_request", "message": "Describe what to watch for", "field": "goal", "request_id": "req_411b5f5fd4eeda46aa6e" }, "message": "Describe what to watch for", "request_id": "req_411b5f5fd4eeda46aa6e" } ``` Branch on the HTTP status and `error.code`, never on the message text. `field` names the first invalid field on a validation error. Every response has an `x-percia-request-id` header, and a JSON error repeats it as `request_id`: **quote it when you ask for help** (Discord or support@percia.ai). A plan limit (`429 plan_limit`) names the limit that was reached in `limit`: ```json { "error": { "code": "plan_limit", "limit": "activeWatches", "message": "You can have up to 20 active watches. Pause or delete one first.", "request_id": "req_411b5f5fd4eeda46aa6e" }, "message": "You can have up to 20 active watches. Pause or delete one first.", "request_id": "req_411b5f5fd4eeda46aa6e" } ``` ## Statuses | Status | Code | Meaning | What to do | |---|---|---|---| | 400 | `invalid_request` | A field failed validation | Fix the field named in `field` | | 400 | `goal_not_allowed` | The goal asks to identify a person, recognise faces or infer emotion | Reword it | | 400 | `pairing_invalid` | A camera pairing link is invalid, used or expired | Make a new one | | 401 | `unauthenticated` | No credential, a wrong key, or an expired session | Check the key | | 402 | `payment_required` | The last payment failed and the 48 hour grace is over | Update the card on the Billing page; do not retry | | 402 | `card_required` | Redeeming a code needs a card on file | Add a card, then redeem again | | 403 | `insufficient_scope` | The key lacks a scope; the answer names it | Create a key with that scope | | 404 | `not_found` | No such thing, or it is not yours (the two look the same) | Check the id and account | | 404 | `code_invalid` | A credit code is unknown, disabled or expired | Check the code | | 409 | `camera_in_use` | A camera has watches | Delete or move the watches first | | 409 | `code_already_redeemed`, `code_fully_claimed` | The account used the code, or it has none left | Do not retry | | 409 | `unsupported_not_acknowledged` | Part of the goal cannot be watched | Tell the person, then send `acknowledgeUnsupported: true` | | 422 | `clarification_needed` | The goal needs an answer; nothing was created | Answer the `question`, then create with the `draftId` | | 422 | `invalid_request` with an old field name | An input from an older version (`cooldownS`, `zones` and similar) | Remove it and say it in the goal | | 429 | `rate_limited` | Too many requests | Wait for `Retry-After`; do not loop | | 429 | `plan_limit` | A limit was reached: 11th watch on a camera, 21st active watch on the account, billing, 20 connections | Read `limit` and `message` | | 429 | `camera_limit` | 50 cameras | Delete one | | 5xx | `internal_error` | A fault on our side | Retry with backoff. A create that returned 5xx may have succeeded: list your watches first | | 503 | `integration_unavailable`, `layer_unavailable` and similar | That feature is not available right now | Try later | A failed webhook delivery is not an API error. It shows on the event as `deliveryStatus: "failed"` (see [Events and webhooks](https://percia.ai/docs/webhooks.md#5-retries-and-failures)). Every operation in the [API reference](https://percia.ai/docs/api.md) lists the statuses it can answer. --- # Changelog > What changed in the API, the app and the integrations, newest first. Page: https://percia.ai/docs/changelog. Index of all docs pages: https://percia.ai/docs/llms.txt # Changelog This page lists the changes that matter to builders, newest first. It is updated with every change that reaches the API, MCP or the integrations. `whoami` returns the latest few entries too. ## Recent changes that matter to builders - **2026-12-05** Live (Beta): talk to a live agent about a camera in the app. See [Live (Beta)](https://percia.ai/docs/live.md). The API gains seven read routes for what the engine sees on a watch ([API reference](https://percia.ai/docs/api.md#reading-what-the-engine-sees)). - **2026-12-05** An account can have up to 20 active watches (`429 plan_limit`, `limit: "activeWatches"`; pause or delete one). Accounts already above 20 keep their watches. Cameras per account go from 10 to 50, camera links included. - **2026-12-04** The API and MCP page in the app shows the connect and API instructions as numbered steps with copy blocks (Claude, Claude Code, ChatGPT, Cursor, other agents). - **2026-12-04** The Percia community Discord is open. - **2026-12-01** Every new watch keeps a keyframe by default, in the app, over the API and over MCP. Send `media: "off"` to store nothing. - **2026-12-01** Watch reads carry `judging.couldNotCheck`: parts of the goal Percia could not check right now. An empty list is not a promise that everything was checked. - **2026-11-30** New `POST /api/cameras/{id}/live`: a live view of a paired or push camera before any watch uses it. - **2026-11-25** Video files over the API: `POST /api/uploads/from-url` and `POST /api/uploads/link`. - **2026-11-14** Paid use is on sale: $0.50 per camera-hour, billed by the minute, 10 free minutes a month. This site's docs changes: first version published as a preview on 2026-12-04. --- # Support > Where to get help, what to include, and how to report a problem. Page: https://percia.ai/docs/support. Index of all docs pages: https://percia.ai/docs/llms.txt # Support ## Ask the community and the team Join the **[Percia Discord](https://discord.gg/97HRGJtzVs)**. Ask questions, share what you build and get help from the team and other builders. It is the fastest place for a how-to question. ## Account, billing and privacy Email **[support@percia.ai](mailto:support@percia.ai)** for anything about your account, a payment, or your data. ## Include these when you ask - The `request_id` from the error (or the `x-percia-request-id` header of the response). - The watch id, camera id or event id. - What you expected and what happened, with the time (and time zone). - Never send an API key, a `whsec_` secret or a pairing link. ## Status Is the website, the app, the API, MCP or the phone cameras down? Look at **[status.percia.ai](https://status.percia.ai)**. ## Terms and privacy - [Terms](https://www.percia.ai/terms) and [privacy](https://privacy.percia.ai/privacy/)