# ScriptGrain API (v1)

Programmatic access to ScriptGrain: build voice profiles, generate drafts in a measured voice, and score text against a profile, with the same quality pipeline as the in-app editor.

Available on every plan, including Free. Generations consume the same credit pool as the in-app flow; there is no separate API quota. A Free account can mint a key, browse its profile, and use the free endpoints, but generation needs a paid plan's credits.

## Auth

Mint an API key in the dashboard: Settings -> API (https://scriptgrain.com/settings?tab=api). The secret (sg_live_...) is shown once, at creation.

Send it on every request:

```
Authorization: Bearer sg_live_<your-secret>
```

## Base URL

```
https://auth.scriptgrain.com/functions/v1/api-v1
```

All endpoint paths below are relative to that base.

## Machine-readable description

The same API as an OpenAPI 3.1 document: https://scriptgrain.com/openapi.json (also https://scriptgrain.com/openapi.yaml). It lists every endpoint with request and response schemas, error codes, credit costs and rate limits, and is checked against the server's router on every build. Load it into Postman, Insomnia, a client generator or an agent's tool loader. `/.well-known/api-catalog` lists it for discovery.

## Endpoints

Profiles:

- `POST /v1/profiles` creates a voice profile from writing samples and starts the extraction (uses one extraction slot, same caps as in-app)
- `GET /v1/profiles` lists your profiles
- `GET /v1/profiles/{id}` returns status and progress while extracting, then the narrative and all 45 measured attributes, plus `company_id` (the voice's default company, or null)

Writing:

- `POST /v1/outlines` generates an outline from a brief (free)
- `POST /v1/generations` generates a draft, either one-shot (`profile_id` + `brief` + `content_type`) or from an approved outline (`generation_id`). Up to 15,000 words (`word_count_target`, within the content type's range). Credits by length, per produced variant: up to 5,000 words 1 credit, up to 10,000 words 2, up to 15,000 words 3. `variants` 1-3 (2 and 3 only up to 4,000 words), optional SSE streaming with `stream: true`. Every draft returns a measured `voice_match_score` and word-count self-report.
- Drafts over 4,000 words are written in the background: the call answers `202` with `{ id, status: "generating", job, poll }` (with or without `stream: true`); poll `GET /v1/generations/{id}` or `GET /v1/jobs/{id}` until the job has succeeded, about a minute per 2,000 words
- `POST /v1/polish` revises a draft toward a voice-match target using the measured feature deltas, best-of tracked (free skip if the draft already passes)
- `POST /v1/humanize` rewrites text, or a generation's draft by `generation_id`, to reduce AI tells while keeping its structure, tone and facts (no voice profile; polish is the voice step) (free skip up to 3,000 words)
- Polish and humanise cost 1 credit up to 5,000 words, 2 up to 10,000, 3 up to 15,000. Over 3,000 words they run in the background and answer `202` with `{ status: "processing", job, poll }`; the text arrives in the job's `result`
- `GET /v1/jobs/{id}` reads a background job: status, sections done, words written, credits charged, and the `result` once it has succeeded (free)
- `POST /v1/jobs/{id}/cancel` stops a job before its next section; what was delivered is kept and charged by its tier (never above the tier asked for, nothing if nothing was delivered)
- `POST /v1/generations/{id}/edit` saves your final edit back (free; feeds closed-loop voice learning)
- `GET /v1/generations` and `GET /v1/generations/{id}` list and fetch history (status `generating` while a long draft is being written)
- `GET /v1/generations/{id}/versions` lists a draft's earlier texts (every edit, polish, humanise or redraft keeps the text it replaced, newest 50); `POST /v1/generations/{id}/versions/{version_id}/restore` puts one back, and the text it replaces is kept too (free)

Brief templates (all plans, free):

- `GET /v1/brief-templates` lists your saved briefs plus any shared with the key's team; `POST /v1/brief-templates` saves one (`name`, `content_type`, and any of `topic`, `angle`, `audience`, `register`, `key_points`, `extra_direction`, `word_count`; `share_with_team` on a team key); `DELETE /v1/brief-templates/{id}` removes one (the author, or a team owner or admin)
- `template_id` on `POST /v1/outlines` and a one-shot `POST /v1/generations` starts from a template: it fills every field the request leaves empty, and a `brief` you send becomes the topic line

Scoring and analysis (all free):

- `POST /v1/voice-match` scores any text against a profile, returning the score and per-feature deltas
- `POST /v1/compare-voice` scores up to three pieces (text or URL) against a main piece with no profile: the off-voice check, with per-feature differences

Voice Brain memory (all plans):

- `GET /v1/profiles/{id}/memory` lists the ideas, claims, stories, frameworks and topics the profile's writing has covered, each with a verbatim quote
- `POST /v1/profiles/{id}/memory/sync` indexes new drafts and samples (no credit)
- `POST /v1/profiles/{id}/novelty` checks a brief against the memory: repeats, established ideas, gaps and grounded angles (no credit)
- `GET /v1/profiles/{id}/next` proposes five angles to write next, each building on an established idea and filling a thin or stale topic (no credit)
- `POST /v1/profiles/{id}/memory/pieces` adds a piece (text or URL) to the memory and indexes it now; `POST .../memory/settings` sets `repeat_policy` (`avoid` or `allow`, i.e. similar content allowed)
- `POST /v1/profiles/{id}/memory/units` adds one memory stated directly (`text`, optional `kind` and `topic_id` or `topic_label`); `POST .../memory/units/{unit_id}` changes a memory's words, kind or topic, and `DELETE` on it deletes the memory; changes survive the piece being read again
- `DELETE /v1/profiles/{id}/memory/pieces/{item_id}` forgets a piece and every memory taken from it
- `GET /v1/profiles/{id}/brains` lists the brains a voice can use; `POST /v1/profiles/{id}/brain` (`{brain_id}`, or `null` for its own brain again) moves the voice to a shared brain or back
- The memory keeps itself current every half hour from your drafts, edits, samples and monitored pages
- Drafts build on the memory by default once it knows ten pieces; pass `continuity: false` to write fresh

Company context (all plans):

- `GET /v1/companies` lists the companies the account can see (name, summary, audience, facts, terminology); `POST /v1/companies` creates one from a website (paid plans), a description, or manual fields (free)
- `company_id` on `POST /v1/outlines` and one-shot `POST /v1/generations` grounds the piece in that company's facts, terminology and audience, and the prompt never invents specifics. **Omit `company_id` to use the voice's default company** (set in the app under Voice Brain, when the voice has one); **pass `null` for none**. An id that does not resolve is 404 `company_not_found`; the resolved id is stored on the generation
- `GET /v1/profiles/{id}/next` angles serve the voice's company audience and facts when it has one

Page rewrite (paid plans):

- `POST /v1/profiles/{id}/rewrite-page` rewrites a public page's copy in the profile's voice, block by block with the page's images and calls to action as context (`{url}`; 1 credit per 1,500 rewritable words, minimum 1; pages under 80 or over 6,000 rewritable words are refused)

Voice monitor (watching pages and running the check need a paid plan, `402 plan_required` otherwise):

- `GET /v1/profiles/{id}/monitor` lists the watched pages and the latest monthly run with per-page scores (any plan)
- `POST /v1/profiles/{id}/monitor/urls` watches a page (`{url, label}`); `DELETE .../urls/{urlId}` stops watching it
- `POST /v1/profiles/{id}/monitor/run` runs this month's check now (once per UTC calendar month)

AI-writing check (all plans, free):

- `POST /v1/ai-detect` runs the stylometric AI-writing check

Brand voice:

- `POST /v1/mimic` builds a brand profile from a public website's writing (1 brand-mimic credit; requires `consent: true`)

Billing (never plan-gated):

- `GET /v1/billing` plan, status, credits, renewal
- `GET /v1/billing/invoice` latest invoice with a PDF link
- `POST /v1/billing/checkout-link` (`plan`, `billing_cycle`, optional `currency`) and `POST /v1/billing/portal-link` return Stripe-hosted links; payments and plan changes always complete in the browser, never through the API

## Guest sessions (agents, no account)

An AI agent whose person has no account can start a guest session with no key: `POST /v1/guest` returns `201` with `guest_token` (an `sg_guest_` key), `claim_url`, `expires_at`, `limits` (one profile, one extraction, no drafts), and a `next` hint and `note`. With `Authorization: Bearer sg_guest_...` the agent may call only `GET /v1/guest`, `GET` and `POST /v1/profiles`, `GET /v1/profiles/{id}`, `POST /v1/voice-match` and `POST /v1/compare-voice` (5 free checks an hour per network); anything else is `403 guest_not_allowed`. One profile, from at most 25,000 words (a second is `403 guest_profile_limit`). Every guest response carries `claim_url` and `expires_at`: give the person the link, where they keep the profile in a free account or delete it.

Limits: 3 sessions a day per network (`429 rate_limited`), a global daily cap and an off switch (`503 guest_unavailable`). A session lasts 7 days, then answers `401 guest_expired` and is archived (kept, so the link still claims it). After a claim the key answers `401 guest_claimed`. MCP clients can use the keyless endpoint `https://mcp.scriptgrain.com/try` instead.

## Behaviour worth knowing

- Rate limit: 60 requests/minute per key (429 `rate_limited` beyond it).
- Credits deduct only after a variant generates successfully; failures cost nothing. Outlines are free. A background job charges as the words are delivered, and the wallet must hold the job's whole tier before it starts (402 `out_of_credits` with `credits_required` otherwise).
- `POST /v1/generations` supports an `Idempotency-Key` header (not with `stream: true`, except when the request itself, or its brief template, sets `word_count_target` over 4,000): retries with the same key replay the stored response instead of generating and charging again, and a long draft's `202` replays the same job.
- Errors return `{ "error": { "code", "message" } }`; every response carries an `X-Request-Id` header to quote at support.

## MCP

The same capabilities are exposed as an MCP server for Claude and other AI assistants: see https://scriptgrain.com/docs/mcp.md

Questions: support@scriptgrain.com
