# Survkit Agent API — start here

Survkit is a survey platform. Each project holds participants, surveys
("structure"), translatable texts, sandboxed participant modules, and
files. This API lets an agent shape all of that from the outside.

## A survey is two parts — definition + module

A **survey definition** is only data: questions, atoms, scales. Participants
**never see it directly**. What a participant opens and fills in is a **module**
— a small JS app (a "bundle") that reads the definition and renders it.

So **"build a survey" is not done when you POST the definition.** It is done
when there is a survey **module** wired to it and a way to open it. Minimum to
deliver something a participant can actually fill in:

1. `POST /surveys` — the definition (questions; `*_key` refs).
2. `PUT /surveys/:id/strings` — the actual texts.
3. `POST /bundles` — upload the module's code (a survey-rendering component).
4. `POST /modules` — wire the bundle to the survey (`module_kind: "survey"`,
   `data: { survey_id }`, `code_ref: "agent-bundle:<slug>"`).
5. `POST /participants/:id/tokens` — an access link to open it.

If you stop after step 1–2, nothing is visible. See `module-sdk.md` for the
module (including the required survey-module behaviour and a worked example).

**For an ordinary survey with no design brief, `example-survey.md` is the
canonical implementation, not an example to take inspiration from.** Copy its
full module source as your starting point and change only the questions, topics
and copy — do **not** write your own, shortened or simplified renderer. Given a
design brief, follow the brief; that document still binds for the required
behaviour and the write shapes.

## Model differences as participant variables first

Most of what a brief presents as a special case is a **variable on the
participant**, not a special mechanism. Work down this table and stop at
the first row that fits — each row below the first costs module code,
analysis complexity, or both:

| What the brief describes | What it is |
| --- | --- |
| People differ (role, perspective, team, site) | a variable: `permission`, `group_name` or an attribute — split the report by it |
| One person belongs to several groups, or rates a handful of people | one **participant row per membership**; participant emails are deliberately not unique, and every row has its own group, link and invitation |
| One person fills the same instrument many times and it must sit behind ONE link | a **fill key** (`survey-definition.md`) |
| The same instrument repeats over time | a **wave** |
| The project manages THINGS, not people — assets, cases, locations, equipment, each with fields and its own audience | an **object** (`agent-api.md` "Objects"): project-owned, typed, filterable attributes, per-object access list, shared across every module — never a participant row and never a JSON blob in someone's records |

Worked example — leadership feedback with a self and an external view.
Name each group after its leader, give the leader `permission: "lead"`
and their team `"staff"`, and ship one plain survey. A report module
restricted to `lead` then filters on the caller's own `group_name` and
splits the results by `permission` — self view and external view are two
cells of one `compare` query, not two surveys. Somebody who leads a team
*and* reports to someone else is simply two participant rows. No fill
key, no extra machinery.

## Demo data: use `POST /demo/seed`, don't hand-roll it

Whenever you need data to look at — previewing a dashboard, testing stats,
demoing a report — **do not write your own seeding loop** over
`POST /participants` + `POST /data/responses`. The server has a purpose-built
generator: **one declarative `POST https://on.survkit.com/api/agent/v1/demo/seed` call** creates N
participants (distributed over attributes by weight, with `{n}`-numbered
names/emails and an optional numbering `offset` for follow-up batches) and
their per-wave responses from an answer model (means/sd per item, weighted
choices, attribute-conditioned effects), deterministic per `seed`, and
re-runnable via `replace_bucket`. Seeded participants land in bucket
`"Demo data"` unless the spec names another one, so demo cohorts stay
separated from real people. Spec + worked example: `agent-api.md`,
section "Demo-data seeding". Requires `participants.write` +
`data_raw.write`.

## People who aren't participants: use share links

If a module has to reach people who are **not** in the participant list —
a workshop room voting from their phones off a QR code, a stakeholder who
should see one result — do **not** create a participant per person, and do
**not** reshare a participant's own access link (that link is their
credential: whoever opens it acts as them).

The module mints a **share link** at runtime (`sdk.createShareLink`).
Opening it creates no participant, no session and no cookie — just a
restricted capability that acts on behalf of the participant who minted
it, limited to the grants the link names. Guest writes land in that
participant's normal record scope, stamped with a per-device actor id, so
the module's storage model doesn't change at all.

Nothing to configure by default: a module may mint links out of the box,
and a link can never carry more than the module's own
`granted_capabilities`. Links that pass on more of the creator's rights
(trees, other participants and their links, PDFs, … up to `grants: 'inherit'`)
or are held to one org unit (`scope`) need the opt-in capability
`share_links_extended`. Mechanics in `module-sdk.md` §3 "Share links";
the capability list in `agent-api.md`.

## Auth

Every request (except this guide and the docs below) needs:

```
Authorization: Bearer <agent token>
```

Tokens are minted per project in the admin UI and carry scopes of the
form `<resource>.<read|write>` — e.g. `structure.write`,
`participants.read`, `data_stats.read`. The full catalogue (25 scopes
across participants, modules/data, and settings) is in `agent-api.md`
§2. A missing scope returns 403 `agent_scope_required`.

An **account token** (minted in the account settings) has every scope on
every project of one account: name the project per request with
`X-Survkit-Project: <id or shortcode>`, and create or archive projects
via `/account/projects`. Details in `agent-api.md` §1 "Account tokens".

## First steps

1. `GET https://on.survkit.com/api/agent/v1/whoami` — verifies your token; returns the project
   (id, name, shortcode) and your scopes. Account token: `GET https://on.survkit.com/api/agent/v1/account`.
2. Download the reference docs you need (below) — don't guess endpoints.
3. Work. Base URL for everything: `https://on.survkit.com/api/agent/v1`

Participant links: token responses return absolute urls
(`https://on.survkit.com/<shortcode>/<token>`) — hand them to operators verbatim,
never ask for a domain.

## Documentation

`GET https://on.survkit.com/api/agent/v1/docs` returns this list as JSON (with byte sizes). Fetch
selectively — you rarely need all of it:

- [agent-api.md](https://on.survkit.com/api/agent/v1/docs/agent-api.md) — The REST surface itself: auth, all endpoints, scopes, error codes, content_mode semantics. Read this first.
- [survey-definition.md](https://on.survkit.com/api/agent/v1/docs/survey-definition.md) — The JSON schema for a survey's questions, atoms and scales (the data). A definition is invisible on its own — a module renders it (see module-sdk.md).
- [module-protocol.md](https://on.survkit.com/api/agent/v1/docs/module-protocol.md) — How sandboxed participant modules talk to the host shell (iframe handshake, capabilities, lifecycle). Read when building a module.
- [module-sdk.md](https://on.survkit.com/api/agent/v1/docs/module-sdk.md) — The JS SDK for participant modules — the app that ACTUALLY renders a survey (or dashboard) to participants. Read this whenever you need a visible, fillable survey; a survey without a module shows nothing.
- [example-survey.md](https://on.survkit.com/api/agent/v1/docs/example-survey.md) — A complete, ship-ready survey module: paged topic blocks, four answer types, fully data-driven copy, the whole draft/finish/reopen lifecycle, styled entirely in Tailwind utilities. Splits what is REQUIRED from what is optional. MANDATORY for an ordinary survey without a design brief: it is the canonical implementation — copy its full source, do not write your own renderer and do not ship the bare skeleton from module-sdk.md §8.
- [stats-api.md](https://on.survkit.com/api/agent/v1/docs/stats-api.md) — Aggregate statistics endpoints (k-anonymous distributions, crosstabs) available to modules and reports.
- [example-dashboard.md](https://on.survkit.com/api/agent/v1/docs/example-dashboard.md) — A complete dashboard module: k-anonymous statsBatch reporting, tree_rollup for per-unit numbers, org-tree drill-down with server-enforced per-caller visibility, a configurable sentiment table, wave-over-wave trend, XLSX export. Splits what is REQUIRED from what is optional. Reads only aggregates, never raw answers.
- [advanced-analytics.md](https://on.survkit.com/api/agent/v1/docs/advanced-analytics.md) — What sophisticated analyses are buildable (driver analysis, reliability/EFA, TURF, within-person change, offline models with write-back) and the recipe for each — 24 rows, three implementation routes. Read when a customer asks for an analysis beyond means.
- [participant-import.md](https://on.survkit.com/api/agent/v1/docs/participant-import.md) — The .xlsx format the admin UI's participant import accepts: identity + attribute columns, tree shapes, section rows (one-value rows that fill down, e.g. groups as visual blocks), auto-created values, round-trip with the export. Read when asked to produce an import file for a human to upload.
- [office-documents.md](https://on.survkit.com/api/agent/v1/docs/office-documents.md) — Two ways to produce .docx/.pptx from a module: fill the customer's own template (sdk.fillOfficeTemplate — placeholder syntax, loops per table row and per slide, images, filters, upload-once flow) or build a document from blocks without a template (sdk.createOfficeDocument — headings, tables, native PowerPoint charts, images). Read when a report must be delivered as Word or PowerPoint.
- [comment-coding.md](https://on.survkit.com/api/agent/v1/docs/comment-coding.md) — Categorise open free-text answers into an analysable scheme and play the categories back (codings, evidence, anonymity verdicts, synthetic prototypes, summary). Needs the data_coding scopes.
- [build-chat-transport.md](https://on.survkit.com/api/agent/v1/docs/build-chat-transport.md) — Only if your entry prompt sent you here: the HTTP wiring for the live chat in a project Build UI (long-poll loop, replies, preview control). Irrelevant without that connection.
- [system-strings.md](https://on.survkit.com/api/agent/v1/docs/system-strings.md) — Optional: override the built-in auth-chrome texts (login mails, verification gates) per language. Only needed when a project wants rewording or a language outside the ~20 prebuilt ones.

These docs are served by the running server, so they always match the
deployed code. Re-fetch them rather than trusting cached copies.
