# Frontrunner HTTP API

Every route below takes JSON and answers JSON under `https://app.usefr.com/api/v1`. The `fr` CLI is a thin client of these routes ([CLI](/docs)); this page is the full list a personal key can call. Markdown: [/docs/api.md](/docs/api.md).

## Basics

```sh
export FR_API_KEY=fr_...      # Settings, API keys, Create key
export FR_WORKSPACE=acme      # one of the ids GET /api/v1/whoami returns
curl -s https://app.usefr.com/api/v1/$FR_WORKSPACE/lists -H "Authorization: Bearer $FR_API_KEY"
```

- **Auth:** `Authorization: Bearer fr_...` on every request. A personal key acts as you: the workspaces you are a member of, `/api/v1` only.
- **Paths:** `:ws` is the workspace id; other `:name` segments are ids from the list and get routes. URL-encode keys in paths (`/exclusions/acme.com`).
- **Bodies:** `Content-Type: application/json`, at most 2 MB.
- **Errors:** a non-2xx status with `{ "error": "<code>", "detail": "<sentence>" }`. Branch on `error`; `detail` is for a person and may be absent. Some errors add a field named in the route (`max`, `existingId`, `columns`). The integration routes answer `{ "ok": false, "error": "<sentence>" }` instead.
- **No pagination** except `GET /:ws/exclusions` and `GET /:ws/inbox/to-message`; list and run reads return everything.
- **Large responses** (64 KB and up) are compressed; send `Accept-Encoding: gzip` or let your client handle it.
- **Retrying:** routes marked upsert or idempotent are safe to repeat. Starting a run, running a campaign and sending a session message do the work again on every call.

| Status | `error` | Meaning |
| --- | --- | --- |
| 401 | `invalid_api_key` | wrong or revoked key; create a new one in Settings |
| 401 | `unauthorized` | no key reached the server, or the header is not `Bearer fr_...` |
| 400 | `invalid_workspace` | `:ws` is not a valid workspace id |
| 403 | `forbidden`, `workspace_not_allowed` | you are not a member of that workspace |
| 404 | `not_found` | no such route |
| 404 | `<thing>_not_found` | the id is wrong or belongs to another workspace |
| 413 | `request_too_large`, `too_many_rows`, `too_many_keys` | split the request; the response names `max` or `cap` |
| 429 | `rate_limited` | too many calls; wait the `Retry-After` seconds |
| 503 | `runtime_unavailable` | the agent runtime is not reachable; retry later |
| 500 | `internal` | a server fault; the body carries a `requestId` to report |

## Who am I

### GET /api/v1/whoami

Checks a key. No workspace in the path.

- Returns `{ auth: "api_key" | "session", personal, keyName, email, workspaces: string[], role }`. Use one of `workspaces` as `:ws`.

## Agents

An agent is a piece of work (its instructions, tools and schedule). Running it creates a run; the run's conversation is a session.

### GET /api/v1/:ws/agents

- Returns `{ agents: Agent[] }`. Each agent has `id`, `name`, `status` (`live`, `ready`, `draft`), `category`, `triggerType` (`cron`, `event`, `manual`, `inbound`), `triggerDetail`, `description`, `steps`, `runs` (count).

### GET /api/v1/:ws/agents/:agentId

- Returns `{ agent, spec, specSource, runnable, schedule }`. `runnable: false` means `POST .../runs` will answer 409. `schedule` is `{ campaignId, state, cron, timezone, words, nextRunAt }`, with `state: "none"` when unscheduled.
- Errors: 404 `agent_not_found`.

### POST /api/v1/:ws/agents

Creates or updates an agent (upsert by `id`; a new id is `pb_...`). Body is the agent object, bare or as `{ "agent": {...} }`.

- `name` (required, up to 200), `id`, `description`, `category` (`Prospecting`, `Inbound`, `Pipeline`, `Sales Intelligence`, `Coaching`, `Ops`, `Content`, `Lifecycle`), `status` (`live`, `ready`, `draft`), `triggerType`, `triggerDetail` (the schedule in words or cron, up to 300), `triggerTimeZone`, `steps` (up to 100 strings), `model`, `goal`, `projectId`, `parentAgentId`.
- Instructions: `system` (up to 60000 characters) or `brief` (up to 40 lines), with `effort` (`low`, `medium`, `high`, `xhigh`, `max`; default `high`), `kind` (`list`, `report`, `task`) and `actionIds` (the tools it may call). A body with only `steps` is saved as `task`, and an update that leaves `kind` out keeps the stored one. A spec sent with `system`, `brief` or `actionIds` and never a `kind` runs on a schedule as `list`: it writes to the list on its campaign (`outputListId`) and cannot start without one, so send `task` for an agent that writes no rows.
- `system` without `brief` or `scaffolding` is the whole prompt, and an update with it replaces the stored one. An agent with a prompt and no `steps` shows that prompt in the app, a line per step, read only: change it with an update that sends `system`.
- Writes to another system: an `actionIds` entry that changes a connected app (a HubSpot update, a Slack post, an email send) runs with no approval step, so the same request must name it in `allowedVendorWrites`, for example `"actionIds": ["hubspot.query_records", "hubspot.update_record"], "allowedVendorWrites": ["hubspot.update_record"]`. Without it the save answers 400 `vendor_writes_not_allowed`, whatever the agent's status. Reads and Frontrunner's own list and report writes need no grant. `GET .../agents/:agentId` shows the grants under `spec.allowedVendorWrites`.
- Event triggers: with `triggerType: "event"`, `eventTriggers` lists what starts a run, each a source id or `{ "source": "rb2b.visit", "rb2bWebsites": ["example.com"] }` to limit RB2B to some websites. Webhook source ids are the `source` values of `GET /api/v1/:ws/webhooks`; a PostHog event has to be selected on the PostHog integration first. HubSpot deal stage changes (Integrations, HubSpot, Events) and Metabase events are checked every two minutes and are chosen on the agent in the app, because their ids are not listed over this API. An update that leaves `eventTriggers` out keeps the stored ones, and any other `triggerType` clears them.
- Returns 201 (new) or 200 `{ agent, spec, schedule: { campaignId, state }, note }`.
- Going live: where the workspace requires a sample test, a new agent sent as `live` is created as `draft` (the `note` says so), turning an existing agent live answers 409 `test_required` until it passes a test in the app, and an edit to a live agent is saved as a draft.
- Errors (400 unless noted): `name_required`, `unknown_parent`, `self_parent`, `unknown_event_source`, `system_required`, `invalid_effort`, `invalid_kind`, `unknown_action_ids`, `vendor_writes_not_allowed`, `stray_vendor_write_grant` (a grant for an action not in `actionIds`), `invalid_event_websites`, `agent_spec_is_repo_owned`, 404 `project_not_found`, 409 `test_required`, 409 `schedule_cannot_start` (the write would leave on a schedule whose runs have no list to write to). Each carries a `detail`.

```sh
curl -s -X POST https://app.usefr.com/api/v1/$FR_WORKSPACE/agents \
  -H "Authorization: Bearer $FR_API_KEY" -H "Content-Type: application/json" \
  -d '{"name":"Weekly hiring signals","status":"draft","brief":["Find companies hiring a first RevOps lead","Add them to the Hiring list"]}'
```

### POST /api/v1/:ws/agents/:agentId/instructions

Publishes a new version of the agent's instructions.

- Body: `{ brief: string[] }` or `{ system: string }`, plus `changeNote` (up to 300).
- Returns `{ ok: true, id, version, spec }`.
- Errors: 400 `system_required`, 400 `not_a_shared_agent`, 404 `not_found`, 409 `not_versioned_here`.

### POST /api/v1/:ws/agents/:agentId/runs

Starts a real run, the same work a scheduled run does. Each call starts a new one.

- Body: `{ brief }` (optional, up to 8000): what you want this time, in words. With no brief the agent does what its instructions say, once.
- `{ test: true }` (optional): a rehearsal instead. No output list is bound and the agent reports what it would have written and posts nothing.
- Returns 202 `{ runId, sessionId }`. Poll `GET /:ws/runs/:runId`.
- Errors: 409 `agent_not_runnable`, 502 `run_failed`, 503 `runtime_unavailable`.

### DELETE /api/v1/:ws/agents/:agentId

Deletes the agent and its campaigns (idempotent).

- Returns `{ ok: true, id, authored, campaigns }`.

## Campaigns

A campaign runs an agent on a schedule and can tie it to a list.

### GET /api/v1/:ws/campaigns

- Returns `{ campaigns: Campaign[] }`: `id`, `name`, `agentId`, `status` (`draft`, `active`, `paused`, `archived`), `schedule` (`{ cron, timezone, label }`), `outputListId`, `sourceListId`, `params`, `createdAt`, `updatedAt`.

### POST /api/v1/:ws/campaigns

Creates or updates a campaign (upsert by `id`; keys you leave out are kept, `null` clears one).

- Body: `name` and `agentId` (required), `id`, `description`, `status` (default `draft`), `schedule` (`{ cron, timezone }` or `null`), `outputListId`, `sourceListId`, `params` (up to 20 string values).
- Returns 201 `{ campaign }`.
- Errors: 400 `name_and_agentId_required`, 400 `params_invalid`, 409 `agent_off` (`active` needs a `live` agent).

### GET /api/v1/:ws/campaigns/:id

- Returns `{ campaign }`. Errors: 404 `campaign_not_found`.

### POST /api/v1/:ws/campaigns/:id/run

Runs the campaign now. Each call starts a new run.

- Body (all optional): `asOf` (`YYYY-MM-DD`), `trigger` (`manual` by default).
- Returns 202 `{ run }`. Poll `GET /:ws/runs/:runId` with `run.id`.
- Errors: 404 `campaign_not_found`, 400 `deliver_to_invalid`, 503 `runtime_unavailable`.

## Runs

A run's `status` is `queued`, `running`, `needs_input` (waiting on a reply: read its events, answer with `POST /:ws/sessions/:id/messages`), `succeeded` or `failed`. A message to a finished run's session reopens it as `running`.

### GET /api/v1/:ws/runs

- Query: `campaignId` (optional).
- Returns `{ runs: Run[] }`, every run you can see.

### GET /api/v1/:ws/runs/:runId

- Returns `{ run }`: `id`, `campaignId`, `agentId`, `name`, `status`, `trigger`, `asOf`, `startedAt`, `endedAt`, `summary`, `stats` (`[{ label, value }]`), `outputs` (`[{ kind, label, href }]`), `outputListId`, `addedRowIds`, `updatedRowIds`, `error`, `cma.sessionId`.
- Errors: 404 `run_not_found`.

### PATCH /api/v1/:ws/runs/:runId

Renames a run.

- Body: `{ name }` (up to 60; empty resets it).
- Returns `{ run }`. Errors: 404 `run_not_found`, 400 `name_or_summary_required`.

### POST /api/v1/:ws/runs/:runId/stop

Stops work on a running run. Project runs use the project's stop operation; other runs also stop their running descendants outside projects. A later message to the session continues the run.

- No body required.
- Returns `{ stopped, run }`. `stopped` is `false` if the run is not running, including a queued or finished run.
- Errors: 404 `run_not_found`, 502 `stop_failed`.

### POST /api/v1/:ws/runs

Records a run that happened outside Frontrunner, so it shows on the campaign. Nothing executes.

- Body: `campaignId` (required, an existing campaign), `status` (`succeeded` or `failed`), `startedAt`, `endedAt` (ISO), `name`, `summary` (up to 20000), `asOf`, `outputs` (up to 10 `{ kind: "xlsx" | "list" | "slack" | "report" | "campaign", label, href }`, https only), `stats` (`[{ label, value }]`).
- Returns 201 `{ run }`.
- Errors: 400 `known_campaignId_required`, `startedAt_after_endedAt`, `outputs_invalid`.

### GET /api/v1/:ws/runs/:runId/events

The run's transcript.

- Query: `since`. Send `since=` (empty) first; the response carries a `cursor`. Send `since=<cursor>` to get only newer events. Windows overlap by a few minutes, so merge by event `id`.
- Returns `{ runId, status, events, approvals, cursor }`.
- Errors: 404 `run_not_found`, 502 `events_unavailable`, 503 `runtime_unavailable`.

### GET /api/v1/:ws/runs/:runId/corrections

- Returns `{ corrections }`: what people said the run got wrong.

### POST /api/v1/:ws/runs/:runId/corrections

Files a correction on a run (idempotent: the same text twice is one correction).

- Body: `text` (required, up to 4000), `kind` (`wrong_output`, `wrong_behaviour`, `missing_capability`), `listId`.
- Returns 201 `{ correction, duplicate: false }`, or 200 with `duplicate: true`.
- Errors: 400 `text_required`, 409 `not_filed`.

## Sessions

A session is a conversation with an agent; every run has one (`run.cma.sessionId`).

### POST /api/v1/:ws/sessions

- Body: `agentId` (required), `message` (up to 20000).
- Returns 201 `{ sessionId }`.
- Errors: 400 `agentId_required`, 502 `session_create_failed`, 503 `runtime_unavailable`.

### POST /api/v1/:ws/sessions/:id/messages

Sends a message. The agent acts on each one.

- Body: `{ text }` (required, up to 100000).
- Returns `{ ok: true }`.
- Errors: 400 `text_required`, 404 `session_not_found`, 409 `session_awaiting_tool_result` (wait and send again), 502 `session_message_failed`.

### GET /api/v1/:ws/sessions/:id

- Returns `{ sessionId, status }`: `running` or `rescheduling` while it works, `idle` or `terminated` when it has stopped.
- Errors: 404 `session_not_found`, 502 `session_status_failed`.

### GET /api/v1/:ws/sessions/:id/events

- Returns `{ sessionId, events }`, the whole transcript every time (no cursor). Track how many you have read.
- Errors: 404 `session_not_found`, 502 `events_unavailable`.

## Projects

A project holds a piece of work: its lists (Audiences), its documents and files (Context) and its agents, as the Projects page shows them. A private project is its creator's and its members': to anyone else every route below answers 404. A deleted project answers 410 `project_deleted`; an archived one is read and refuses changes (409 `project_archived`).

### GET /api/v1/:ws/projects

- Returns `{ projects }`, most recently active first, archived ones left out: `id`, `name`, `description`, `status` (`active`), `visibility` (`team`, `private`), `datasets`, `rows`, `createdAt`, `updatedAt`, `lastActivityAt`, and `v3: true` for an Outbound campaign.

### POST /api/v1/:ws/projects

Creates a project, as New project in the app (not an Outbound campaign).

- Body: `name` (required, up to 120), `description` (up to 500), `brief` (what the project is for, the rules every agent in it follows).
- Returns 201 `{ project }`.
- Errors: 400 `name_required`.

### GET /api/v1/:ws/projects/:projectId

- Returns `{ project, links, datasets, files }`. A link is `{ kind, id, title, role, rows, missing, createdAt }`: `kind` is `list`, `doc`, `file` or `agent` (or `dataset`, `project`, `run`, `skill`, `channel`, added in the app), `role` the section it is in (`audience`, `context`, `agent`), `missing` when what it points at is gone. A list shared with others but not with you is left out. `datasets` are the project's own tables (`{ id, name, rowKind, rows, updatedAt }`), `files` its folder (`{ id, path, bytes, updatedAt }`).
- Errors: 404 `project_not_found`, 410 `project_deleted`.

### POST /api/v1/:ws/projects/:projectId/links

Puts something in the project: a list in Audiences, a Business Logic document or a context file in Context, an agent under Agents. Adding what is already there changes nothing.

- Body: `kind` (`list`, `doc`, `file`, `agent`) and `id` (a `lst_` list, a `bdoc_` document, a context file id from `GET .../context/files`, a `pb_` agent).
- An agent moves into the project as it does in the app: its record's `projectId` changes (it leaves the project it was in), and its schedule, steps and tools stay as they are. An agent with unsaved changes is not moved (409 `agent_has_draft`): save or discard them in the app first. 409 `agent_not_moved` when the save did not move it.
- Returns 201 `{ link }`, and a `note` when the project's Agents list has not shown a moved agent yet.
- Errors: 400 `link_kind`, 400 `ref_required`, 404 `project_not_found`, 404 `ref_not_found`, 409 `project_archived`, 409 `agent_has_draft`, 409 `agent_not_moved`, 410 `project_deleted`.

### DELETE /api/v1/:ws/projects/:projectId/links/:kind/:refId

Takes it out again (`kind` and the id as above). An agent taken out stays under Removed on the project's page, where it can be put back; removing it again answers `link_not_found` and keeps that.

- Returns `{ ok: true }`.
- Errors: 404 `link_not_found`, 404 `project_not_found`, 409 `project_archived`, 409 `agent_has_draft`, 410 `project_deleted`.

## Lists

A list holds rows keyed by `key` (a domain, a LinkedIn slug, an email), with one cell per column.

- Row `state`: `new`, `reviewed`, `not_relevant`, `actioned`.
- Column `type`: `text` (default), `longtext`, `number`, `date`, `url`, `email`, `phone`, `badge`, `reasoning`, `sources`.
- Column `role` (optional): `person`, `account`, `account_key`, `title` (current job), `linkedin` (person profile), `email`, `phone`, `account_linkedin` (company page), `reasoning` (row reason), `score` (the primary numeric assessment from 0 to 100, independent of the column key or label). Reuse the existing field for each role when updating a schema.

### GET /api/v1/:ws/lists

- Returns `{ lists: List[] }` without rows: `id`, `name`, `description`, `kind` (`master`, `static`), `columns` (`[{ key, label, type, role }]`), `rowKind` (`person`, `company`), `status`, `createdAt`, `updatedAt`.

### GET /api/v1/:ws/lists/:listId

- Query: `newSince` (ISO date, rows surfaced since), `state` (one row state).
- Returns `{ list, rows, suppressions, makers }`. A row is `{ id, key, cells: { <columnKey>: string | number | null }, state, sources, surfacedAt, surfacedByRunId, feedback, userNote }`. Ranked lists come in rank order.
- Errors: 404 `list_not_found`, 400 `invalid_newSince`, 400 `invalid_state`.

### POST /api/v1/:ws/lists

Creates a list (upsert by `id`; columns merge by key).

- Body: `name` (required, unique in the workspace), `columns` (required, 1 to 100 `{ key, label, type, role }`), `id`, `description`, `kind` (default `master`), `rowKind`, `warm` (true for people the workspace already knows: suppression entries from the calendar, the CRM, the customer list or a bulk import then do not hold back its rows; omitted on an upsert, the stored value stays).
- Returns 201 `{ list }`.
- Errors: 400 `name_and_columns_required`, 409 `name_taken` (with `existingId`: use that list).

### PATCH /api/v1/:ws/lists/:listId/name

Renames an audience while keeping its id, rows and columns. Later dataset publications keep the saved name.

- Body: `{ name }` (required, 1 to 200 characters).
- Returns `{ list }` after the rename is saved.
- Errors: 400 `invalid_name`, 404 `list_not_found`, 409 `name_taken`.

### DELETE /api/v1/:ws/lists/:listId

Deletes an audience and its rows. A linked accounts or people list stays.

- Returns `{ deleted: true }` once the deletion is saved.
- Errors: 404 `list_not_found`, 409 `list_in_use` (`detail` names the live agents, campaigns or runs to stop first, `dependencies` lists them), 503 `list_delete_unavailable`.

### PUT /api/v1/:ws/lists/:listId/viewers

Makes a list private: only the people named see it, its rows or that it exists. An empty body shares it with the workspace again. Needs the workspace's Private lists setting.

- Body: `{ userIds?: string[], emails?: string[] }`. A person setting it stays among the viewers.
- Returns `{ list }`.
- Errors: 400 `unknown_person`, `not_a_member` or `viewers_exclude_you`, 403 `private_lists_off`, 404 `list_not_found`.

### PUT /api/v1/:ws/lists/:listId/views

Replaces the list's saved views (the filter bar's named views: filters and sort over the list, kept for everyone who reads it). Needs the workspace's List filter bar setting.

- Body: `{ views: [{ id?, name, query }] }`. `query` is the list page's filter and sort query (`f=state:new&range=employees:50:&sort=employees&dir=desc`, no leading `?`); a view without an `id` is new. At most 30 views, names up to 80 characters.
- Returns `{ list }`.
- Errors: 400 `views_required`, `too_many_views`, `view_name_required` or `view_query_invalid`, 403 `list_filters_v2_off`, 404 `list_not_found`.

### POST /api/v1/:ws/lists/:listId/columns

Adds columns (upsert by key).

- Body: `{ columns: [{ key, label, type }] }`, or one column as the body.
- Returns `{ list, added: string[] }`.
- Errors: 404 `list_not_found`, 400 `columns_required`, 400 `too_many_columns` (`max: 100`), 409 `deleted_column`.

### PATCH /api/v1/:ws/lists/:listId/columns

Reorders columns.

- Body: `{ order: string[] }` (column keys).
- Returns `{ list }`. Errors: 400 `invalid_order`, 409 `unknown_column`.

### PATCH /api/v1/:ws/lists/:listId/columns/:key

Renames a column.

- Body: `{ label }` (1 to 80 characters).
- Returns `{ list }`. Errors: 400 `invalid_label`, 404 `column_not_found`.

### DELETE /api/v1/:ws/lists/:listId/columns/:key

Removes a column from the list.

- Returns `{ list }`. Errors: 404 `column_not_found`, 400 `last_column`.

### POST /api/v1/:ws/lists/:listId/rows

Adds or updates rows (upsert by `key`; only the cells you send change).

- Body: `{ rows: [{ key, cells, sources }] }`, up to 2000 rows per call. `key` up to 300; cells are strings (up to 4000), numbers or `null`; `sources` up to 12 `{ url, title }`.
- Returns `{ added, updated, reconfirmed, suppressed, updatedColumns, held, counts: { added, updated, reconfirmed, suppressed, skipped } }`. Keys on the list's suppressions or the workspace exclusions are dropped and named in `suppressed`.
- Errors: 404 `list_not_found`, 400 `rows_required`, 413 `too_many_rows` (`max: 2000`).

### PATCH /api/v1/:ws/lists/:listId/rows/:rowId/cells/:columnKey

Edits one cell. `:rowId` is the row's `id`, not its key.

- Body: `{ value }`.
- Returns `{ columnKey, list, row }`.
- Errors: 400 `invalid_cell`, 404 `row_not_found`, 404 `column_not_found`, 409 `column_removed`, 403 `column_source_forbidden`.

### POST /api/v1/:ws/lists/:listId/rows/:rowId/enrich

Fills a person row's empty LinkedIn, email and phone cells. Filled cells are never replaced. The person is identified from the row's LinkedIn, else its email, else a single profile matching its name at its company; nothing is written for a person who cannot be identified. Spends enrichment credits.

- Body: none.
- Returns `{ filled, missing, summary, row }`: `filled` maps `linkedin`, `email` or `phone` to the value written; `missing` lists what is still empty.
- Errors: 404 `list_not_found`, 404 `row_not_found`, 409 `not_a_person_list`, 403 `demo_workspace`.

### POST /api/v1/:ws/lists/:listId/rows/state

Sets the state of many rows by key.

- Body: `state`, `keys` (up to 5000), `note` (optional; `null` clears).
- Returns `{ updated: string[], unknownKeys: string[], list }`. `not_relevant` also suppresses the key, so it stays off the list.
- Errors: 404 `list_not_found`, 400 `invalid_state`, 400 `keys_required`.

### POST /api/v1/:ws/lists/:listId/rows/:rowId/state

Sets one row's state by row `id`.

- Body: `{ state, note }`.
- Returns `{ row }`. Errors: 400 `invalid_state`, 404 `row_not_found`.

### POST /api/v1/:ws/lists/:listId/rows/note

Leaves the same feedback note on many rows by key. State is unchanged.

- Body: `note` (up to 4000), `keys` (up to 5000).
- Returns `{ updated, unknownKeys }`.
- Errors: 400 `note_required`, 400 `keys_required`.

### POST /api/v1/:ws/lists/:listId/rows/:rowId/note

Writes the row's note, with a revision check.

- Body: `text` (up to 20000), `revision` (`0` to create; otherwise the revision you read).
- Returns `{ note: { text, revision, updatedAt, updatedBy } }`.
- Errors: 400 `invalid_note`, 404 `row_not_found`, 409 `note_conflict` (the body carries the current `note`: re-read, merge, resend).

### DELETE /api/v1/:ws/lists/:listId/rows/:rowId/hold

Releases a row held back from publishing.

- Returns `{ row }`. Errors: 404 `row_not_found`.

### POST /api/v1/:ws/lists/:listId/suppressions

Keeps a key off the list from now on (upsert).

- Body: `key`, `reason` (`not_relevant`, `already_customer`, `in_comms`, `corrected`, `other`), `note`.
- Returns 201 `{ suppression }`.
- Errors: 404 `list_not_found`, 400 `key_required`, 400 `invalid_reason`.

### DELETE /api/v1/:ws/lists/:listId/suppressions/:key

- Returns `{ removed: boolean }` (idempotent).

### POST /api/v1/:ws/lists/:listId/instantly-variables

Copies columns onto the leads already in an Instantly campaign, matched by the list's email column. Adds no leads and sends no mail; repeat it after the column improves.

- Body: `campaignId` (the Instantly campaign id), `variables`: `{ "<columnKey>": "personalization" | "<variableName>" }`, or an array of column keys (each becomes a variable of the same name).
- Returns `{ campaignId, variables, emailColumn, leads, updated, missing, failed, skipped }`. `missing` are emails the campaign does not hold.
- Errors: 404 `list_not_found`, 400 `campaignId_required`, `variables_required`, `unknown_column` (with `columns`), `no_email_column`, `no_leads`, 502 `instantly_failed`, 503 `action_unavailable`.

### GET /api/v1/:ws/lists/:listId/people

For a company list: its companion people list.

- Returns `{ listId, peopleListId, list, rows, materialised, companies, people }`.
- Errors: 404 `list_not_found`, 400 `not_a_company_list`.

### POST /api/v1/:ws/lists/:listId/people

Creates or refreshes the companion people list of a company list.

- Body: `{ runId }` (optional).
- Returns 201 when the people list was created, otherwise 200, in the shape above.

### GET /api/v1/:ws/lists/:listId/nooks.csv

The list as a Nooks dialer CSV (a file, not JSON).

- Query: `part` (2000 rows each), `keys` (comma-separated), `batch`, `country`.

### DELETE /api/v1/:ws/lists/:listId/ad-sync

Stops syncing the list to an ad audience (idempotent).

- Returns `{ list }`.

### GET /api/v1/:ws/integrations/:id/crm-fields

The fields Frontrunner may write in a connected CRM (`int_monaco`, `int_attio`, `int_hubspot`): every writable field of each object it pushes (`account`, `contact` where the CRM has one), read live, each with its `mode` when allowed (`overwrite`, or `fill_empty`: only where the CRM has no value). Until a field is ticked for an object, its custom fields are allowed to overwrite and its standard fields are not.

- Returns `{ crm, objects: [{ object, ticked, fields: [{ key, name, type, options?, custom, mode? }] }] }`.

### PUT /api/v1/:ws/integrations/:id/crm-fields

Sets the fields one object may write, replacing that object's list. Every push of a list to the CRM, by a person or an agent, writes no other field.

- Body: `{ object: "account" | "contact", fields: [{ key, mode }] }`, `mode` `overwrite` or `fill_empty`; `fields: []` allows none, `fields: null` puts the object back to the default.
- Returns `{ allowlist, view }` (the view as GET answers it).

### GET /api/v1/:ws/integrations/:id/crm-activity

LinkedIn messages the Inbox writes into Attio (`int_attio` only) as notes on the person: one note per message sent from the Inbox on a LinkedIn account connected to Frontrunner, and one per reply in those conversations, only for people Attio already has. Shown where the workspace has LinkedIn activity in Attio turned on.

- Returns `{ crm, on, sent, received, week: { written, skipped, failed, queued }, reasons, lastFailure? }`: `sent` and `received` are each off until set.

### PUT /api/v1/:ws/integrations/:id/crm-activity

Turns notes for sent messages, replies, or both on or off.

- Body: `{ sent?: boolean, received?: boolean }`.
- Returns the view as GET answers it.

### GET /api/v1/:ws/lists/:listId/crm-push

What a push of the list to a CRM would write: the connected CRMs that take one (Monaco, Attio, HubSpot), the account fields the workspace allows there (read live, with their mode) and the list's mapping.

- Query: `crm` (default the one the list was pushed to, else the first connected).
- Returns `{ setup: { targets, crm, fields, mapping, domainColumn, contacts, keepSynced, error? }, columns, sync }`.

### POST /api/v1/:ws/lists/:listId/crm-push

Writes the list's rows into the CRM as accounts, matched by company domain. Only the mapped fields are written, and only fields the workspace allows (a mapped field it does not allow refuses the push); an account the CRM does not have is created. A row with no company domain does not go.

- Body: `{ crm, mapping: [{ column, field }], domainColumn?, contacts?, keepSynced?, keys? }`.
- `keepSynced` pushes the rows the list gains or changes from now on.
- Returns `{ result: { ok, summary, data }, list }`; a push of more than 100 rows answers that it started and goes on in the background (the list's `crmSync.last` shows progress).

### DELETE /api/v1/:ws/lists/:listId/crm-push

Stops pushing the list as it changes. The mapping stays for the next push; the CRM keeps what it has.

- Returns `{ list }`.

## Context files

Your own material for agents and the assistant to read: a customer export, a CRM dump, notes. CSV, TSV, XLSX, JSON and text are read; anything else is stored as is. Up to 32 MB per file.

### GET /api/v1/:ws/context/files

- Query: `includeSuperseded=1` adds the older versions.
- Returns `{ ws, files: [{ id, name, title, description, kind, bytes, table, version, status, uploadedByLabel, uploadedAt }] }`. `kind` is `table`, `text`, `json` or `binary`; `table` holds `rows`, `columns` and the first rows.

### POST /api/v1/:ws/context/files

Uploads one file. The body is the raw file bytes (any `Content-Type` but `application/json`), not multipart.

- Query: `name` (the filename, required), `title`, `description`, `resolution` (`new_version`, `keep_both` or `skip`: the answer to a conflict, given up front).
- Returns `{ status: "stored", file }`, or `{ status: "skipped", file, reason }` when `resolution=skip` met a conflict.
- A file that collides with one already here (the same bytes, the same filename, or the same columns) is 409 `{ status: "conflict", token, conflict: { kind, message, existing, options } }` and nothing is stored. Send it again with a `resolution`: `new_version` replaces the earlier file and keeps it in version history, `keep_both` stores both.
- Errors: 400 `name_required`, 400 `empty_body`, 400 `invalid_resolution`, 400 `upload_failed`, 413 `file_too_large`, 422 `unreadable_workbook`.

### GET /api/v1/:ws/context/files/:id

- Query: `offset`, `limit` (default 50, up to 500) page the preview of a table.
- Returns `{ file, versions, preview: { columns, rows, totalRows } }` for a table, `{ file, versions, text }` (the first 40,000 characters) for text and JSON.
- Errors: 404 `not_found`.

### GET /api/v1/:ws/context/files/:id/download

The original bytes as uploaded (a file, not JSON).

- Errors: 404 `not_found`, 404 `blob_missing`.

### GET /api/v1/:ws/context/docs

The workspace's Business logic documents.

- Query: `includeAll=1` adds drafts and archived documents; without it, only the active ones agents read.
- Returns `{ ws, docs: [{ id, title, summary, status, ownerName, revision, updatedAt, chars }] }`. `status` is `active`, `draft` or `archived`.

### GET /api/v1/:ws/context/docs/:id

- Returns `{ doc: { id, title, summary, status, ownerName, revision, updatedAt, chars, body, citations: [{ n, label, url, kind }] } }`, in any state. `body` is markdown.
- Errors: 404 `not_found`.

### POST /api/v1/:ws/context/docs

Creates a Business logic document. It is active (agents read it) unless `status` is `draft`.

- Body: `{ title, body?, summary?, citations?, status?: "draft", id? }`. `body` is markdown, up to 40,000 characters. Pass your own `id` (`bdoc_custom_` and 6 to 80 letters, digits, `_` or `-`) to make a retry safe: the same id answers the document already made, with `existing: true`.
- Returns 201 `{ ok: true, doc }` (the document as GET returns it, without `citations`). A summary left out is written for you shortly after.
- Errors: 400 `title_required`, 400 `invalid_doc_id`, 409 `doc_deleted` (that id is in the trash), 413 `body_too_large` (with `max`).

### PUT /api/v1/:ws/context/docs/:id

Edits a document. Fields left out are kept; `body` replaces the whole body.

- Body: `{ title?, summary?, body?, citations?, note?, status?, ifRevision? }`. `note` is the line in the document's history (default "Edited in the app"). `status: "active"` publishes a draft or brings back an archived document; `status: "archived"` puts an active one away, on its own with no edit. Pass the `revision` you read as `ifRevision` and the write is refused if anyone changed the document since.
- Returns `{ ok: true, doc }` with the new `revision`.
- Errors: 400 `invalid_doc_status`, 400 `invalid_if_revision`, 400 `archive_takes_no_edits`, 404 `not_found`, 409 `revision_conflict` (with the current `revision`; read again), 409 `doc_archived` (unarchive it first), 409 `doc_is_draft` (a draft is published, not archived), 413 `body_too_large`.

### DELETE /api/v1/:ws/context/docs/:id

- Moves the document to the trash on the Business logic page. Returns `{ ok: true, record: { deletedAt, ... } }`.
- Errors: 404 `doc_not_found`.

### POST /api/v1/:ws/context/docs/:id/restore

- Brings a deleted document back as a new revision. Returns `{ ok: true }`.
- Errors: 404 `deleted_doc_not_found`.

## Exclusions

The workspace's suppression list: keys (domains, emails, LinkedIn profiles, company names, people by name) no agent may add to any list and no list push takes. A URL is stored as its host, a LinkedIn profile as `linkedin.com/in/<slug>` and a person at a company as `Jane Doe @ Acme`. Each entry is an account (`domain`, `name`, `slug`, `cvr`) or a contact (`person`, `email`, `person-name`).

### GET /api/v1/:ws/exclusions

- Query: `q` (matches key, note or name), `level` (`account`, `contact`), `kind` (`person`, `email`, `person-name`, `domain`, `company`), `source` (`manual`, `import`, `agent`, `customer-list`, `calendar`, `crm`), `limit` (default 200, up to 5000), `offset`.
- Returns `{ exclusions: [{ id, key, kind, name, company, note, source, by, at }], total, bySource, byLevel, limit, offset }`, newest first.

### POST /api/v1/:ws/exclusions

Adds exclusions (upsert by key).

- One: `{ key, note }`. Returns 201 `{ exclusion }`, or 200 `{ exclusion, already: true, detail }` when the key is already on the list.
- Many: `{ keys: string[] }` or `{ exclusions: [{ key, note, kind, name, company }] }`, up to 5000, with optional `source` (`calendar` and `crm` are kept by the suppression sync and read as `manual` here) and `note`. `kind: "person-name"` stores a bare name as a person; other kinds are read off the key. Returns `{ ok: true, added, updated, unchanged, total }`.
- Errors: 400 `key_required`, 400 `keys_required`, 413 `too_many_keys` (`cap: 5000`).

### POST /api/v1/:ws/exclusions/sort

Sorts a paste or a file into contacts and accounts, as the keys they would be stored as. Writes nothing.

- Body: `{ text }` (one value per line), or a CSV or XLSX file as the raw body. A file's header decides by column (email, LinkedIn, name, company, website); free text with no shape is read by the model.
- Returns `{ entries: [{ key, kind, level, name, company, by }], skipped: [{ value, why }], asked }`. Post the entries to `POST /exclusions` to add them.
- Errors: 400 `text_required`, 400 `no_table`, 400 `unreadable_file`, 413 `file_too_large`.

### DELETE /api/v1/:ws/exclusions/:key

- Removes any entry, a `calendar` or `crm` one too, for good: the calendar and CRM sync does not add the key back, and the Inbox no longer holds the person back for that meeting or deal. Adding the key again suppresses it as before.
- Returns `{ ok: true }`. Errors: 404 `exclusion_not_found`.

### GET /api/v1/:ws/suppressions

The rows taken off the workspace's lists, each list's own suppressions.

- Query: `q` (matches key, name, list or who removed it), `level` (`account`, `contact`; a row of a people list is a contact), `limit` (default 200, up to 5000), `offset`.
- Returns `{ removed: [{ id, key, name, listId, listName, level, by, at }], total, byLevel, limit, offset }`, newest first.

## Inbox

### GET /api/v1/:ws/inbox/inbounds

LinkedIn conversations whose newest message is from the other person, on the LinkedIn accounts you can read in the Inbox. Poll it to copy replies into a CRM.

- Query: `since` (ISO time, default 24 hours ago, at most 7 days back), `seat` (one account id from `seats`).
- Returns `{ since, inbounds: [{ seatId, seatName, chatId, at, text, attachment, unread, inmail, contact: { name, headline, profileUrl, providerId }, lists: [{ id, name }], crm }], seats: [{ id, name, provider, readAt, complete, error }] }`, newest first. `text` is the newest message only.
- Each account is read from LinkedIn at most every 15 minutes; a call inside that window answers from the last read (`readAt`). `complete: false` means the read stopped at 100 conversations before reaching `since`.
- Key on `chatId` plus `at`: a conversation comes back on every poll until you reply.
- Errors: 400 `invalid_since`, 400 `since_too_old`, 404 `seat_not_found`.

### GET /api/v1/:ws/inbox/to-message

To message: the people the Inbox offers a first LinkedIn message to, as the Inbox shows them to you (its order, its holds and suppressions), on the LinkedIn accounts you can read there. For reading the queue in a sheet or a model.

- Query: `seat` (an account id from `seats`, or the account's name; default every account you can see), `list` (a list id, or up to ten joined by commas), `rel` (`existing` or `account`, where the Inbox splits To message by CRM), `limit` (default 100, up to 500), `offset`, `format` (`json`, or `csv` for the same page as a file, with `X-Total-Count` and, while more remain, `X-Next-Offset` headers).
- Returns `{ view: "to_message", seat, seats: [{ id, name }], total, served, bySeat: [{ id, name, count }], offset, limit, nextOffset, refreshedAt, refreshing, people: [{ key, seatId, seatName, name, headline, company, website, location, profileUrl, connectedAt, lists: [{ id, name }], reason, source, campaign, crm, skipped, alsoOn }] }`. `total` is the To message count and `served` how many people the pages add up to: the same, up to 5,000 a queue (above that, narrow with `list`). Page with `offset` while `nextOffset` is there.
- With one `seat`, `total` is that account's To message count in the Inbox. Across every account, a person two accounts are connected to is listed once, under one account, with the others in `alsoOn`; `bySeat` counts the rows per account, so an account's share can be lower than its own count.
- Reads the copy the Inbox keeps: never a LinkedIn profile, never a send, and a repeat call does not read LinkedIn again. 30 calls every 10 minutes per person and workspace; each call is recorded under your name.
- Off until the workspace is switched on: 403 `inbox_export_locked`.
- Errors: 400 `invalid_format`, 403 `inbox_export_locked`, 404 `seat_not_found` (with `seats`, the accounts you can see), 429 `rate_limited` (`Retry-After` in seconds), 503 `inbox_not_ready` (the suppression list is still loading; try again in a minute).

## Outreach

### GET /api/v1/:ws/outreach/stats

LinkedIn and email sends per account per UTC day: the counts the Sequences page reads, for a dashboard or a sheet of your own.

- Query: `from`, `to` (YYYY-MM-DD, UTC, both included; `to` defaults to today) or `days` (counted back from `to`), default the last 30 days, at most 366; `by` (`seat`, the default, or `campaign` to add each started HeyReach campaign per account).
- Returns `{ workspace, from, to, timezone: "UTC", at, sources: { heyreach, inbox, instantly }, totals, days: [{ day, ...counts, emails }], seats: [{ name, heyreachId, inboxId, totals, days: [{ day, ...counts }] }], mailboxes: [{ email, name, totals: { emails }, days: [{ day, emails }] }], campaigns, campaignsLeft, errors }`. Every day of the window is there, oldest first, zeros included.
- Counts: `connectionRequests`, `accepted`, `messaged` (people a sequence wrote to first, InMails included), `messages` (every message a sequence sent, follow-ups included) and `replies`, from HeyReach's stats per account; `inboxMessaged` (people written to from the Inbox, each once a day), `inboxFirstMessages` (the first messages among them) and `inboxReplies` (replies to first messages sent in the window or the 90 days before it), from the Inbox on accounts connected to it. `emails` per Instantly mailbox.
- Each count is an event on the day it happened: an accept counts on the day of the accept, not the day of its request.
- A HeyReach seat is one account by its id; an Inbox account joins the HeyReach seat with its name when exactly one has it. With `by=campaign`, `campaigns: [{ id, name, totals, seats: [{ name, totals, days }] }]`, newest campaigns read first; `campaignsLeft` counts the ones not read.
- A source that did not answer is left out and named in `errors`; the rest is still returned. Each window is read at most every 15 minutes (2 when a source was left out). 60 calls every 10 minutes per person and workspace; a workspace reads at most 12 windows it has not read in the last 15 minutes every 10 minutes, 3 of them with `by=campaign`.
- Errors: 400 `invalid_date`, 400 `invalid_days`, 400 `invalid_window`, 400 `window_too_long`, 400 `invalid_by`, 400 `invalid_query` (a parameter given twice), 429 `rate_limited` (`Retry-After` in seconds), 503 `outreach_unavailable`.

## Outbound copy

### POST /api/v1/:ws/lists/:listId/copy

Each person's words for one step, or for a sequence's steps, written from their row by the Sequences writer with the workspace's Business Logic. Nothing is kept on the list and nothing is sent.

- Body: either `channel` (`linkedin` or `email`), `mode` (LinkedIn only: `message`, the default, `connect` for the connection note, or `inmail`), `instruction` (what to write, required) and `subject` (an email's or an InMail's, required for them; merge fields filled per person); or `spec`, a whole sequence as `POST /api/v1/:ws/copy/draft` returns it (its fixed steps are filled in, its steps with an `ai.instruction` are written). People: `keys` (row keys), else `offset` and `limit` (default 10) over the list's rows waiting to go out (new and reviewed, not pushed yet), in the list's order. A call writes at most 24 steps: 24 people for one step to write, 12 for two, and so on.
- Returns `{ list: { id, name }, spec: { vendor, mode, name, steps }, rows: [{ key, name, steps: [{ stepId, subject, body, ai, error }] }], total, offset, nextOffset, missing }`. `error` is set on a step that was not written for that person; page with `offset` while `nextOffset` is there; `missing` names `keys` that are not on the list waiting to go out (keys match as row writes do: case and spaces ignored).
- The people are written in parallel, so a call takes about one model answer (10 to 60 seconds). Not retried by the server: calling again writes again.
- 1,000 written steps per workspace per day (a person on a one-step write is one); a step the writer was asked for counts even when its answer could not be used. Each call is recorded under your name.
- Errors: 400 `bad_channel`, 400 `bad_mode`, 400 `no_instruction`, 400 `bad_spec` (with the reason), 400 `too_many_keys`, 404 `not_enabled` (Sequences is off in the workspace), 404 `list_not_found`, 404 `rows_not_found`, 409 `no_rows`, 409 `no_model`, 429 `copy_cap` (with what is left today).

### POST /api/v1/:ws/copy/draft

A sequence drafted from the workspace's best past campaigns of that channel (reply rates and words) and its Business Logic: steps, waits, subjects, fixed words with merge fields, and the steps to write per person. Nothing is made.

- Body: `channel` (`linkedin` or `email`), `mode` (LinkedIn only: `connect`, `message` or `inmail`; default `message`), `listId` (optional: its columns become the merge fields the draft may use), `goal` (optional, what the sequence is for).
- Returns `{ spec: { vendor, mode, name, steps: [{ id, kind, waitDays, subject, body, ai: { instruction } }], settings }, basis }`; `basis` names the past campaigns it learned from and their reply rates. Pass `spec` to `POST /api/v1/:ws/lists/:listId/copy` to write it for a list's people.
- 50 drafts per workspace per day; each call is recorded under your name.
- Errors: 400 `bad_channel`, 400 `bad_mode`, 404 `not_enabled`, 404 `list_not_found`, 409 `no_model`, 429 `copy_cap`, 502 `magic_failed`.

## Integrations

### GET /api/v1/:ws/integrations

- Returns `{ connections: { "<int_id>": { status, mode, account, verifiedAt, ... } } }`. Credentials never appear.
- A connection can be `connected` and still read nothing. What is wrong is on it: `health` (`{ state: "broken", cause }` from the daily check), `check.error` (a stored key the vendor refused), `sync.lastError` (the last failed read) and `sync.refused` (object types the credential may not read, each with the vendor's sentence, for example a missing Attio scope).

### GET /api/v1/:ws/integrations/:id/spec

What connecting a vendor takes.

- Returns `{ id, mode, fields: [{ key, label, hint, placeholder, optional }], setupSteps, docsUrl, oauth, nango }`. `hint` is where in the vendor's app the value lives. `oauth` or `nango` with `available: true` means the vendor signs in on the Integrations page instead.

### POST /api/v1/:ws/integrations/:id/connect

Connects a vendor with an API key or fields; the key is checked with the vendor first.

- Body: `{ fields: { "<name>": "<value>" } }` (for most vendors, `{ "api_key": "..." }`).
- Returns `{ ok: true, mode, account }`; webhook vendors add `webhookUrl` and `setupSteps`.
- Errors: `{ ok: false, error: "<sentence>" }` with 400 (missing fields), 422 (the vendor rejected the key), 501 (connect this one in the app: it signs in with OAuth).

### POST /api/v1/:ws/integrations/:id/disconnect

- Returns `{ ok: true }` (idempotent).

### GET /api/v1/:ws/slack/project-pings

Where the workspace's own Slack hears that a project finished while the people who had it open were away: a project whose work settled after a person last had it open, posted once as the Frontrunner app with those people mentioned.

- Returns `{ enabled, flag, channel: { id, name } | null }`. `enabled` holds when the `slack_project_pings` flag (an operator's, in the admin panel) and a channel both do.

### POST /api/v1/:ws/slack/project-pings

- Body: `{ channel }`, a channel id (`C...`) or `#name` the Frontrunner app can see in the workspace's Slack; `{ channel: null }` stops the pings. With `test: true` the app posts one line into the channel as it is set.
- Returns the same shape as GET, plus `test: { ok, ts }` when asked.
- Errors: 400 `channel_required`, 404 `channel_not_found` (check the name, or add the app to the channel if it is private), 409 `slack_not_connected`, 409 `channel_archived`, 409 `app_not_in_channel` (a private channel the app has not been added to), 502 `slack_error` (Slack refused to look: `detail` carries what it said, such as `missing_scope`).

### GET /api/v1/:ws/webhooks

- Returns `{ webhooks: [{ source, label, vendor, url, detail }] }`: the URLs to paste into each vendor that sends events to Frontrunner.
