<cursor_untrusted_data_1337 source="CallDynamicTool">

# Ghostsuite Agent API

Read this page top to bottom before you call anything. It is written for AI agents and for the humans wiring them up. Everything here describes behavior that is live today and was checked against the production API on 2026-12-03.

## Quickstart (5 steps)

Base URL (this deployment): `https://xvunwksrhbzmxilrvoxn.supabase.co/functions/v1`

1. Ask for a sign-in code. The user gets an email with a numeric code.
   `POST {BASE}/suite-agent-auth` body `{"op":"request_otp","email":"you@example.com"}`
2. Verify the code. Type exactly the digits the email shows. Today that is 8 digits, but do not hard-code a length.
   `POST {BASE}/suite-agent-auth` body `{"op":"verify_otp","email":"you@example.com","token":"<digits from email>"}`
   You get a short-lived `session_token` (starts with `gst_sess_`, valid 5 minutes) and your `orgs`.
3. Get the agent API key (shown once).
   `POST {BASE}/suite-agent-auth` with header `Authorization: Bearer <session_token>` and body `{"op":"ensure_api_key","suite_org_id":"<org id>"}`
   Save the `api_key` (starts with `gs_live_`) in a secret store right now.
4. Call the API with the key: `Authorization: Bearer gs_live_...`
   `GET {BASE}/suite-api/clients` lists clients. `GET {BASE}/suite-agent-api/usage` shows your usage.
5. Read the `Usage and metering` and `Errors` sections before you loop or batch anything.

Rules that prevent most failures:

- Send `Content-Type: application/json` on every request that has a body.
- Send an `Idempotency-Key` header on every write (POST, PATCH, DELETE) so a retry never double-writes.
- On 429 wait for the `Retry-After` header (seconds) before retrying. On 402 stop and tell the human.
- Never print, log, or commit the `gs_live_` key.

## What this is

The Ghostsuite agent API lets an AI agent work inside one Ghostsuite organization on behalf of a person: manage clients, contacts, notes, opportunities, reminders, focus tasks, LinkedIn leads, and ingest call transcripts. Usage is metered in weekly units so every account has a predictable cost.

Three Supabase Edge Functions make up the API. All of them live under the same base URL:

| Function | Path | Purpose | Auth |
| --- | --- | --- | --- |
| `suite-agent-auth` | `POST /suite-agent-auth` | Email code sign-in, list orgs, get or rotate the agent key. Body field `op` picks the action. | none for `request_otp` and `verify_otp`; `Bearer gst_sess_...` for the rest |
| `suite-api` | `/suite-api/...` | CRM path REST: clients, contacts, notes, opportunities, reminders, focus tasks, leads, transcripts. HTTP method plus path picks the action (no `op`). | `Bearer gs_live_...` |
| `suite-agent-api` | `GET /suite-agent-api/usage` and `POST /suite-agent-api` | Usage readout and brokered product operations. Body field `op` picks the action. | `Bearer gs_live_...` |

Product broker operations for Ghostsign, Ghostrack, and Ghostpost are live on `POST /suite-agent-api` (see `Product broker ops`). The CLI exposes them as `ghostsuite sign …`, `ghostsuite track …`, and `ghostsuite post …` with `stability: live` in the manifest. Before the first successful broker call on a product, the org owner must link with `ghostsuite link track|sign|post --org <uuid>` (requires a `gst_sess_` owner session). Ghostsign and Ghostpost linking also needs server flags and the product `suite.link.provision` broker op deployed.

## Base URL and headers

- Base URL: `https://xvunwksrhbzmxilrvoxn.supabase.co/functions/v1` (the Suite Supabase project). The `/docs` page on the Suite site shows the base URL for the deployment you are reading.
- `Authorization: Bearer <token>` is the only auth header you need. Use the `gs_live_` key for `suite-api` and `suite-agent-api`. Use the `gst_sess_` session token only for `suite-agent-auth`. You do not need an `apikey` header.
- `Content-Type: application/json` for request bodies.
- `Idempotency-Key: <unique string, up to 200 chars>` on writes. See `Retries and idempotency`.
- All responses are JSON. Errors look like `{"error":"<message or code>"}`; usage errors also include `"code"`; `suite-api` CRM routes may also include `"message"` with the same text.

## Getting started in detail

### 1. Request the code

```bash
curl -sS -X POST "$BASE/suite-agent-auth" \
  -H "Content-Type: application/json" \
  -d '{"op":"request_otp","email":"you@example.com"}'
```

Response (200): `{"ok":true}`

- The person receives an email from Ghostsuite. New people get "Confirm your email address". Returning people get "Your sign-in link". Both emails contain a block labeled "Your code" with the digits. Ignore the link button; agents type the code.
- First sign-in creates the account and a default workspace named "<email name>'s workspace".
- Emails are normalized for abuse control: text after a `+` in the name part is dropped (`me+x@example.com` is the same person as `me@example.com`), and dots are ignored for Gmail addresses.
- Limits: requests are limited per IP, per email, and per email domain. When exceeded you get 429 `{"error":"otp_locked","code":"rate_limited"}` with `Retry-After`. Do not request codes in a loop.

### 2. Verify the code

```bash
curl -sS -X POST "$BASE/suite-agent-auth" \
  -H "Content-Type: application/json" \
  -d '{"op":"verify_otp","email":"you@example.com","token":"12345678"}'
```

Response (200):

```json
{
  "session_token": "gst_sess_<redacted>",
  "expires_at": "2026-12-03T16:43:47.830Z",
  "orgs": [
    { "id": "ab50e0c3-d0d4-416d-adbd-911928683c6d", "name": "ghostcoded's workspace", "slug": "ghostcoded-1", "role": "owner" }
  ]
}
```

- Type whatever digits the email shows. The code is currently 8 digits. It can change, so never validate the length yourself.
- Codes expire (about one hour) and work once. Wrong or expired code returns 401 with the auth error message (for example `{"error":"Token has expired or is invalid"}`). Request a new code.
- The `session_token` lasts 5 minutes. Use it right away for steps 3 and 4, then discard it.
- Verify attempts are rate limited too (429 `rate_limited`).

### 3. List organizations (optional)

```bash
curl -sS -X POST "$BASE/suite-agent-auth" \
  -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \
  -d '{"op":"list_orgs"}'
```

Response (200): `{"orgs":[{"id":"...","name":"...","slug":"...","role":"owner"}]}`

### 4. Get the agent API key

```bash
curl -sS -X POST "$BASE/suite-agent-auth" \
  -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \
  -d '{"op":"ensure_api_key","suite_org_id":"ab50e0c3-d0d4-416d-adbd-911928683c6d"}'
```

First call (200):

```json
{
  "key": {
    "id": "d45024f7-af3c-4391-b2f3-2173b4395e06",
    "label": "Agent",
    "key_hint": "c23d",
    "scopes": ["clients:read","clients:write","opportunities:read","opportunities:write","transcripts:write","leads:read","leads:write","reminders:read","reminders:write","notes:read","notes:write","focus:read","focus:write"],
    "created_at": "2026-12-03T16:38:49.976753+00:00"
  },
  "api_key": "gs_live_<redacted>",
  "existing": false
}
```

- `api_key` is the secret. It is returned only on this first call. Save it immediately.
- Calling `ensure_api_key` again returns `{"existing":true,"key":{"id","key_hint","created_at"},"key_hint":"c23d"}` and no secret. If you lost the key, rotate it (below).
- Only an org owner or admin can create or rotate the key. Otherwise 403 `{"error":"Org owner or admin required"}`.
- The agent key has a fixed set of 13 scopes (listed above). Scopes cannot be edited on an agent key.
- Where to store the key: an environment variable such as `GHOSTSUITE_AGENT_KEY` in your secret manager or a file with permissions `600`. Never put it in a prompt, a chat message, a log, a URL, or a git repository.

### 5. Rotate a lost or leaked key

```bash
curl -sS -X POST "$BASE/suite-agent-auth" \
  -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \
  -d '{"op":"rotate_api_key","suite_org_id":"<org id>","key_id":"<key.id from ensure_api_key>"}'
```

Response (200): `{"key":{...},"api_key":"gs_live_<redacted>","existing":false,"rotated":true}`. The old key stops working immediately. You need a fresh session (steps 1 and 2) to rotate. The key id is shown in the app under Settings > Integrations > API, and in the `key.id` field returned by `ensure_api_key`.

### 6. Link products (org owner, session)

Broker ops need a product link row for the same profile as the agent key `created_by`. Only the org owner can link or unlink. `app_slug` accepts `ghostrack`/`track`, `ghostsign`/`sign`, or `ghostpost`/`post`. Ghostrack is always eligible when the broker is configured. Sign and post return `link_not_available` until the server enables them and the product ships `suite.link.provision`.

```bash
curl -sS -X POST "$BASE/suite-agent-auth" \
  -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \
  -d '{"op":"link_product","suite_org_id":"<org id>","app_slug":"ghostrack"}'
```

Response (200): `{"linked":true,"remote_org_id":"<uuid>","remote_user_id":"<uuid>"}`. Repeating the call is idempotent and returns the same ids.

List status (owner or admin):

```bash
curl -sS -X POST "$BASE/suite-agent-auth" \
  -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \
  -d '{"op":"list_product_links","suite_org_id":"<org id>"}'
```

Response (200): `{"links":[{"app_slug":"ghostrack","remote_org_id":"...","linked_at":"...","status":"linked"}]}`. Rows are for the signed-in profile only, not the whole org.

Unlink (owner only; Suite-side disable, no product deletes):

```bash
curl -sS -X POST "$BASE/suite-agent-auth" \
  -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \
  -d '{"op":"unlink_product","suite_org_id":"<org id>","app_slug":"ghostrack"}'
```

Response (200): `{"unlinked":true}`. Re-link with `link_product` clears `unlinked` idempotently.

Link ops cost 0 units. They are rate limited per org and per profile.

### Session errors

| Status | Body | Meaning |
| --- | --- | --- |
| 401 | `{"error":"Missing agent session"}` | No `gst_sess_` bearer token sent. |
| 401 | `{"error":"Agent session expired"}` | Session is older than 5 minutes or unknown. Run verify_otp again. |
| 400 | `{"error":"Unknown op: nope"}` | The `op` is not one of `request_otp`, `verify_otp`, `list_orgs`, `ensure_api_key`, `rotate_api_key`, `list_product_links`, `link_product`, `unlink_product`. |
| 400 | `{"error":"Valid email is required"}` or `{"error":"email and token are required"}` | Missing fields. |
| 403 | `{"error":"Org owner or admin required"}` | The signed-in person is not an owner or admin of that org. |
| 403 | `link_forbidden` | Non-owner tried `link_product`, or non-owner/admin tried `list_product_links`. |
| 409 | `link_conflict` | Product tenant or CRM installation disagrees with the provisioned remote org id. |
| 409 | `replay` | Broker rejected a duplicate `suite.link.provision` within its replay window (about 60 seconds). |
| 501 | `link_not_available` | Sign or Post link is disabled on the server or the product broker op is not deployed yet. |
| 503 | `product_not_configured` | Product broker or Suite signing key is not configured yet. |
| 503 | `not_available` | Unlink needs the Suite link status migration applied first. |

## Authentication for API calls

Every call to `suite-api` and `suite-agent-api` needs `Authorization: Bearer gs_live_...`.

| Status | Body | Meaning | What to do |
| --- | --- | --- | --- |
| 401 | `{"error":"Missing or invalid API key"}` | Header absent or not shaped like `Bearer gs_live_...`. | Fix the header. |
| 401 | `{"error":"Invalid API key"}` | Key unknown or revoked. | Rotate or ask the human for a new key. Do not retry. |
| 401 | `{"error":"API key expired"}` | Key has an expiry that passed. | Get a new key. |
| 403 | `{"error":"API key org mismatch","code":"org_mismatch"}` | You passed `?suite_org_id=` for a different org than the key belongs to. | A key works for exactly one org. Remove the parameter or use that org's key. |
| 403 | `{"error":"Missing scope clients:write"}` | The key lacks the scope the route needs. | Agent keys have all 13 scopes, so this means a non-agent key. Use the agent key. |

## suite-api: CRM routes

Base path: `{BASE}/suite-api`. These are plain REST routes. Replace ids with real UUIDs. Passing something that is not a UUID in a path can return 500 today, so validate ids before you call.

Metering class per route (see `Usage and metering`): reads cost 1 unit, changes cost 3 units. A request that fails (non 2xx) is refunded.

| Method and path | What it does | Units | Scope |
| --- | --- | --- | --- |
| `GET /clients` | List clients (up to 200, by name). Optional `?referred_by_client_id=<uuid>` | 1 | clients:read |
| `POST /clients` | Create a client. Required: `display_name`. Optional: `email`, `phone`, `company_name`, `website`, `status`. | 3 | clients:write |
| `GET /clients/{id}` | Get one client | 1 | clients:read |
| `PATCH /clients/{id}` | Update client fields | 3 | clients:write |
| `DELETE /clients/{id}` | Delete a client | 3 | clients:write |
| `GET /clients/{id}/contacts` | List contacts | 1 | clients:read |
| `POST /clients/{id}/contacts` | Add a contact. Required: `full_name`. Optional: `email`, `phone`, `role_title`, `notes`. | 3 | clients:write |
| `PATCH /clients/{id}/contacts/{contact_id}` | Update a contact | 3 | clients:write |
| `DELETE /clients/{id}/contacts/{contact_id}` | Delete a contact | 3 | clients:write |
| `GET /clients/{id}/notes` | List notes | 1 | notes:read |
| `POST /clients/{id}/notes` | Add a note. Required: `body`. | 3 | notes:write |
| `PATCH /clients/{id}/notes/{note_id}` | Edit a note | 3 | notes:write |
| `DELETE /clients/{id}/notes/{note_id}` | Delete a note | 3 | notes:write |
| `GET /clients/{id}/activity` | Timeline for a client | 1 | notes:read |
| `GET /opportunities` | List opportunities | 1 | opportunities:read |
| `GET /opportunities/stages` | Pipeline stages | 1 | opportunities:read |
| `GET /opportunities/pipelines` | Pipeline names | 1 | opportunities:read |
| `GET /opportunities/{id}` | Get one | 1 | opportunities:read |
| `POST /opportunities` | Create. Required: `client_id`, `name`. Optional: `value_cents`, `stage_id`, `notes`, `expected_close_date`. | 3 | opportunities:write |
| `PATCH /opportunities/{id}` | Update | 3 | opportunities:write |
| `DELETE /opportunities/{id}` | Delete | 3 | opportunities:write |
| `GET /reminders` | List reminders | 1 | reminders:read |
| `GET /reminders/{id}` | Get one | 1 | reminders:read |
| `POST /reminders` | Create. Required: `title`. Optional: `due_at` (ISO time), `suite_client_id`, `body`. | 3 | reminders:write |
| `PATCH /reminders/{id}` | Update | 3 | reminders:write |
| `DELETE /reminders/{id}` | Delete | 3 | reminders:write |
| `POST /reminders/{id}/complete` and `/uncomplete` | Mark done or not done | 3 | reminders:write |
| `GET /focus/tasks` | List focus tasks | 1 | focus:read |
| `GET /focus/tasks/{id}` | Get one | 1 | focus:read |
| `POST /focus/tasks` | Create. Required: `title`. | 3 | focus:write |
| `PATCH /focus/tasks/{id}` | Update | 3 | focus:write |
| `DELETE /focus/tasks/{id}` | Delete | 3 | focus:write |
| `GET /leads` | LinkedIn leads due for follow up | 1 | leads:read |
| `GET /leads/stats` | Weekly lead stats | 1 | leads:read |
| `GET /leads/{id}` | Get one lead | 1 | leads:read |
| `POST /leads` | Add a lead. Needs `name` and a `linkedin_url` (linkedin.com/in/...) or email. | 3 | leads:write |
| `PATCH /leads/{id}` | Update a lead | 3 | leads:write |
| `POST /leads/stage` | Move a lead. Needs `stage` and `lead_id` or `linkedin_url`. | 3 | leads:write |
| `POST /leads/touch` | Record a touch and set follow up | 3 | leads:write |
| `DELETE /leads/{id}` | Delete a lead | 3 | leads:write |
| `POST /transcripts` | Ingest a call transcript, match attendees to clients | 3 | transcripts:write |

The full field-by-field schema is in the OpenAPI file `/openapi/suite.yaml`. The examples below are real responses captured from production.

### Clients

Create (201):

```bash
curl -sS -X POST "$BASE/suite-api/clients" \
  -H "Authorization: Bearer $GHOSTSUITE_AGENT_KEY" \
  -H "Content-Type: application/json" -H "Idempotency-Key: create-acme-001" \
  -d '{"display_name":"Docs Probe Co","email":"probe@example.com","phone":"555-0100"}'
```

```json
{ "client": { "id": "e5627d22-1deb-4028-9c0f-d8d08df7d7da", "display_name": "Docs Probe Co", "email": "probe@example.com", "status": "lead", "referred_by_client_id": null, "referred_by": null } }
```

List (200): `GET /suite-api/clients` returns `{"clients":[ ... ]}` (an empty org returns `{"clients":[]}`).

Get (200): `GET /suite-api/clients/{id}`

```json
{ "client": { "id": "e5627d22-1deb-4028-9c0f-d8d08df7d7da", "display_name": "Docs Probe Co", "email": "probe@example.com", "phone": "555-0100", "company_name": null, "website": "https://example.com", "status": "lead", "tags": [], "referred_by_client_id": null, "created_at": "2026-12-03T16:39:03.983786+00:00", "updated_at": "2026-12-03T16:39:03.983786+00:00", "referred_by": null } }
```

Update (200): `PATCH /suite-api/clients/{id}` with `{"display_name":"Docs Probe Co (renamed)"}` returns the full `client` object. Delete (200): `{"ok":true}`.

Errors you will see: 400 `{"error":"display_name is required"}`, 400 `{"error":"invalid_id"}` when the path id is not a UUID, 404 `{"error":"Not found"}`.

### Contacts and notes

Add contact (201), body `{"full_name":"Pat Probe","email":"pat@example.com","role_title":"Owner"}`:

```json
{ "contact": { "id": "8949b62d-0e14-46d9-91da-3a635cac7ed4", "full_name": "Pat Probe" } }
```

Missing `full_name` returns 400 `{"error":"full_name is required"}`. Unknown fields return 400 `{"error":"Unknown field: ..."}`. `role_title` is stored as `title`. `email` and `phone` are stored on `suite_client_channels`, not on the contact row. List contacts (200): `{"contacts":[{"id","suite_client_id","full_name","title","is_primary","notes","created_at","updated_at"}]}`.

Add note (201), body `{"body":"First note"}`:

```json
{ "note": { "id": "c529c7b7-db86-4b6b-8269-99150b5c02f5", "suite_client_id": "e5627d22-1deb-4028-9c0f-d8d08df7d7da", "author_profile_id": "c54f713e-01bf-45b4-ba0b-bad6e7ac87d0", "body": "First note", "created_at": "2026-12-03T16:39:09.054322+00:00" } }
```

List notes (200): `{"notes":[ ... ]}`. Activity (200): `{"activity":{},"links":[],"timeline":[{"id","type","title","detail","at"}],"has_more":false,"last_activity_at":"...","last_activity_summary":"Note added"}`.

### Opportunities

Create (201), body `{"client_id":"<client uuid>","name":"Docs Probe Deal","value_cents":250000}`:

```json
{ "opportunity": { "id": "bd59b214-c73c-4005-97a1-b06d2d4448d3", "suite_client_id": "e5627d22-1deb-4028-9c0f-d8d08df7d7da", "stage_id": "dd7aea95-1f45-4f18-b95d-7d42238fe26f", "name": "Docs Probe Deal", "value_cents": 250000, "currency": "usd", "stage_name": "Qualified", "is_won": false, "is_lost": false, "hidden": false, "client_display_name": "Docs Probe Co" } }
```

(Real responses include more fields such as `position`, `probability`, `owner_profile_id`, timestamps.) Missing fields return 400 `{"error":"client_id and name are required"}`. List (200): `{"opportunities":[],"hidden_count":0,"has_more":false}`. Stages (200): `{"stages":[{"id","name":"Qualified","position":0,"is_won":false,"is_lost":false,"pipeline":null}, ...]}`. Pipelines (200): `{"pipelines":["crm"]}`.

### Reminders

Create (201), body `{"title":"Follow up with Docs Probe Co","due_at":"2026-12-20T15:00:00Z","suite_client_id":"<client uuid>"}` returns `{"reminder":{"id","title","due_at","suite_client_id","completed":false,"recurrence":null,"notify_email":false,"assignee_ids":[], ... }}`. List (200): `{"reminders":[...],"total":1,"has_more":false}`. Missing title returns 400 `{"error":"title is required"}`.

### Focus tasks

Create (201), body `{"title":"Docs probe task"}` returns `{"task":{"id","title","notes":"","category":"personal","status":"open","ram_slot":"none", ... },"owner_user_id":"..."}`. List (200): `{"tasks":[...],"owner_user_id":"..."}`.

### Leads

Add (201), body `{"name":"Lee Lead","linkedin_url":"https://www.linkedin.com/in/docs-probe-lee"}`:

```json
{ "created": true, "message": "Added Lee Lead at New.", "lead": { "id": "5b2fc30f-61cc-4b92-9c68-e388017cb80f", "name": "Lee Lead", "email": null, "linkedin_url": "https://www.linkedin.com/in/docs-probe-lee", "stage": "New", "note": "", "source": null, "value": null, "next_follow_up_on": "2026-12-06", "last_contact_on": null, "updated_at": "2026-12-03T16:40:13.120039+00:00" } }
```

Move stage (200), body `{"linkedin_url":"https://www.linkedin.com/in/docs-probe-lee","stage":"Replied"}` returns `{"message":"Moved Lee Lead to Replied.","lead":{...}}`. List (200): `{"message":"No leads to follow up.","today":"2026-12-03","count":0,"leads":[]}`. Stats (200): `{"message":"This week: 0 new, 0 replies, 0 calls, 0 won, 0 lost.","week_start":"","new":0,"replies":0,"calls":0,"won":0,"lost":0}`.

### Transcripts

Ingest (201), body `{"title":"Kickoff call","transcript_text":"Alex: hello. Pat: hi.","attendees":[{"email":"pat@example.com","name":"Pat Probe"}],"external_id":"call-001"}`:

```json
{ "transcript_id": "eedea7a9-1c58-4e7e-a478-e4b613891481", "match_status": "matched", "match_reason": "email", "client_ids": ["e5627d22-1deb-4028-9c0f-d8d08df7d7da"], "created_clients": 0 }
```

`match_status` is `matched` when an attendee email matches a client and `unmatched` otherwise (for example `match_reason: "no_attendees"`). Always send `title`, `transcript_text`, and `attendees`. An empty or invalid body (for example `{}` or a JSON array) returns 400 `{"error":"transcript body is empty or invalid"}` and is not charged.

## suite-agent-api

### GET /suite-agent-api/usage

Free to call (0 units). It does use one rate limit token. Returns your current usage (see `Usage and metering` for each field):

```bash
curl -sS "$BASE/suite-agent-api/usage" -H "Authorization: Bearer $GHOSTSUITE_AGENT_KEY"
```

```json
{ "tier": "free", "plan_status": "active", "used_units": 46, "weekly_limit": 100, "percent": 46, "reset_at": "2026-12-10T16:38:47.397Z", "pack_units": 0, "pack_percent": 0 }
```

Orgs with an unlimited grant (beta testers) get `{"unlimited":true,"label":"Unlimited"}`.

### POST /suite-agent-api

Body: `{"op":"<op name>", ...fields}`. Optional: `suite_org_id` (must equal your key's org or you get 403 `org_mismatch`), `idempotency_key` (or send the `Idempotency-Key` header).

Live today:

| op | Class and units | Result |
| --- | --- | --- |
| `suite.usage.bar` | read, 0 units | `{"ok":true,"op":"suite.usage.bar","usage":"see GET /usage"}` |

Everything under `suite.*` other than `suite.usage.bar` is handled by `suite-api` in this release. Calling them here returns 501 `{"error":"Use suite-api for CRM and transcript routes in this release"}`.

Product broker ops are live (see below). Other error shapes on this endpoint:

| Status | Body | Cause |
| --- | --- | --- |
| 400 | `{"error":"op is required"}` | No `op` in body. |
| 400 | `{"error":"Unknown op"}` | Op name not in the registry. |
| 400 | `{"error":"Invalid JSON"}` | Body is not valid JSON. |
| 400 | `{"error":"recipients required for send ops","code":"recipients_required"}` | A send op without a recipient list. |
| 400 | `{"error":"invalid_request","code":"invalid_request"}` | A broker id field is not a UUID, or a Ghostsign op omitted `project_id` / `document_id`. Not charged. |
| 405 | `{"error":"Method not allowed"}` | Only `GET /usage` and `POST` exist. |
| 501 | see above | CRM op sent to the wrong function. |

## Product broker ops

These ops are registered, metered, and brokered to the product Edge functions. Failures map to stable codes (for example **403** `not_linked`, **404** `not_found`, **422** `validation_error`); units are refunded on broker failure.

| op | Product | Class | Units |
| --- | --- | --- | --- |
| `sign.document.read` | Ghostsign | read | 1 |
| `sign.fields.place` | Ghostsign | change | 3 |
| `sign.envelope.send` | Ghostsign | send | 10 plus 1 per 100 recipients |
| `track.project.create` | Ghostrack | change | 3 |
| `post.email.send` | Ghostpost | send | 10 plus 1 per 100 recipients |

Call them as `POST /suite-agent-api` with `{"op":"sign.document.read", ...}`. Send ops must include a recipient list (`recipients`, `recipient_hash`, or `recipient_hashes`) on the Suite request for metering. Those recipient fields are not sent in the product broker `payload` (see `docs/broker-contract.md`).

If the org is not linked on that product for the profile behind the agent key (`created_by`), or the Suite link row is `unlinked`, the broker returns **403** `not_linked` and usage is refunded. The org owner runs `ghostsuite link track|sign|post` for that org.

Certain money-moving ops stay blocked at the Suite gateway with **403** `forbidden_op` even if named in the server registry.

## Usage and metering

Every organization has a weekly allowance of units. Each API call spends units based on what it does.

| Class | Units | Examples |
| --- | --- | --- |
| Read | 1 | list or get anything |
| Change | 3 | create, update, delete, ingest a transcript |
| AI | 5 | `suite.client_chat.ask` (registered, not exposed yet) |
| Send | 10, plus 1 for each full 100 recipients | emails or signature requests to people (product send ops) |

Rules:

- The week is a rolling 7 day window per organization. `reset_at` in `/usage` tells you when the next window starts and the counter returns to zero.
- Units are reserved before the work and settled when it succeeds. A failed request (validation error, 4xx, 5xx, or product error) is refunded, so errors never cost units. Verified live: a 400 on a contact create left usage unchanged.
- Reads are never blocked by the cap. Once nothing is left, reads still return 200 and stop counting. Changes, AI, and sends are blocked.
- The Free tier also limits sends to 3 different recipients per week.
- `/usage` costs 0 units.

`/usage` fields:

| Field | Meaning |
| --- | --- |
| `tier` | Current agent plan tier (`free`, `plus`, `pro`, `max`). |
| `plan_status` | Stripe plan status for the org (for example `active`). |
| `used_units` | Units spent in the current weekly window. |
| `weekly_limit` | Weekly unit allowance for the tier. |
| `percent` | Whole number 0 to 100: floored percent of `used_units` over `weekly_limit` (never rounds up to 100 before the allowance is fully used). |
| `reset_at` | ISO timestamp when the weekly counter resets. |
| `pack_units` | Units left in purchased top-up packs (paid tiers only). |
| `pack_percent` | Floored percent of one 333 unit pack remaining in `pack_units`. |
| `unlimited` and `label` | Only present (instead of the fields above) for orgs with an unlimited grant. |

### Tiers

| Tier | Price | Weekly units |
| --- | --- | --- |
| Free | $0 | 100 |
| Plus | $9 per month | 1,000 |
| Pro | $19 per month | 4,000 |
| Max | $49 per month | 15,000 |

Only the human org owner changes the plan, in the app under Settings > Billing. Agents cannot buy or change anything.

### Top-up packs

- A pack costs $10 and adds 333 units. Packs are used after the weekly allowance runs out and expire 12 months after purchase.
- Top-ups are opt-in, owner-only, and available on paid tiers only (never on Free).
- The default monthly top-up spend cap is $50 per organization. The owner can change it.
- If the owner turned on automatic reload, the API may buy a pack by itself when you hit the cap and then continue. If that charge is still in progress the 402 response includes `"status":"pending"`; wait a few seconds and retry.

## Errors

| Status | Body or code | Meaning | What the agent should do |
| --- | --- | --- | --- |
| 409 | `link_conflict` | Link provision disagrees with existing CRM remote org mapping. | Resolve installation mismatch with the human owner. |
| 409 | `replay` | Duplicate `suite.link.provision` inside the broker replay window. | Wait about 60 seconds and retry `link_product` with the same args. |
| 400 | `{"error":"..."}` | Bad input: missing field, invalid JSON, unknown op, empty transcript body. | Fix the request. Do not retry unchanged. Costs nothing. |
| 400 | `{"error":"invalid_id"}` | A path id (or a nested contact or note id) is not a UUID. | Fix the id. Do not retry unchanged. Costs nothing. |
| 401 | `Missing or invalid API key`, `Invalid API key`, `API key expired` | Bad, revoked, or expired key. | Stop. Ask the human to rotate the key. |
| 402 | `payment_required` | Paid tier, weekly units and packs are used up, and top-ups are enabled. Body: `{"error":"payment_required","code":"payment_required","reset_at":"...","top_up_url":"https://suite.ghostcoded.com/settings/billing?top_up=1"}`. `Retry-After` is seconds to reset. | Stop writes. Tell the human the top_up_url. Reads still work. Resume after the owner buys a pack or at reset_at. |
| 403 | `org_mismatch` | `suite_org_id` does not match the key's org. | Drop the parameter or use the right key. |
| 403 | `not_linked` | No linked row for the agent key's profile on that app (or status is `unlinked`). Usage refunded. | Owner runs `ghostsuite link track|sign|post`, or uses SSO or CRM mapping where linking is not enabled. |
| 403 | `forbidden_op` | Suite blocked the op for agents (for example money-moving ops). Usage refunded when applicable. | Do not call that op; use a supported broker op instead. |
| 403 | `Missing scope ...`, `Org owner or admin required` | Permission problem. | Use the agent key, or have an owner or admin do it. |
| 404 | `{"error":"Not found"}` | Unknown CRM route or resource id (`suite-api`). | Check the path and id. |
| 404 | `{"error":"not_found","code":"not_found"}` | Product broker could not find the resource (any upstream 404 maps here). Usage refunded. | Fix ids; do not retry unchanged. |
| 404 | `{"error":"broker_call_failed","code":"broker_call_failed"}` | Broker endpoint missing or misrouted. Units are refunded. | Retry later after deploy; do not treat as a missing entity. |
| 422 | `smtp_not_configured`, `validation_error`, and similar | Product broker rejected the send (for example SMTP not set on the org). Units are refunded. | Fix org config or payload. |
| 503 | `suite_billing_unavailable`, `broker_not_configured` | Product broker or Ghostsign billing handoff failed. Units are refunded. | Retry later; owner may need Sign billing or broker env on the product. |
| 405 | `Method not allowed` | Wrong HTTP method. | Fix the method. |
| 409 | `idempotency_in_flight` | Same Idempotency-Key is still being processed. | Wait 2 to 5 seconds and retry with the same key. |
| 409 | `idempotency_consumed` | That Idempotency-Key was used by a request that failed and was refunded. | Retry with a new key. |
| 429 | `usage_exhausted` | Free tier (or paid tier without top-ups) used up the weekly units and a change, AI, or send was requested. Body: `{"error":"usage_exhausted","code":"usage_exhausted","reset_at":"..."}`. `Retry-After` is seconds until reset (up to 7 days). | Stop writes. Keep doing reads if useful. Tell the human they can upgrade, or wait for reset_at. Do not loop. |
| 429 | `rate_limited` | Too many calls too fast. Body: `{"error":"rate_limited","code":"rate_limited"}` with `Retry-After` (seconds, usually 1). | Sleep for `Retry-After`, then retry the same request. |
| 429 | `otp_locked` with code `rate_limited` | Too many sign-in code requests or attempts. | Wait for `Retry-After`. |
| 500 | `{"error":"internal_error"}` or `usage_check_failed` | Server problem. The body never includes database text. | Retry with the same Idempotency-Key after a few seconds, up to 3 times with backoff. If it persists, tell the human. |
| 501 | `Use suite-api for CRM and transcript routes in this release` | CRM op sent to `suite-agent-api`. | Call the `suite-api` route instead. |

How to tell 429 `usage_exhausted` from 429 `rate_limited`: read `code`. `rate_limited` clears in about a second. `usage_exhausted` will not clear until `reset_at`.

## Rate limits

Each API key has a bucket of 60 tokens that refills at 1 token per second. Every request to `suite-api` or `suite-agent-api` (including `/usage`) takes one token. Bursts of up to 60 are fine, then you get about 1 request per second sustained. When the bucket is empty you receive 429 `rate_limited` with a `Retry-After` header in seconds. In a live test, 80 parallel calls produced 63 successes and 17 rate limited responses. Pace bulk work to at most 1 request per second, and use `Retry-After` rather than a fixed sleep.

## Unlimited grants (beta testers)

Ghostcoded can grant an organization or person unlimited usage for beta testing. An unlimited org is still metered (calls are recorded with the same weights) but is never blocked: it never receives 402 or 429 `usage_exhausted`. Rate limits still apply. `GET /usage` returns `{"unlimited":true,"label":"Unlimited"}`. Grants can be revoked at any time, after which the normal tier limits apply. To request one, ask the Ghostcoded team.

## Retries and idempotency

- Send an `Idempotency-Key` (any unique string, up to 200 characters, for example a UUID) on every POST, PATCH, and DELETE. Use the same key when you retry the same logical action.
- If you do not send one, the server makes a random key for each request, so a retry after a timeout can create a duplicate. Always send one for writes.
- A key is remembered per API key and operation. Replaying a successful request returns 200 `{"replayed":true}` and does not run it again (no data is returned: read the record with a GET if you need it).
- If the first attempt is still running you get 409 `idempotency_in_flight`. If the first attempt failed and was refunded you get 409 `idempotency_consumed`: use a new key.
- Retry only on: network errors, 500, 429 `rate_limited` (after `Retry-After`), and 409 `idempotency_in_flight`. Never retry 400, 401, 402, 403, 404, or 429 `usage_exhausted` unchanged.
- Backoff: wait 1 s, 2 s, 4 s, then stop and report. Add a little random jitter.
- Reservations that never finish are cleaned up automatically after about 15 minutes.

## Copy and paste examples

Set up:

```bash
export BASE="https://xvunwksrhbzmxilrvoxn.supabase.co/functions/v1"
export GHOSTSUITE_AGENT_KEY="gs_live_..."   # from ensure_api_key, stored securely
```

Check usage:

```bash
curl -sS "$BASE/suite-agent-api/usage" -H "Authorization: Bearer $GHOSTSUITE_AGENT_KEY"
```

List clients:

```bash
curl -sS "$BASE/suite-api/clients" -H "Authorization: Bearer $GHOSTSUITE_AGENT_KEY"
```

Create a client safely (retry-proof):

```bash
curl -sS -X POST "$BASE/suite-api/clients" \
  -H "Authorization: Bearer $GHOSTSUITE_AGENT_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"display_name":"Acme Dental","email":"office@acme.example"}'
```

Add a note, then a reminder:

```bash
curl -sS -X POST "$BASE/suite-api/clients/$CLIENT_ID/notes" \
  -H "Authorization: Bearer $GHOSTSUITE_AGENT_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" -d '{"body":"Asked for a proposal by Friday."}'

curl -sS -X POST "$BASE/suite-api/reminders" \
  -H "Authorization: Bearer $GHOSTSUITE_AGENT_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d "{\"title\":\"Send proposal\",\"due_at\":\"2026-12-18T15:00:00Z\",\"suite_client_id\":\"$CLIENT_ID\"}"
```

### Minimal TypeScript client

```ts
const BASE = 'https://xvunwksrhbzmxilrvoxn.supabase.co/functions/v1'
const KEY = process.env.GHOSTSUITE_AGENT_KEY! // never hard-code or log this

type ApiResult<T> = { status: number; body: T }

async function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms))
}

export async function ghostsuite<T = unknown>(
  method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
  path: string,
  body?: unknown,
): Promise<ApiResult<T>> {
  const idempotencyKey = method === 'GET' ? undefined : crypto.randomUUID() // reuse across retries
  for (let attempt = 0; attempt < 4; attempt++) {
    const res = await fetch(`${BASE}${path}`, {
      method,
      headers: {
        Authorization: `Bearer ${KEY}`,
        'Content-Type': 'application/json',
        ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
      },
      body: body === undefined ? undefined : JSON.stringify(body),
    })
    const json = (await res.json().catch(() => ({}))) as T & { code?: string; error?: string }

    if (res.status === 429 && json.code === 'rate_limited') {
      const wait = Number(res.headers.get('Retry-After') ?? '1')
      await sleep(Math.max(1, wait) * 1000)
      continue
    }
    if (res.status === 500 || (res.status === 409 && json.error === 'idempotency_in_flight')) {
      await sleep(2 ** attempt * 1000)
      continue
    }
    if (res.status === 402) {
      throw new Error(`Out of units. Ask the owner to top up: ${(json as { top_up_url?: string }).top_up_url}`)
    }
    if (res.status === 429 && json.code === 'usage_exhausted') {
      throw new Error(`Weekly units used up until ${(json as { reset_at?: string }).reset_at}`)
    }
    return { status: res.status, body: json }
  }
  throw new Error('Gave up after 4 attempts')
}

// Usage
const usage = await ghostsuite('GET', '/suite-agent-api/usage')
const created = await ghostsuite('POST', '/suite-api/clients', { display_name: 'Acme Dental' })
```

## Common mistakes

1. Hard-coding the code length. The emailed code is 8 digits today. Type whatever digits the email shows.
2. Throwing away the `api_key`. It is shown once. If you lose it, use `rotate_api_key` (needs a new sign-in).
3. Using the `gst_sess_` session token on `suite-api`. It only works on `suite-agent-auth` and expires after 5 minutes. Use the `gs_live_` key everywhere else.
4. Sending writes without an `Idempotency-Key`. A retry after a timeout then creates duplicates.
5. Retrying 429 `usage_exhausted` in a loop. Only `rate_limited` is worth retrying. `usage_exhausted` lasts until `reset_at`.
6. Treating 402 as a bug. It means the owner must act. Stop and tell the human the `top_up_url`.
7. Calling CRM ops through `suite-agent-api` (501). Use `suite-api` paths.
8. Passing `suite_org_id` for a different org (403 `org_mismatch`). One key equals one org.
9. Creating a contact with `name` instead of `full_name`, or an opportunity with `title` instead of `name` and `client_id`.
10. Passing a non-UUID in a path such as `/clients/abc`. That returns 400 `{"error":"invalid_id"}`. Validate ids before you call.
11. Calling product broker ops before link. You get **403** `not_linked` until the owner links with `ghostsuite link track|sign|post`, or after an unlink until they link again.
12. Polling `/usage` in a tight loop. It spends rate limit tokens. Check it once per task or when you get a 4xx.
13. Hammering the API. Stay under about 1 request per second for sustained work.
14. Logging request headers. That leaks the key.

## Machine-readable files

- This guide as plain markdown: `/agent-api.md`
- Pointer file for AI crawlers: `/llms.txt`
- OpenAPI for the agent endpoints: `/openapi/agent.yaml`
- OpenAPI for the CRM routes: `/openapi/suite.yaml`
- Index of all specs: `/openapi/index.json`
- Interactive reference: `/docs?tab=api&module=agent`



</cursor_untrusted_data_1337>