# Keel: a guide for agents
Build and edit through Keel’s API. `/openapi/v1.json` has exact requests, answers, problems and examples; this guide explains access and editing.

## Network access
Keel's API and this guide are on app.keelpage.com. Previews and links open on the site's address ({slug}.keelpage.com, or its own domain once connected), so your network settings must allow both; `*.keelpage.com` covers every keelpage.com address where wildcards are accepted. Before anything else, check from the tool you'll use to send requests (for example your code tool), not only a page reader, that you can reach `https://app.keelpage.com/openapi/agent-guide.md`. If you can't, stop and tell the person: "Allow app.keelpage.com and your site's address in my network settings (in Claude: Settings → Capabilities, or ask your organisation's owner), then ask me again." Name the site's address when you know it. Don't answer with a general connection error.

## Tokens
- A token belongs to one site and has one role: `siteAdmin` or `contentCreator`. It works on that site only; any other site answers 404. Approved sessions also reach that site’s staging copy with the same role.
- An access token lasts 15 minutes. Send it as `Authorization: Bearer <token>` on every request. Never put a token in a URL, a log, a page or a commit.
- Agent access ends at `sessionExpiresAt` or after seven days without refresh; bot access ends with its registration. Neither role can exceed the one granted by the person or bot registration. The helper's own session answer lists its own site first (`kind: "own"`), then created sites (`"created"`) and staging copies (`"stagingCopy"`, with `mainSiteId`). The admin's AI helper access list still shows only created sites.
## Getting a token as an agent
A person approves with their passkey and chooses **Keep access for**, default **12 hours**; the page shows the requested length and end date. They can choose from 12 hours up to the site’s maximum (as much as 90 days) and end access at any time. Longer access requires your registered signing key. Owners set the maximum on **AI helper access**; lowering it bounds sessions from approval and ends overdue ones. People read `GET /api/sites/{siteId}/agent-sessions/maximum`. `ownerName` is the name they gave, or null when they gave none (`{ "maximumKeepHours": 168, "canChange": false, "ownerName": null }`). It never includes an email address.

With the site tool, `keel login --site SLUG --keep 30d` accepts `12h`, `7d`, `30d` or `90d`. On macOS, its EC P-256 private key stays in Keychain, never a file or output. Without Keychain signing, it explains why and requests at most twelve hours. The person still chooses the length.

1. Ask for access. No credentials needed.
```
POST /api/agent/sessions
{ "clientName": "Site builder agent", "site": "keel-qa", "role": "siteAdmin", "keepHours": 720,
  "publicKey": "(public PEM or JWK only; never your private key)" }
```
`site` is the site's id or its keelpage.com name. `role` is the most you ask for. `keepHours` is 12, 168, 720 or 2160 (omitted means 12). Register `publicKey` even for a twelve-hour request if the person may choose longer. The answer is 201:

```
{ "deviceCode": "(secret, keep in memory)", "userCode": "BCDF-GHJK", "verificationUri": "https://app.keelpage.com/agent/approve",
  "verificationUriComplete": "https://app.keelpage.com/agent/approve?code=BCDF-GHJK", "expiresIn": 600, "interval": 5, "siteId": "3d1a5c6e-0b52-4e3d-8b59-7c1e2f0a4b11" }
```
2. Show the person `verificationUriComplete` and the `userCode`. They have ten minutes.
3. Poll every `interval` seconds:

```
POST /api/agent/token
{ "grantType": "deviceCode", "deviceCode": "(the device code)" }
```
`400 authorization-pending` means keep waiting. `slow-down` means poll less often (use the new `interval`). `access-denied` and `expired-token` mean stop. When approved, the answer is 200:

```
{ "accessToken": "(15 minutes)", "tokenType": "Bearer", "expiresIn": 900, "expiresAt": "2026-10-08T10:15:00Z",
  "refreshToken": "(works once)", "sessionExpiresAt": "2026-10-08T22:00:00Z",
  "sessionId": "9a3c2d1e-5b6f-4a7c-8d9e-0f1a2b3c4d5e", "siteId": "3d1a5c6e-0b52-4e3d-8b59-7c1e2f0a4b11", "role": "siteAdmin" }
```
4. Before the access token ends, refresh:

```
POST /api/agent/token
{ "grantType": "refreshToken", "refreshToken": "(the newest one)" }
```
For sessions longer than twelve hours, add `proof: { time, id, signature }` on every refresh. Sign the UTF-8 message `POST\nabsolute-token-address\nUnix-seconds\none-time-id` with no final newline. The address must be the actual endpoint address used for this request, including scheme, host and query string. `time` is Unix seconds; `id` is a fresh random value of 16–128 ASCII letters, digits, hyphens or underscores. Use RSA SHA-256 PKCS#1 or EC P-256 SHA-256 (64-byte P1363 signature), encoded as base64url without padding. Keel stores only the public key and hashed ids. Missing or wrong proofs, proofs older than five minutes or more than thirty seconds ahead, and repeated ids end the session with an audited denial. Never retry a refresh whose outcome is uncertain.

Use only the newest refresh credential: each works once, and reuse ends the session. Device codes also work once. `GET /api/agent/session` shows only your session and the role you have right now. `POST /api/agent/session/end` ends it. People see approver, end date, last use and **End access** on **AI helper access**. Ending access stops tokens immediately. Owners/administrators receive notices for long approvals and three days before sessions of seven days or more end. Notices name the helper, approver, end date and revocation link, never a token, key or code.
## Longer access: add a signing key
1. Make an **EC P-256** key pair where the helper runs. Keep the same private half for the whole session, including after restarts; never send it to Keel, the person, logs or source control. Choose storage for that machine:
   - **Windows:** protect an exported private key with DPAPI for the current user before saving it, or keep a non-exportable key in the current user’s certificate store.
   - **Linux:** use a file only the helper’s account can read (`chmod 600`, directory `chmod 700`), or Secret Service on a desktop.
   - **macOS:** keep the private key in Keychain and sign there; do not persist an unprotected private-key file.
2. Send **only the public half** (SubjectPublicKeyInfo PEM or public JWK) as `publicKey` in a new `POST /api/agent/sessions`. Even with `keepHours: 12`, a key lets the person choose longer, within the site's maximum. A pending request cannot gain a key: ask again and show the new approval link and code.
3. On **every refresh of access approved for more than 12 hours**, sign the proof below with that private key. The signature binds the refresh to this helper; a copied refresh credential alone cannot be used elsewhere. Keep the time, one-time id, exact address and signature together in `proof`, and always use the newest refresh credential.

Without a key, the 201 and pending poll answers include `signingKeyNote` and `signingKeyGuideUri` pointing here. The person can approve at most 12 hours. Longer requests without a key are refused with this same guide address.

C# (.NET `ECDsa`): the same cross-platform .NET API works on Windows, Linux and macOS. `nistP256` makes an EC P-256 key; `SignData` defaults to a 64-byte IEEE P1363 signature. The example holds the private key in memory; connect the protected store above for restarts, and never make a new key for each refresh.
```csharp
using System.Globalization;
using System.Security.Cryptography;
using System.Text;

public static class HelperSigning {
    public sealed record Proof(long Time, string Id, string Signature);
    public static ECDsa CreateKey() => ECDsa.Create(ECCurve.NamedCurves.nistP256);
    public static string PublicKey(ECDsa key) => key.ExportSubjectPublicKeyInfoPem();
    public static Proof Sign(ECDsa key, string tokenAddress, long time) {
        var id = Guid.NewGuid().ToString("N");
        var message = $"POST\n{tokenAddress}\n{time.ToString(CultureInfo.InvariantCulture)}\n{id}";
        var bytes = key.SignData(Encoding.UTF8.GetBytes(message), HashAlgorithmName.SHA256);
        var signature = Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
        return new Proof(time, id, signature);
    }
}
```
```csharp
using var key = HelperSigning.CreateKey(); // Once per session; send HelperSigning.PublicKey(key) in the new session request.
var proof = HelperSigning.Sign(key, "https://app.keelpage.com/api/agent/token", DateTimeOffset.UtcNow.ToUnixTimeSeconds());
// POST camelCase JSON { grantType: "refreshToken", refreshToken: newestRefreshToken, proof } to that exact address; keep the new refreshToken.
```
Command line (`openssl`, Python 3, POSIX shell): works on Linux and macOS; on Windows use WSL with Linux storage, or the native C# path above with DPAPI/certificate storage. Set the site and exact token address for your server. This file-based example is suitable for Linux (`umask 077` gives owner-only access); on macOS use it only for a temporary check, delete the temporary private file afterwards, and use Keychain for persistent sessions.
```sh
umask 077
mkdir -m 700 helper-keys
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -pkeyopt ec_param_enc:named_curve -out helper-keys/private.pem
openssl pkey -in helper-keys/private.pem -pubout -out helper-keys/public.pem
python3 -c 'import json,pathlib; pathlib.Path("session-request.json").write_text(json.dumps({"clientName":"Site helper","site":"keel-qa","role":"contentCreator","keepHours":168,"publicKey":pathlib.Path("helper-keys/public.pem").read_text()}))'
# POST session-request.json to /api/agent/sessions, then show the returned approval link and poll.
address='https://app.keelpage.com/api/agent/token'
address=${TOKEN_ADDRESS:-$address}
time=$(date +%s)
id=$(openssl rand -hex 16)
printf 'POST\n%s\n%s\n%s' "$address" "$time" "$id" > helper-keys/message
openssl dgst -sha256 -sign helper-keys/private.pem -out helper-keys/signature.der helper-keys/message
python3 - "$time" "$id" <<'PYPROOF'
import base64, json, pathlib, sys
b = pathlib.Path("helper-keys/signature.der").read_bytes()
# OpenSSL emits DER integers r,s; Keel needs each as 32 bytes, concatenated (P1363).
n = b[3]; offset = 4 + n
r = int.from_bytes(b[4:offset], "big").to_bytes(32, "big")
s = int.from_bytes(b[offset + 2:offset + 2 + b[offset + 1]], "big").to_bytes(32, "big")
signature = base64.urlsafe_b64encode(r + s).decode().rstrip("=")
pathlib.Path("helper-keys/proof.json").write_text(json.dumps({"time":int(sys.argv[1]),"id":sys.argv[2],"signature":signature}))
PYPROOF
```
Put the contents of `proof.json` under `proof` in `{ grantType: "refreshToken", refreshToken: newestRefreshToken, proof }` and POST to exactly `$address`. Repeat signing with a fresh time and id for each refresh. There is **no final newline** in the signed message. Send JSON with numeric `time` (Unix seconds), a fresh 16–128 character ASCII letter/digit/hyphen/underscore `id`, and base64url `signature` without padding. EC signatures must be **P1363, not OpenSSL's DER**. Proofs older than five minutes, more than thirty seconds ahead, missing, invalid, or using a repeated id end the session with an audited denial. Never retry a refresh whose outcome is uncertain; credential reuse also ends access. Tokens remain 15 minutes, access stays within the site maximum, and seven days without refresh ends it.

## Getting a token as a bot
A system administrator registers the bot with a public key (or a managed identity). Then, every time a token is needed:

```
POST /api/bot/token
{ "botId": "3d1a5c6e-0b52-4e3d-8b59-7c1e2f0a4b11", "assertionType": "privateKeyJwt", "assertion": "(a JWT signed with the bot's private key)" }
```
The JWT has `iss` and `sub` set to the bot's id, `aud` set to the token endpoint, `exp` at most five minutes ahead and a fresh random `jti` (each is single use). Sign it with the algorithm of the registered key (`ES256` or `RS256`). With `"assertionType": "managedIdentity"` the assertion is the platform identity's access token. The answer holds an `accessToken`, `expiresAt`, `siteId` and `role`. Every refusal is the same 401, whatever the cause. A bot that goes over its hourly action cap is paused (403 `bot-paused`) until a person resumes it.

## Connectors
Claude, ChatGPT, Grok and Grok Bot can also connect as a connector: the person adds `https://app.keelpage.com/mcp` in the helper's connector settings, signs in to Keel with an email link or a passkey, picks the site and the role and approves with their passkey. Keel is the OAuth authorization server (discovery at `/.well-known/oauth-protected-resource`), so there is no device code to show. A connection works on one site for at most 12 hours, and **End access** on **AI helper access**, where it's listed as "Claude connector" (or ChatGPT, Grok), stops it at once. It has five tools: `keel_connection` (call it first: the site, your role, when it ends), `read_guide` (this guide's sections as topics), `find_api` (matching operations, never the whole description), and `keel_get` and `keel_change`, which call Keel's own API on that site with the same checks, problems and activity history. For example, `keel_get` with `{ "path": "/api/sites/{siteId}/pages" }` lists the pages; `keel_change` sends a POST, PUT, PATCH or DELETE the same way, with `ifMatch` (the ETag you last read) on updates. Another site's paths, system addresses and media uploads are refused.

## Native parts and forms

- Forms offer a Web address question: `{"name":"website","type":"url","label":"Current site address","required":true}` inside `fields`. The Forms editor, form preview, page Preview and Live keep `type=url` and `inputmode=url`, with `autocomplete=url` by default. Omit `required` or use false for an optional question. The server accepts HTTP(S) addresses and normalizes a bare dotted host to HTTPS; other non-empty answers return 400 with `fields.website`. Empty required answers also return 400 naming that field. To remove the question, send the complete remaining `fields` list with `If-Match` through `PUT /forms/{id}` (or the versioned design document). The editor uses Remove question.
- Forms offer Checkboxes (pick any): `{"name":"services","type":"checkboxes","label":"Services","required":true,"options":[{"value":"business","label":"Business"},{"value":"it","label":"IT"}]}` inside `fields`. Visitors tick any of the options. A submission stores the ticked values as a list in option order. None ticked on a required question, or a value that is not an option, returns 400 naming that field. The inbox preview includes every answered visible question, including `Services: business, it` and later questions such as Your name; each labelled answer is capped at 140 characters with `…` when shortened, and the detail and CSV keep complete answers and the same option values. Notification HTML and text show one option per line. A JSON array or repeated multipart/URL-encoded name for any other field returns 400 naming `fields.{name}`. The editor uses the same Choices list as choose-one. An unknown member of the field is still rejected.
- Forms accept `type: "date"`, inclusive `earliestDate`/`latestDate` in `yyyy-mm-dd`, and `noPastDates` in the site's time zone. The server refuses impossible days, timestamps and out-of-range answers. Submissions keep the ISO day; inbox `formattedDate` and CSV `{name} (site date)` use the site's locale.
- Heading data is `{ "text": "Order & collect", "level": 2, "anchor": "order" }`; optional `html` keeps only `em` (`i` becomes `em`), has no attributes, derives the plain `text` and is omitted when emphasis is gone. Any other element, attribute or comment is refused with 400 at `data.html`, for example `{ "html": "<strong>Order</strong> & collect" }` returns "Headings keep only words and italics (<em> or <i>), so <strong> isn't kept."; use a Text part for other formatting. The 300-character limit counts words. Optional anchors start with an ASCII letter, then letters, digits, hyphens or underscores, up to 64 characters. They must be unique across Columns and cleaned Text/HTML IDs. Omitted/empty anchors add no ID. Button `href: "#order"` links here; `href: "/visit#order"` links to a published heading on another page.
- Quote is `type: "quote"`, with `data: { "text": "Lovely bread", "name": "Sam", "role": "Customer" }`. Text is required (4,000 characters, line breaks kept); Name and Role are optional (200 each). Empty attribution is omitted; a role alone has no leading comma. All are encoded plain words. Existing rich-text blockquotes keep their markup.
- Cards is `type: "cards"`, with `data: { "columns": 3, "cards": [{ "mediaId": "<site-media-uuid>", "title": "Fresh bread", "text": "Baked today", "alt": "Bread on a plate", "link": "/menu#bread" }] }`. Each of 1–30 cards needs a title (200 characters); its optional library picture ID must be tenant-verified. Optional text allows 1,000 characters with line breaks; alt allows 300. Omitted/null alt inherits the file's description; `alt: ""` is decorative. Optional title links follow Button rules. Columns are 2, 3 or 4 (default 3), stacking below 768px. Picture replacements, responsive variants and alt fallback apply; missing media keeps words. `/_keel/content-parts.css` loads once; style the hooks below and `--cards-gap`. No inline styles or scripts are added.
- Allow Quote/Cards in the region's `allowedBlockTypes`; Columns accepts both. OpenAPI describes their data shapes. Native parts retain history, snapshot media references, markup/count limits, search and publish/purge behavior. Text parts and paste keep `details`, `summary` and `open`. The visual editor keeps the disclosure and its saved open state through answer edits. Example Text HTML: `<details><summary>Q</summary>A</details>`. HTML parts also keep `name` on `details` for one-open accordions. Form controls and active content stay out. Line breaks and tabs in one-line words become a space. All visitor links use one rule: `https://`, `http://`, `mailto:`, `tel:`, a path on this site or an `#anchor`; an anchor stays in its preview. Collection URL fields retain their own rule. Search example: `{ "id": "site-search", "type": "search", "data": { "label": "Search this site", "placeholder": "What are you looking for?", "buttonText": "Search" } }`. Only these three data keys are accepted. Omitted fields use these server defaults; null, wrong types, unknown keys, empty label/button wording and excessive lengths return field errors. Placeholder may be empty; plain text is normalized and encoded. Read defaults and configurable limits from `layout.partChoices.search`. The labelled native GET form targets `/_search` on the site host, with unique input ids and external part styles, no script. Search uses live published public pages, public collection items and first list pages; excludes drafts, unpublished/deleted, private and noindex content. Results are uncached and paged; empty query, no results and too-long query each give a message. Draft previews submit to the live set and explain **Search works once the site is published**. Allow `search` in page/Header/Footer region lists; Columns accepts it. Region content belongs to each page. For one shared header/footer box, put `{% search '{}' %}` in Layouts > Code or an included shared design part; the JSON argument accepts the same three fields, e.g. `{% search '{"label":"Find harbour","placeholder":"","buttonText":"Go"}' %}`. Save and publish the layout/shared part; remove the tag to remove the box. Existing restrictive lists remain unchanged. See the pages/rendering guide and Help for the full example.
- `POST /api/sites/{siteId}/pages/{pageId}/duplicate` with the source's `If-Match` and `{ "title": "Menu copy", "slug": "menu-copy", "parentPageId": null }` copies saved parts, layout and SEO into a draft. Use a new nonempty address, even for a homepage. The source stays unchanged; children, history, live state/dates and schedules are not copied. Normal parent/address/layout/raw-HTML permissions and the people-only Mailchimp destination rule apply.
- `POST /api/sites/{siteId}/pages/{pageId}/paste-content` with `{ "regionKey": "main", "html": "<h2>Menu</h2><p>Bread</p>" }` returns `{ "parts": [...], "omissions": [...] }` without saving or publishing. Headings keep words and inline italics without IDs; paragraphs/lists/emphasis/safe links become Text; tenant-verified library pictures keep alt intent and safe links. Styles, scripts, forms, unsafe embeds, tables, code, rules, unavailable pictures and disallowed types are omitted and reported. Upload external pictures first. Review omissions, append parts, then save through the normal page PUT with `If-Match`; combined anchors, part/markup limits and permissions still apply. The admin offers review and Undo. Word and Google Docs bold and italic are converted to `<strong>` and `<em>` before styles are removed. Docs’ normal-weight `<b id="docs-internal-guid-…">` wrapper is removed, so the whole paste does not become bold. For example, `<span style="font-weight:700">Bold</span>` becomes `<strong>Bold</strong>`.

## The loop

1. `GET /api/sites` lists your reachable original and staging copy. Note their `id` values.
2. `GET /api/sites/{siteId}/design` returns the whole design as one JSON document, with an `ETag` and a `version` member: theme, partials, layouts, menus, globals, collections, forms, redirects and SEO settings.
3. Read before writing, then change what you need; keep documents focused and leave untouched members out. One `PUT /design` is one audit event and purge. Never invent credentials or addresses.
4. `PUT /api/sites/{siteId}/design` with the changed document and `If-Match: <the ETag you read>`. The answer lists the changes (the first 200; `truncated` is true when there were more), whether each is live or a draft, and the document's new version:

```
{ "version": "d1-Q2bT0mXk8m3N2s0wJ1pQxg", "unchanged": 0, "truncated": false,
  "changes": [ { "kind": "layout", "key": "homepage", "change": "created", "live": false, "draftVersion": 1 } ] }
```
5. Publish what you saved as drafts: `GET /api/sites/{siteId}/design/changes?check=true` adds `warnings` from the existing bounded publish checks, including real-page main-heading advice, without publishing; check problems or limits are warnings alongside the list. Omit `check` for the metadata list. `GET /api/sites/{siteId}/design/changes` lists every unpublished layout, partial, theme, menu and globals change (and the live pages each layout or partial affects). `POST /api/sites/{siteId}/design/publish` takes nonempty `items` from that list (`kind`, `id`, `version`) and publishes every reviewed change together, all or nothing. Missing/empty items is 400 `validation`; a matching subset is 409 `design-review-incomplete`: its `detail` gives both counts and names each missing change (kind, name, id) and `current` holds the whole list, so send every item again; to publish one change on its own, use its own publish request instead (`POST /api/sites/{siteId}/theme/publish` for the theme); changed versions are 409 `stale` with `current`.

   For partials, `affectedPages` follows literal and nested includes across the public design and reviewed drafts. A dynamic include counts every live page. Unreadable templates or checking limits also conservatively count every live page. Draft-only, deleted and not-found pages are excluded. `affectedPageCount` is the full total; `affectedPages` lists up to 50 in path order. Example: a footer included by the About layout reports `affectedPageCount: 2`, with paths `/about` and `/about/team`. Main-heading warnings use real saved page drafts and live page snapshots, including their regions and nested parts, and name the page and checked content. A sample page never supplies the heading warning.

6. Check your work with `GET /api/sites/{siteId}/status` until nothing waits to be published and no problem is listed.
### How the document works

- Omitted members stay unchanged; send each named entry whole. Layouts, partials, menus, collections and forms use `key`; redirects use `source`; theme and globals have one entry each.
- Members that only `GET` fills in (`id`, `status`, `publishedVersion`, `hasUnpublishedChanges`, item counts, `webhookConfigured`) are ignored on `PUT`, so you can send back a document you read.
- To remove something, list it in `delete`: `menus`, `forms`, `collections` and `redirects` by key or source, and `globalsValues` by key. Nothing else can be deleted.
- Apart from independent redirect rows, a refusal saves nothing: 400 `validation` for bad fields, or 409 `design-document-refused` with `problems`, each naming a `path` (such as `layouts[2].source`), problem `type` and explanation.
- `If-Match` is required (428 `precondition-required` without it). If the design changed since you read it, you get 409 `stale` with the current document in `current`. Merge your change into it and send again.
- The same document sent twice changes nothing the second time (`unchanged` counts it).
- Redirects match whatever the capital letters. Keel stores sources in lower case without a trailing slash. Answers show the source sent and the stored source when they differ. A second rule with the same source and destination is already covered; a different destination is refused and names the other rule. `/About/` to `/about` needs no rule: Keel already makes that change. `/About.html` and `/About/index.html` to `/about` are separate old addresses and can be saved. Rules that need no change and refused rules do not prevent the other valid rules from being saved. Read `notices` and `refused` in a bulk answer, including a successful one.
- An exact redirect can match an old WordPress query address: `{ "source": "/?page_id=126", "destination": "/about", "match": "exact" }` (also `/?p=55`). Only the path is normalized; the whole query matches exactly, including case, order and encoding. Extra values do not match. A query rule wins over path rules, consumes that query and can match home without hiding its ordinary address. A destination can set a new query; path-only rules still carry the visitor's query. Prefix sources cannot carry queries. Loop, chain and platform-address checks still apply.

### Drafts and what goes live at once

- Drafts (not visible to visitors until you publish): the theme, partials, layouts, menus, globals and pages.
- Live as soon as the request succeeds: collection definitions, forms, redirects, SEO settings, a layout's `isDefault`, and every `delete`.
- A draft never changes the live site. Use a preview to see it first. Every draft design save runs publish's checks. A problem in the saved source is refused with publish's message; a problem that depends on another draft is listed in `warnings` while the draft is saved. `showPageTitle` is a layout setting, on by default: Keel supplies a title heading at the start of `main` when the page has no Level 1 Heading. It never puts that heading after `body`. Turn it off in the layout's settings when the design supplies its own heading. This setting stays a Draft until the layout is Published and is kept in versions and restore. Keel supplies a missing head title from the meta title, else the page title. An authored head title stays; an SVG title does not count. Previews have the same additions and first-party SEO fields as Live (title, description, canonical, Open Graph, Twitter and JSON-LD), plus noindex. Canonical and og:url point to the live page address; analytics and integrations never run on previews. Forms show where the security check runs on the published page and never send.

## Pages, media, previews
- `GET /api/sites/{siteId}/pages/deleted` gives deleted pages and their `version`. Restore via `POST /api/sites/{siteId}/pages/{pageId}/bring-back`, `If-Match: "<version>"`, body `{ "slug": "team-restored" }` to use a new address if taken; restore deleted parents first. Returns the new path as a draft. SiteAdmin bots, agents and people can `POST /api/sites/{siteId}/pages/deleted/permanent` with `{ "pages": [{ "id": "<pageId>", "version": "<version>" }], "cascade": true }`: includes deleted descendants, refuses live descendants, missing/stale versions or another site's pages atomically. A missing `pages[].version` is 428 `precondition-required` naming that body field, not the If-Match header. A page that is not deleted refuses the whole request and the message names that page by title and address; nothing is removed. `deletedBy` is the AI helper's name when a helper deleted the page (the same name Activity shows) and the person's email when a person deleted it. Omit cascade to require all descendants explicitly. One audit event and transactional cache purge; permanent deletion cannot be undone.
- `GET /api/sites/{siteId}/pages/by-slug?path=/about` reads by path (`/`: home). Page PUTs accept `isNotFoundPage`: omitted keeps it, true chooses/clears the previous choice, false clears. Home/collection-list owners are refused by field. An unpublished choice carries a built-in-until-published notice. Deletion clears it; bring-back does not reclaim it. Imports use this upsert; backups keep it. Creators, bots and agents may set it; If-Match, one audit and transactional not-found purges apply.
- `PUT /api/sites/{siteId}/pages/by-slug` creates or updates a draft by path:

```
{ "path": "/about", "title": "About us", "layoutKey": "homepage", "regions": { "main": [ { "type": "richText", "data": { "html": "<p>Hello.</p>" } } ] } }
```
  Creating answers 201 with `{ "created": true, "page": { ... } }`, a `Location` for the page and its `ETag`. Updating answers 200 with `{ "created": false, "page": { ... } }` and the current `ETag`, with no `Location`. Updating an existing page needs `If-Match` with the page's latest `ETag`: omission returns 428 `precondition-required`, and an old version returns 409 `stale` with `current`. The parent path must exist. Every submitted region key must belong to the page's layout; a wrong key returns 400 naming the regions it takes, with nothing saved. Removing populated layout regions (upsert, design document or layout version restore) returns 409 `layout-regions-affected` with `errors.drop` keys and `current.affected` page, item and part counts and first 50 names with addresses per kind. Review them; resend the same schema with every affected key in `drop` to confirm. Backup restores into existing drafts also refuse populated-region removal; confirm through the layout writer before repeating the restore. Copies start empty; Promote and Switch back replace reviewed content and design together. `drop` is never stored or returned by GET /design; the confirmed answer reports `partsWithoutPlace`. Parts stay under Content without a place and stop rendering on publish. A layout change keeps existing content outside its regions as `orphanedRegions`. Later saves keep that content without resending those keys; `PUT /pages/{pageId}` can explicitly remove it with `dropOrphanedRegions: ["old-region"]`.
- Layouts and partials saved by key, and theme saves, answer with the resource itself: 201 with `Location` when created, or 200 with no `Location` when updated. Both return the current `ETag`.
- Page and collection slugs use lowercase letters, numbers, hyphens and underscores (`about_us`, `photo_galleries`), with single hyphens between words; write requests refuse capitals and surrounding or internal whitespace with 400 naming `slug` (or `path` for page upsert); input is never silently rewritten. For example, `About_Us`, ` about_us ` and `about us` are refused; send `about_us` explicitly. Page upserts require canonical paths (`/about_us`, without a trailing slash). Read lookups and legacy redirect matching retain their normalization. Collection slugs may have several page-slug parts (`de/photo_galleries`), up to 9 parts and 699 characters; the first cannot be reserved. Collections cannot nest; a page may own the list at any depth. `collection.url` and `item.collection.url` give the full list address. Prefix redirects cannot hide served lists, feeds or items. Year archives such as `/de/news/2023` are numbered list pages: import an exact old address link to a query-style list; path-style lists hold that address. Dated item slugs work; filtered year lists are not built.
- `GET /api/sites/{siteId}/collections/{key}/items/by-slug?slug=example` reads an item's current `ETag`. `PUT /api/sites/{siteId}/collections/{key}/items/by-slug` creates a draft for a new slug without `If-Match`. For an existing slug, send `If-Match: <latest ETag>`: omission returns 428 `precondition-required`, and an old version returns 409 `stale` with `current`. The successful update returns the new `ETag` for the next write. Send only regions the item layout defines. Content kept after a layout change remains saved without resending its keys; `PUT /collections/{key}/items/{itemId}` can explicitly remove it with `dropOrphanedRegions: ["old-region"]`.
- A decorative section background needs no new setting: use `{ "type": "image", "data": { "mediaId": "<image id>", "decorative": true } }`; it loads eagerly even far down the page. Existing `loading: "eager"` also works; `loading: "lazy"` keeps an explicit lazy choice.
- `POST /api/sites/{siteId}/pages/{pageId}/publish` makes the draft live. `POST /api/sites/{siteId}/pages/{pageId}/unpublish` takes it down.
- `POST /api/sites/{siteId}/preview` with `{ "pageId": "..." }` returns a signed address of the draft, good for 12 hours. A draft or preview keeps its complete draft address, including draft parents. `page.path` is the full path at every supported depth (for example `/en/meet-us`), without a trailing slash except `/`; `page.url` applies the site’s trailing-slash rule to that full path. Live uses the published path; previews use the draft path, never the signed preview address. API page `path` and `publishedPath` give the full draft and live paths. Both template values remain available inside `{% include %}`, `{% render %}`, region wrappers and navigation loops, and on collection item and list pages. A child of a never-published parent can be previewed at its full draft path; publishing it requires publishing its parent first. `page.url`, `page.path`, canonical, `og:url`, breadcrumbs built from those values, `redirectOnPublish` and the editor agree about that address. `POST /api/sites/{siteId}/collections/{key}/items/{itemId}/preview` with `{}` returns a signed draft address for that item, on a Coming soon site as well as a Live one. It follows the same rule as a page preview. `editMode: true` is people-only. While a site is Coming soon, visitors still see its Coming soon page at 403 (the same page, noindex, no-store, no Retry-After). An image address that exists is plain 403, never that page. A site administrator checks a saved redirect first: `POST /api/sites/{siteId}/launch-check` with `{ "path": "/old", "hours": 1 }`. GET or HEAD the returned `url`. A saved 301 answers 301, and `Location` is the destination (for example `/new`). `Location` does not include the check. A preview request needs a User-Agent header, for example `curl -A 'Keel import' 'https://example.keelpage.com/_preview/...'`. Images lazy-load, so a headless screenshot must scroll the page or force eager loading: `{ "type": "image", "data": { "mediaId": "<id>", "loading": "eager" } }`.
- Media: `POST /api/sites/{siteId}/media/uploads` with `{ "fileName": "photo.png", "contentType": "image/png", "size": 67, "altText": "A loaf", "caption": "Cooling" }` (`size` is the file's exact byte count) returns 201 `{ "asset": { "id": "<id>" }, "upload": { "url": "<put address>", "method": "PUT", "headers": { "x-ms-blob-type": "BlockBlob" } } }`. PUT the file bytes to `upload.url` with `upload.method` and every `upload.headers`, and no API token. `{id}` is `asset.id`. Then `POST /api/sites/{siteId}/media/{id}/complete` with no body. To set alt text afterwards, `PATCH /api/sites/{siteId}/media/{id}` `{ "altText": "A loaf" }` with `If-Match: <asset.version from complete>`; that version stays good while Keel makes the image's web sizes, until someone else edits the file (then 409 `stale` with `current`). `GET /api/sites/{siteId}/media` lists what is there. Each successful row write returns its new version as `ETag`, including upload start, completion and retry; use that token for the next update. Give every image alt text. The supplied alt text and caption survive completion and processing. Use the ETag returned by `/complete` for a following PATCH. Processing changes the version once. If processing wins, PATCH returns 409 with `current`; use that version when you retry. Missing `If-Match` still returns 428. Use `altText`, rather than `alt`. `{ "altText": "" }` marks a picture decorative; `{ "altText": "   " }` (only spaces) returns 400 naming `altText`.
- Field values use their declared JSON shape: a single `itemLinks` field takes one item id string, while `multiple: true` takes a list of id strings. `itemLinks.targetCollectionId` needs the target collection created first: `POST /api/sites/{siteId}/collections` with `{ "key": "people", "name": "People", "slug": "people" }`, then `PUT /api/sites/{siteId}/collections/{key}` with the author field `{ "key": "author", "type": "itemLinks", "targetCollectionId": "<people id>" }`. Shape errors name the field and what it takes.
- In an item layout, wrap an optional field and its words in a test, so an empty field leaves nothing behind: `{% if item.author != blank %}<p class="byline">By {{ item.author | escape }}</p>{% endif %}` writes no bare "By" when Author is empty.
- A write with an unknown key returns 400 and names the keys that request takes. Fixed-choice part fields name their exact accepted values; for Columns, `width` takes `equal`, `2-1` or `1-2`. There are no aliases. Unknown types name the closest one. Parts also check nested slides and cards. See each part's data schema in `/openapi/v1.json`. Slideshow (`slider`) takes `style` (pictures by default), `slides` (1 to 30), `arrows` and `dots` (true by default), `height` (pictures only), `autoplay` and `interval` (3 to 20 seconds, default 6 when autoplay is on). Slides use `heading`, `text`, `linkUrl`, `mediaId`, `alt`, `buttonLabel`, `buttonUrl`, `buttonNewTab`, `author` and `role`. `captionElement` takes `p` or `h2` to `h6`; omitted means `h2`. Use `p` for plain slide captions that do not add headings. Pictures and cards use it; quotes keep their quote markup. It saves as a page Draft and stays with published and restored versions.
- Collection list uses `{ "collection": "<collection id>", "limit": 10 }`, up to 50 items; optional order is newest (default), oldest or chosen, with 1–50 ordered item ids in items for chosen. Non-live, removed or moved choices are skipped before limit; use an id, not the collection key. Picture uses `{ "mediaId": "<media id>", "alt": "Description", "link": "/about" }` and renders `figure > a > img` when it has a link. Image fields cannot be multiple. Liquid menus are `navigation.<menu>.items`; there is no `menus` variable or `{% menu %}` tag. Each menu item has `label`, `url`, `children`, `is_current` and `is_ancestor`.
- Rich text preserves semantic markup including `address`, `figure`, `figcaption`, `cite`, `abbr`, `time`, `small` and `mark`. When HTML cleaning removes elements, attributes or comments, successful saves include a `warnings` list naming what was removed. Review it before publishing.
- Text parts and rich-text fields keep a `class` on any element they keep when it follows the part class rule (up to four lowercase names separated by single spaces, each starting with a letter; `keel-` is reserved), so Theme CSS can style it, and an image's `loading` when it is `lazy` or `eager`. Any other class or loading value is refused with 400 naming the field (`regions.main[0].data.html` for a part, `values.body` for a field), and nothing is saved. Example: `{ "type": "richText", "data": { "html": "<p class=\"course-red\">Second course</p><p><img src=\"/_media/<siteId>/plate.webp\" alt=\"Plate\" loading=\"lazy\"></p>" } }` is kept as written in the draft, Preview and Live; `<p class=\"MsoNormal\">` is refused.
### Form submissions

Forms enable the security check by default: omitted `turnstile` or `"turnstile": null` means on. Send `"turnstile": false` to turn it off (also in a design document's form). Standard page and item Previews show where the security check runs on the published page (“The security check shows here on the published page.”) and do not load its script; scriptless editor pictures keep that inactive placeholder. Example: `POST /api/sites/{siteId}/preview` with `{ "pageId": "<page id>" }`, open `url`: the notice immediately says “This is a preview. Forms here don't send.” No submission is stored or delivered. Forms endpoints and design-document `forms` accept `agreement` and `words`. An agreement is always required, always shown and never pre-ticked; marketing `consent` stays optional and never pre-ticked. Both sanitize inline wording with site-path or configured platform-host HTTPS links and no styles, scripts or event handlers. Agreements keep submissions and record cleaned wording/version in `agreements` beside `consents`, with `ipHash` and `submittedAt` as proof. Use the complete German form example in `p9-forms.md`, “Agreements and visitor words”. Built-in form defaults follow the site language: German and French are available; languages without a translation table fall back to English. Custom `words` use the same keys and override those defaults. The complete German example/key list is in the forms design document (`p9-forms.md`), “Agreements and visitor words”; `/openapi/v1.json` describes `FormWords`. Words are plain text (1–1,000 characters); `tooLong` accepts `{max}`, date bounds `{date}`. A design-document form entry without `words` uses the site defaults when displayed; send the whole entry including `words`. On `PUT /forms/{id}`, omitted or null `words` preserves the stored words; send default values to use the site defaults. Script and ordinary post use the same refusals. Public form submissions use `POST /_forms/{key}` on the site host. Turnstile tokens are single-use: a replayed POST returns 400 `verification-failed`, “We couldn't check that you're not a robot. Complete the check, then send the form again.” Complete a fresh check before retrying; no second submission is stored or delivered. Direct submissions need `yes` and the rendered hidden `_keel_agreement_{name}` version; missing ticks or stale versions are refused before storage or delivery. People edit these fields and visitor words in Forms.

## Sizes and limits

- A design document may be up to 4 MiB (413 `payload-too-large` beyond that). A page body may be up to 1 MB.
- A design document holds at most 200 partials, 50 layouts, 50 regions per layout, 20 menus, 30 collections, 20 forms and 1,000 redirects (including `delete.redirects`). `delete` holds at most 20 menus, 20 forms, 30 collections and 100 globals values. Lists total at most 1,200 entries. Beyond a limit: 400 `validation` at the list or `document`. Split larger designs; omitted entries are left alone.
- Per agent session or bot: `PUT /design` 60 an hour, `GET /design` 120 an hour, `GET /status` 30 a minute. Beyond that you get 429 `rate-limited` with a `Retry-After` header: wait that long. Asking for an agent session: 10 requests per 15 minutes per address. Bot tokens: 20 per 15 minutes per bot. A bot has an hourly action cap (1,000 by default): every write and every refused request counts; reads do not. Get a new access token only when the last one is about to end.

Staging copy and whole or picked backup Restore validate page parts as stored draft saves, including children in Columns. Unfinished Cards and Button choices are kept; HTML cleaning, field contracts and link checks still run. Staging retains the same stored-content validation when recreating existing public pages, including Promote and Switch back. Ordinary Publish still checks completeness: a new blank card returns 400 at `regions.main[0].data.cards[0].title`. A failed copy says **No staging copy was made** and names the page, part, field and repair. A menu, site-wide details, redirect, file or search settings refusal on a copy also says the copy was not made and could not be copied; it does not say the part was in a backup. The same refusal on a whole or picked backup restore still names the backup. The staging card says to fix the problems above only when it lists problems; otherwise the failure's own next step, such as Try again, is enough. A failed Switch back has `switchingBack: true` and says Switch back. For example, `{ "kind": "promote", "status": "failed", "switchingBack": true, "failure": "Switch back failed. Nothing was changed. Try again." }`. A page refused for its title, layout, search settings or region name names that field and what to change, such as `title`: Give the page a title of up to 200 characters. For example, a Button with `href: "javascript:alert(1)"` is refused with its page name, part id, `regions.main[0].data.href` and the safe-link instruction. Restore reports a refused page without replacing its current draft. Only people switch the original Live within plan limits. A `siteAdmin` token may promote/switch back, restore its backups or discard staging. Page backup checks/restores use their existing content role and destination checks. Confirmations, versions, audit and promotion locks still apply. Share links on reachable sites/copies need `contentCreator`: URLs return once, token lists hide person ids and show Person or Agent; revoke needs the creator credential or `siteAdmin`.

## What only a person can do

These answer 403 `bots-not-allowed` to a token:

- people, roles, invitations, domains, bots, approving or managing other agent sessions, renaming, deleting or suspending a site, form submissions (their export, files and webhook deliveries) and the site audit log. A person who removes or gives the account owner a lower role gets 403 `forbidden` with detail `The account owner cannot be removed or given a lower role here. A system administrator changes the account owner on Accounts.` (`DELETE /api/sites/{siteId}/users/{userId}` or `PUT /api/sites/{siteId}/users/{userId}/role` with `{ "role": "contentCreator" }`). Promoting that owner from content creator to site administrator is allowed. The last site administrator is 409 `last-site-admin`;
- the activity bell, `GET /api/activity`: a person's running and finished work across their sites, for example `{ "items": [{ "kind": "clone", "title": "Bringing harbour.example over", "state": "running", "step": "Rebuilding your design and pages", "done": 3, "total": 6, "lastHeardAt": "2026-11-05T15:00:20Z", "link": "/accounts/…/clones/…?siteId=…" }], "pollSeconds": 10 }`. An agent follows its own work through the clone or job status reads instead;
- integrations, the security policy, the publish webhook (address, secret and deliveries), deleting a backup (restoring into a new site remains system-only), and Redesign (`/api/sites/{siteId}/redesign`: the owner's brief, for example `{"brief":{"mainAction":"Book a visit",…}}`, its cost and its start on the staging copy, and its review: `GET /runs/{jobId}/review`, then Keep, Drop or another direction, for example `POST /runs/{jobId}/keep` with `If-Match` and `{"replaceLiveChanges":false}`). AI model settings require a person with system administrator access: `PUT /api/system/ai/features/{feature}` with `feature=clone` and current `If-Match`, for example `{"enabled":false,"provider":"anthropic","model":"claude-sonnet-5-5","fallbackProvider":"xai","fallbackModel":"grok-4.7","monthlyCapMicroCad":50000000}`. Set both retry fields or clear both with null; a 400 names `provider` or `fallbackModel` when invalid. Authorized AI usage reports also return nullable per-attempt page/chain, outcome/refusal, tool/time, page-trait and visible/thinking token fields; for example `pageKey: "home", chainPosition: 2, visibleOutputTokens: "11", thinkingTokens: "22", outputTokens: "33"`. Clone installs default rates and its approved prompt at startup; the separate judge uses the Clone policy’s Claude setting for either build model, carried on its server ticket, and a redesign’s judge uses the Redesign policy’s own (Start and admission refuse a redesign with no judge or an unpriced model). Call kind and failed-page approval use durable rows, so audit archival cannot change them. Missing xAI reasoning usage retains the maximum spending reservation. Internal worker reservations distinguish Build, Judge, LessonWriter, RenderDecision and StyleProfile; for example `kind: 3` permits only structured learning output without tools, capped at 8,192 tokens on the chosen primary model, and `kind: 4` is the crawl's one fetch-or-render choice, structured output without tools capped at 2,048 tokens on whichever of the Clone model and retry model costs less, falling back to Keel's own rule when refused, and `kind: 5` is a redesign screen's one style reading per reference site, structured output without tools capped at 2,048 tokens on the cheaper of the Redesign model and retry model, whose refusal only lists that site. These are typed counts and choices, never page text; older rows and unknown provider counts keep nulls; zero means measured zero. A changed model, retry model or judge model (Clone and Redesign each have one) saves only after a passing check of that exact provider and model from the last 24 hours; otherwise the 400 names `model`, `fallbackModel` or `judgeModel` and says "Try this model first". Start one with `POST /api/system/ai/features/{feature}/model-checks` with `feature=clone` and `{"field":"judge","provider":"anthropic","model":"claude-sonnet-5-5"}`; the 202 points at `GET /api/system/ai/model-checks/{id}`, which reads `queued`, `running`, `passed`, `failed` or `unknown` with plain words and the check cost. A model with no rates is priced first with `POST /api/system/ai/features/{feature}/rates` with current `If-Match` plus `provider` and `model`; `PUT` the feature with `judgeProvider` and `judgeModel` to change the judge. A changed model must also be on its provider's list, which Keel's worker fetches every six hours: `GET /api/system/ai/provider-models` returns each provider's `models` newest first (for example `{"id":"claude-sonnet-5-5","displayName":"Claude Sonnet 5.5","stillListed":true,"price":{"currency":"USD","inputMicroPerMillionTokens":3000000,"outputMicroPerMillionTokens":15000000}}`) with `state` `idle`, `queued` or `running`, the last fetch's `failure` and plain-word `message`. `POST /api/system/ai/provider-models/{provider}/refresh` with `provider=anthropic` or `xai` and no body queues a new fetch (202; at most once a minute per provider, 429 `rate-limited` otherwise). Saving a model its provider doesn't list is a 400 naming the field, for example `fallbackModel`: "Choose fallbackModel from the models xAI lists; grok-4.7-typo isn't one of them."; a saved model the provider no longer lists (`stillListed: false`) can be kept. Changing `provider` needs a `model` too: a 400 naming `model` says "Choose a model for xAI.". A refresh no worker claims within ten minutes reads `idle` with `failure` `notPickedUp`, and can be refreshed again.

These `PUT /design` changes also need a person; a token gets 403 `people-only-change` with paths in `errors`, saving nothing:

- `forms[].notifyAddresses` (where form notifications are sent), `redirects[].destination` pointing at another site, and `seo.securityTxt` (the site's security contact).

Leave these members unchanged; ask the person to change them in the Keel admin, and stop and ask whenever a request is refused as people-only. Hosted Clone build sessions last 12 hours on one Coming soon site and cannot publish or call people-only operations. Use `import_media` (or `POST /api/sites/{siteId}/media/clone-imports`) with `{ "runId": "11111111-1111-1111-1111-111111111111", "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "purpose": "image", "altText": "" }` for a screened picture; `purpose` also accepts `font` or `document`. The server copies and checks bytes without exposing a signed upload address; unknown/unsafe files return 400 naming `sha256`, mismatched kinds name `purpose`. Replays return the existing media item, removable through normal Media DELETE. Only the current build session can import while its run is active. Their forms must keep answers in the inbox with `{ "notifySiteAdmins": false, "notifyAddresses": [], "storeSubmissions": true }`; omitted or true notifySiteAdmins returns 400 naming `notifySiteAdmins` (or `forms[i].notifySiteAdmins`). A build session may save only Keel's own clone runtime as the theme script, nothing else; any other script returns 400 naming `script` (or `theme.script`), so send `{ "css": "body { color: red; }", "script": null }` and leave scripts to the owner. Hosted tools only delete resources confirmed by a successful create reply in this run; bulk `delete` sections are refused. Never submit a form on the source or the Keel copy. Preserve original post `publishedAt` in draft imports and decorative `alt=""`; a Keel auto-inserted h1 is a markup repair in “What we fixed”, not a heading change.

## Problems to expect

Every error is a problem document (`application/problem+json`) with `type`, `title`, `status` and `detail`. The `type` is `https://keelpage.com/problems/<slug>`. Branch on the slug:

| Slug | Status | What to do |
|---|---|---|
| `validation` | 400 | Read `errors`: field paths with sentences. Fix and send again. |
| `invalid-token` | 401 | The access token is malformed, ended or revoked. Refresh, or ask again. |
| `bots-not-allowed` | 403 | A person has to do this. |
| `people-only-change` | 403 | The document contains one of the three changes above. |
| `forbidden` | 403 | Your role is too low for this. |
| `not-found` | 404 | Not found, or not your site. |
| `precondition-required` | 428 | Send `If-Match`. |
| `stale` | 409 | Changed since you read it. Use `current`, merge, send again. |
| `design-document-refused` | 409 | Read `problems`; fix each entry. |
| `payload-too-large` | 413 | Send less. |
| `rate-limited` | 429 | Wait for `Retry-After`. |

## Reading the status

Every page/item detail or list, theme, layout/partial/menu detail or list, globals and page/item layout choice has one `publication`: `live` means **Live**, `draft` means **Draft (not on your site)**, `liveWithChanges` means **Live, with changes not on your site yet**. Scheduling `status` and site `launchStatus` (`live` / `comingSoon`) remain separate. `hasUnpublishedChanges` remains for one release; layout `isPublished` still means usable for publication, and `draftDiffers` means region-schema edits. Old snapshots' missing settings take defaults; JSON whitespace and key order do not create changes. Arrays and text keep their meaning. Saving back live content clears the mark. Deliberately unpublished pages/items wait only after another saved edit; never-published drafts count even empty.

`GET /api/sites/{siteId}/changes` is open to Content creators, approved agents and bots on their reachable site. It returns every waiting change, without bodies, authors or a 50-item cap; `count` equals `items.length`. Example: `{ "count": 1, "items": [{ "kind": "page", "id": "00000000-0000-0000-0000-000000000001", "name": "About", "publication": "liveWithChanges", "path": "/about" }] }`. Kinds are `page`, `item`, `theme`, `layout`, `partial`, `menu`, `globals`; optional `key`, `path`, `collection`, `slug` may be null. Overview and its single **Publish your changes** checklist step use this complete reader. **Preview with changes** preserves live versions. **Publish design changes** publishes design; pages/items retain their own publish actions.

`GET /api/sites/{siteId}/status` reports launch state, domains, drafts, schedules, publishes, cache, webhooks, backups, today's views and problems, with no personal data or caching. `drafts.design`, `drafts.pages` and `drafts.items` each give a count and the newest 50 items. Work until all counts are zero and no new problems remain. Pages deliberately taken off the site do not count as waiting until they have new saved edits. Never-published drafts still count, even empty drafts. For example, publish About us, take it off the site: it leaves `drafts.pages`; edit its main or sidebar region: it returns. The bounded legacy lists are derived from the same complete changes reader. A person going Live through `PUT /api/sites/{siteId}/launch` (or the system site's PATCH) must first publish a home page at `/`. For example, `{"launchStatus":"live"}` without that home returns 400 `validation`, with `detail: "Publish your home page first."` and `errors.launchStatus: ["Publish your home page first."]`. Publish the home and retry with the current `If-Match`. Switching to Coming soon remains allowed. Agent and bot tokens remain refused by the people-only launch rule.

## The publish webhook

A person can set one site address for signed notices when content goes live or comes down:

```
POST https://example.com/hooks/keel
Content-Type: application/json
X-Keel-Event: site.published
X-Keel-Delivery: 5d0e2d3f-6c1b-4f0e-9a52-3b7c8e9f0a1b
X-Keel-Timestamp: 1790000000
X-Keel-Signature: sha256=<hex>

{ "event": "site.published", "id": "5d0e2d3f-6c1b-4f0e-9a52-3b7c8e9f0a1b",
  "site": { "id": "3d1a5c6e-0b52-4e3d-8b59-7c1e2f0a4b11", "name": "Keel QA", "host": "keel-qa.keelpage.com" },
  "occurredAt": "2026-10-08T10:00:00Z",
  "items": [ { "kind": "page", "path": "/about", "version": 3, "change": "published" } ] }
```
Verify HMAC-SHA256 using the UTF-8 secret over the timestamp, a dot and exact body bytes. Compare `sha256=` plus lowercase hex with `X-Keel-Signature` in constant time; refuse timestamps over five minutes old. Answer with any 2xx. Keel attempts failed deliveries up to four times; a person can resend from the admin. Ignore repeated delivery ids. The secret is shown once when the person sets the address or rotates it.

## Stable part classes and optional region wrappers

Every native part root adds `keel-block keel-block--{type}` with the exact case-sensitive type key below. Tags and existing classes remain; Text's blockquotes are untouched. Empty editor placeholders are `p[data-keel-empty-part]` with the type classes. Live and edit markup use the same renderer; private edit attributes/comments are not theme selectors.

| Type key | Root and child markup (common block classes omitted here) |
| --- | --- |
| `heading` | `h1`–`h6` with encoded words or sanitized inline `em`, and an optional unique `id`. |
| `richText` | `div.rich-text` with cleaned paragraphs/headings/lists/tables/links/emphasis/images; quotes remain `blockquote > p`. |
| `button` | `a.button.button--{style}` with validated `href` and encoded label; default style `primary`. |
| `image` | `figure` with optional `picture picture--{size} picture--align-{alignment}`, optional link around responsive `img`, then optional `figcaption`. `loading`: `auto` (default), `eager`, `lazy`. First Picture/Cards/Slider image in layout output order (including Columns) defaults to eager + high fetch priority; later ordinary ones lazy. Decorative Pictures (decorative true or effective empty alt, including the file alt) load eagerly, including section backgrounds. Explicit lazy consumes first position; later eager has no high priority. Same on previews and collection pages. |
| `quote` | `figure.keel-quote > blockquote.keel-quote__quote > p.keel-quote__text`, then optional `figcaption.keel-quote__attribution` with `span.keel-quote__name` and/or `span.keel-quote__role`; empty name markers appear only while editing. |
| `cards` | `div.keel-cards.keel-cards--{2/3/4} > article.keel-cards__card`: optional `img.keel-cards__picture`, `h2.keel-cards__title` with optional `a.keel-cards__link`, optional `p.keel-cards__text`. |
| `columns` | `div.columns.columns--{ratio} > div.column`, each containing independently classed parts; ratios `1-1`, `2-1`, `1-2`, `1-1-1`. |
| `embed` | `div.embed.embed--{provider} > iframe`, titled/lazy with the provider's sandbox and permissions. |
| `video` | `video.keel-video > source`, optional captions `track` and download link; embeds use `div.embed.embed--{youtube/vimeo} > iframe`. |
| `slider` | `section.keel-slider.keel-slider--{style} > div.keel-slider__viewport > div.keel-slider__slide`; controls use `keel-slider__pause/prev/next/dots/dot/icon`. |
| `form` | `form.keel-form`: `keel-form__errors`, `div/fieldset.keel-field.keel-field--{kind}.keel-field--{width}`, `keel-field__label/input/radio/checkbox/hint/error/required`, `keel-form__actions/submit`. |
| `collectionList` | `ul.keel-collection-list > li > a` or `span`, with optional `time[datetime]`. |
| `mailchimp` | `form.keel-signup`: `keel-signup__field > label.keel-signup__label + input.keel-signup__input`, optional required/hidden hp and `keel-signup__actions/submit`. |
| `rawHtml` | Every authored top-level element gets the common classes; existing children/classes/gaps stay. Text-only content gets a classed span. Admin-only authoring. |

Regions JSON accepts the short example `[{"key":"main","label":"Main"}]` or `{ "regions": [ … ] }`; Keel stores and answers the object form. Omitted `allowedBlockTypes` defaults to every current part; save expands the list and publish uses that same list. Explicit lists restrict the area. Invalid lists return 400 naming `regionSchema.regions[index].allowedBlockTypes`. A layout region can set `wrap: true` for `div.keel-region.keel-region--{key}` around its parts. Omitted/false means no wrapper, including for existing layouts and snapshots. Starters opt in. Visual → **Wrap {area name} for styling** edits it; save and publish to apply it. Region keys, part permissions, history, snapshots and API validation keep their existing rules. No inline styles are generated; platform block classes do not consume the four-authored-class allowance. Skip a layout's empty wrapper with `{% if regions.aside.size > 0 %}…{% endif %}` (combine region tests with `or`; `!= empty` also works). Counts include unregistered parts, exclude Content without a place and stay the same in Edit preview; Add still lists every schema region. Keep the first region unguarded and visible in Theme for the fallback not-found body. Only new sites get updated starters. Empty regions are left out on Live and standard previews; where a wrapper with no stored parts is still written (Edit preview, the not-found body's first region), `.keel-region[data-empty]` selects it; avoid `:has(:empty)`, which matches Picture images and Form inputs too.

Use theme hooks from `docs/PART-MARKUP.md`; keep CSS in Theme or an external stylesheet. Optional part `className` (also Columns children): up to four single-space-separated names, 120 characters total; each `[a-z][a-z0-9_-]{0,39}`, never `keel-`. Empty/omitted means none. Saves/copies preserve it; roots append it after platform classes. Layouts read `regions.<key>[n].class`.

## Clone

Clone approval, progress, review and page choices are people-only. Ask the owner to use Clone in the admin; an agent cannot approve or retry a clone. One exception (D-115), Keel's own Internal account: an agent its owner approved there with Site administrator access can start a live-address clone, read its status and review summary, and cancel or resume it. The example is the `StartInternalCloneAsAgent` operation in the API description (send `requestId`, `sourceAddress`, `hasContentRights`, `targetName`, `targetSlug` and `reason`; 202 gives `jobId`). Going Live, publishing, page choices and money stay with the owner; any other account is 403. Redesign has the same exception (D-121): that agent can redesign its own home site or a site its Internal clone made. The examples are the `SaveInternalRedesignAsAgent`, `StartInternalRedesignAsAgent` (send `requestId` and the brief's `eTag`; 202 gives `jobId`; the same `requestId` returns the same job), `GetInternalRedesignAsAgent`, `GetInternalRedesignReviewAsAgent`, `KeepInternalRedesignAsAgent` and `DropInternalRedesignAsAgent` operations, with the review's eTag as `If-Match` to keep or drop. The owner's Internal authorization pays; another direction and money stay with the owner. A clone that stopped at its page limit can copy its next pages onto the same site (D-129): the example is the `CopyNextInternalClonePagesAsAgent` operation (send a new `requestId`; 202 gives the new `jobId`). Pages already on the site are never changed, and it counts as one clone start. On any other account the owner presses **Copy the next pages** in the admin. An owner-approved Internal agent can also edit content on that account's own Coming-soon agent clones, with Content creator access only; Live and people-only actions stay with people. For a redesign, `CreateInternalStagingCopyAsAgent` returns 202 and a run Location: poll it until succeeded, then start the redesign (the agent and approver need Site administrator at home); its example is in the API description.

## Custom themes and layouts

People building in the admin: see the Help article Custom themes and layouts for the screen-by-screen steps. Starters are optional. `is_home` is true on the home page and false on every other page, in Preview, Live and a launch check, and `page.is_home` is the same value: `{% if is_home %}Welcome home.{% else %}Not the home page ({{ page.is_home }}).{% endif %}`. A Blank site starts with no design. Add your theme and layouts with `PUT /api/sites/{siteId}/design` (`theme` `css`, `tokens` and `script`; `partials`; `layouts` with `source` and `regionSchema`) or the layout and theme saves already described. You can rewrite a starter's `starter-home` layout in place. Custom theme CSS and custom layout HTML are first-class on every plan. The plan decides whether a site may go Live and on which address. `partStyles` is `keel` (Keel's part styles; omitted, or a theme with no setting, serves the same stylesheet) or `structural` (only the CSS a part needs to work: slider, column and embed layout, and the form's hidden and required mechanics, with none of Keel's form grid, field gaps, control heights, form width, figure image width, or button colours). Example: `{ "css": "body{margin:0}", "tokens": {}, "partStyles": "structural" }`.

A layout is a whole HTML document in Liquid (Fluid). Put `{% head_content %}` in `<head>` and `{% body_end_content %}` before `</body>`. If either is missing, Keel inserts that content itself, so both are recommended. This fallback also supplies draft-only SEO on Coming soon page and collection-item previews. An authored `<title>` stays in both Preview and Live: use `<title>{{ seo.title }}</title>` to follow the page’s SEO title. Keel already writes the description, canonical, Open Graph/Twitter tags and automatic JSON-LD; writing those again in the layout creates duplicates, and an earlier hard-coded tag may hide the value you are trying to check. Put `{% head_content %}` in `<head>` and omit your own copies of Keel’s metadata. `{% region 'key' %}` has no closing tag; `{% endregion %}` is refused. List every key from the source in `regionSchema.regions` (`key`, `label`, optional `allowedBlockTypes` and `wrap`). A region allows a part only by its exact type key. HTML parts are `rawHtml`: there is no `html` type and no `allowHtml` setting. Write notes as `{% comment %}…{% endcomment %}` or `{% # … %}`. `{# … #}` is not a Liquid comment, and a layout or partial that holds one is refused at save. Incoming HTML in parts, rich-text values, partials and layouts refuses inline style attributes and scripts with 400 naming the field. Use classes and Theme CSS. Unchanged stored part HTML keeps the existing save behaviour. The admin removes pasted styles with a plain note; paste-content proposes parts and reports omissions without saving. Clean inline SVG is kept in HTML parts, partials and layouts; scripts, handlers, animation, foreign content and external references inside SVG get the SVG field error, including scripts inside foreign content. Scripts outside SVG keep the Scripts field error. SVG href/xlink:href/src may point only to #fragments or data images. Uploaded SVG media still uses its existing sanitizer. Liquid-built tag names remain refused at save: use complete literal elements in each branch.

Liquid output is HTML-escaped by default. Picture and link values print as their `url`; missing values are nil and use `default`'s fallback. `include` shares assignments with the including layout; `render` is isolated. Their limits continue to apply. A `{% capture d %}<strong>{{ page.title }}</strong>{% endcapture %}` holds rendered HTML; `{{ d }}` prints that markup. `append` and `prepend` preserve captured markup and escape any plain-text operand, so `{% assign s = '' | append: d %}{{ s }}` prints the same HTML. Captured labels have already been escaped once. For literal tags as visible text use `| escape`; for attribute values, output plain values or use `| escape`. Rich-text collection fields are cleaned on save (incoming scripts, event handlers, javascript: URLs and style attributes are refused) and checked again on render, including after a field changes type. `{{ t.quote }}` outputs escaped text. Use `{{ t.quote | raw }}` to render its cleaned HTML in items, lists and partials. The `raw` filter bypasses output escaping; it does not clean an ordinary string. Use it only for a rich-text field or HTML you trust, in element content, never an attribute. Use `{{ t.quote | escape }}` to show the tags as text. Liquid `split` drops a leading empty item, and a filter is not allowed inside a `for` tag, so assign first: `{% assign parts = '/de/x' | split: '/' %}{% for part in parts %}{{ part }}{% endfor %}` gives `de` then `x`.

Scope theme CSS with a class on `<body>` (`{{ layout.body_class }}`, from the layout's `bodyClass`). Style Keel's parts by the classes in Stable part classes and optional region wrappers. Publish the theme, then layouts and partials, then pages (parents before children; a page needs its layout published). Or publish every reviewed design change together, as in The loop. `POST /api/sites/{siteId}/layouts/{layoutId}/publish` publishes only that layout. Renaming or removing a populated region key is the `layout-regions-affected` review under Pages, media, previews.

## Video import walkthroughs

Start each file with `POST /api/sites/{siteId}/media/uploads`, giving `fileName`, `contentType` (`video/mp4` or
`video/quicktime`) and the exact `size` in bytes. Read `upload.maxSize`; it is the effective limit, not a value to
copy into a script. The defaults are 2 GiB for videos, 15 MB for images and 50 MB each for PDFs and fonts (1 MB is 1,048,576 bytes).
`Media:VideoMaxBytes`, `Media:ImageMaxBytes`, `Media:PdfMaxBytes`, `Media:FontMaxBytes` and
`Media:CaptionsMaxBytes` are settings. Captions default to 2 MB. Read `GET /api/sites/{siteId}/media/upload-settings`
for effective `imageMaxBytes`, `pdfMaxBytes`, `fontMaxBytes`, `videoMaxBytes` and `captionsMaxBytes`.
A size refusal's `detail` and `errors.size` give the limit and actual bytes.

The start answer keeps `url`, `method`, `headers`, `mode`, `blockSize`, `expiresAt` and `sessionExpiresAt`.
It adds `blocks.put` (method, URL template and headers), `blocks.idRule`, `blocks.idExample`, `blocks.commit`
(method, URL and headers), `blocks.commitBody` and `complete` (method, API path and headers). The top-level
`url/method/headers` now also supports a **single PUT** of the whole video, up to `maxSize`. This needs
`x-ms-blob-type: BlockBlob`, supplied in `headers`. A single PUT needs no block-list commit. Existing scripts
that use the original URL and block-id rule still work. Use blocks for resumable uploads.

Storage requests have no API authorization header or cookies. Send every returned header. HttpClient and curl
supply Content-Length from the body; it must equal the body bytes. Never change or discard the SAS query. The
SAS still lasts at most 15 minutes; its expiry is `expiresAt`. Before it expires, finish storage writes or call
`POST /api/sites/{siteId}/media/{id}/upload/renew` and use the new instructions for the same file. Renewal never
extends `sessionExpiresAt`. If a storage response is uncertain, resend the same block id and bytes; `Latest`
allows repeating the commit too. Stop all writes before calling `complete`.

### Small video: one PUT with curl

For a roughly 11 MB MP4, set `API` to the admin API origin, `SITE` to the site id and `FILE` to the local MP4.
`TOKEN` is the helper's approved API token. Use it only for API requests. These commands need curl, jq and Python 3.

```sh
set -e
FILE=small.mp4
size=$(python3 -c 'import os,sys; print(os.path.getsize(sys.argv[1]))' "$FILE")
jq -n --arg name "$(basename "$FILE")" --argjson size "$size" \
  '{fileName:$name,contentType:"video/mp4",size:$size}' > start.json
curl --fail-with-body -sS -X POST "$API/api/sites/$SITE/media/uploads" \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  --data-binary @start.json > upload.json
# Require a successful start before reading instructions. Keep upload.json private: it contains a SAS.
mapfile_headers() { # Bash arrays work on macOS's Bash too; no mapfile command required.
  headers=()
  while IFS= read -r header; do headers+=( -H "$header" ); done < <(
    jq -r "$1 | to_entries[] | .key + \": \" + .value" upload.json)
}
mapfile_headers '.upload.headers'
curl --fail-with-body -sS -X "$(jq -r '.upload.method' upload.json)" \
  "$(jq -r '.upload.url' upload.json)" "${headers[@]}" --upload-file "$FILE"
# Storage must return 201. Then make the authenticated API completion request (no body).
curl --fail-with-body -sS -X "$(jq -r '.upload.complete.method' upload.json)" \
  "$API$(jq -r '.upload.complete.url' upload.json)" -H "Authorization: Bearer $TOKEN"
```

Run the shell examples in Bash. Completion returns 202 while preparing, with `Location` and `Retry-After`.
Poll that API Location with the same API token until `status` is `ready` and `canUse` is true. A `videoRejected`
asset gives `failureCode` and `failureReason`; stop and use that explanation. Completion still checks the declared
size and freezes the file; preparation still checks the file format, magic bytes and decode structure.

### Large video: blocks and commit with curl

For a roughly 161 MB MP4, repeat the start commands with `FILE=large.mp4`. Read the block size from the answer.
Every block except the last has exactly that many bytes; the last has the remaining bytes. Indexes start at zero.
An id is standard Base64 of **four unsigned big-endian index bytes followed by the block's 32 SHA-256 bytes**.
For example, index 0 and bytes `abc` give the SHA-256
`ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad`, and the id
`AAAAALp4Fr+PAc/qQUFA3l2uIiOwA2Gjlhd6nLQQ/2HyABWt`. This tiny example explains the encoding; an actual
block must satisfy the returned size. URL-encode the id in the block PUT URL, but keep its Base64 form in XML.

After the start request above, run:

```sh
parts=$(mktemp -d)
python3 - "$FILE" upload.json "$parts" <<'PY'
import base64, hashlib, json, pathlib, struct, sys, urllib.parse
file, answer, directory = sys.argv[1:]
upload = json.load(open(answer))['upload']
ids = []
with open(file, 'rb') as source, open(directory + '/index.tsv', 'w') as inventory:
    index = 0
    while chunk := source.read(upload['blockSize']):
        id = base64.b64encode(struct.pack('>I', index) + hashlib.sha256(chunk).digest()).decode()
        path = directory + '/' + str(index)
        pathlib.Path(path).write_bytes(chunk)
        inventory.write(path + '\t' + urllib.parse.quote(id, safe='') + '\n')
        ids.append(id)
        index += 1
pathlib.Path(directory + '/commit.xml').write_text(
    '<BlockList>' + ''.join('<Latest>' + id + '</Latest>' for id in ids) + '</BlockList>')
PY
mapfile_headers '.upload.blocks.put.headers'
while IFS=$'\t' read -r part encoded_id; do
  url=$(jq -r --arg id "$encoded_id" '.upload.blocks.put.url | split("{blockId}") | join($id)' upload.json)
  curl --fail-with-body -sS -X "$(jq -r '.upload.blocks.put.method' upload.json)" \
    "$url" "${headers[@]}" --data-binary "@$part" || exit 1
done < "$parts/index.tsv"
# Put Block List is required; successful block PUTs alone do not finish the upload.
mapfile_headers '.upload.blocks.commit.headers'
curl --fail-with-body -sS -X "$(jq -r '.upload.blocks.commit.method' upload.json)" \
  "$(jq -r '.upload.blocks.commit.url' upload.json)" "${headers[@]}" \
  --data-binary "@$parts/commit.xml"
curl --fail-with-body -sS -X "$(jq -r '.upload.complete.method' upload.json)" \
  "$API$(jq -r '.upload.complete.url' upload.json)" -H "Authorization: Bearer $TOKEN"
rm -rf "$parts"
```

Each storage request must return 201; stop on another status. Poll completion as in the small-file walkthrough.
For a resume, read `GET /api/sites/{siteId}/media/{id}/upload?page=1` and follow `nextPage`. Recompute every
accepted block's id from the reselected file before reusing it. Resend absent blocks with their original ids, then
commit the complete ordered list. Never use the helper's API token at the storage URL.

### Small and large videos with C# HttpClient

The same function handles a small file as a single PUT (`useBlocks: false`) and a large file as blocks
(`useBlocks: true`). Set `api.BaseAddress` to the admin origin and its authorization to the approved API token.
Use a separate `storage` HttpClient without authorization or cookies. These examples use only .NET libraries.
All filenames, sizes, block sizes, limits, headers and URLs come from the file or the API answer.

```csharp
using System.Buffers.Binary;
using System.Net;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

async Task<JsonElement> UploadVideo(HttpClient api, HttpClient storage, Guid site, string path, bool useBlocks)
{
    var file = new FileInfo(path);
    using var start = await api.PostAsJsonAsync($"/api/sites/{site}/media/uploads", new
    { fileName = file.Name, contentType = "video/mp4", size = file.Length });
    start.EnsureSuccessStatusCode();
    using var answer = JsonDocument.Parse(await start.Content.ReadAsStringAsync());
    var upload = answer.RootElement.GetProperty("upload");
    if (file.Length > upload.GetProperty("maxSize").GetInt64()) throw new InvalidOperationException("File exceeds the returned limit.");
    await using var input = file.OpenRead();
    if (!useBlocks)
        await SendStorage(upload, new StreamContent(input));
    else
    {
        var blocks = upload.GetProperty("blocks");
        var buffer = new byte[upload.GetProperty("blockSize").GetInt32()];
        var ids = new List<string>();
        for (uint index = 0; input.Position < input.Length; index++)
        {
            int count = await input.ReadAtLeastAsync(buffer, (int)Math.Min(buffer.Length, input.Length - input.Position));
            var bytes = new byte[36];
            BinaryPrimitives.WriteUInt32BigEndian(bytes, index);
            SHA256.HashData(buffer.AsSpan(0, count)).CopyTo(bytes, 4);
            var id = Convert.ToBase64String(bytes);
            ids.Add(id);
            var put = blocks.GetProperty("put");
            await SendStorage(put, new ByteArrayContent(buffer, 0, count),
                put.GetProperty("url").GetString()!.Replace("{blockId}", Uri.EscapeDataString(id)));
        }
        var xml = "<BlockList>" + string.Concat(ids.Select(id => $"<Latest>{id}</Latest>")) + "</BlockList>";
        await SendStorage(blocks.GetProperty("commit"), new StringContent(xml, Encoding.UTF8));
    }
    var complete = upload.GetProperty("complete");
    using var completion = await api.SendAsync(new HttpRequestMessage(
        new HttpMethod(complete.GetProperty("method").GetString()!), complete.GetProperty("url").GetString()));
    completion.EnsureSuccessStatusCode();
    using var completed = JsonDocument.Parse(await completion.Content.ReadAsStringAsync());
    return completed.RootElement.Clone(); // 202 means preparing; poll Location using Retry-After.

    async Task SendStorage(JsonElement instruction, HttpContent body, string? url = null)
    {
        using var request = new HttpRequestMessage(new HttpMethod(instruction.GetProperty("method").GetString()!),
            url ?? instruction.GetProperty("url").GetString()) { Content = body };
        foreach (var header in instruction.GetProperty("headers").EnumerateObject())
        {
            if (header.Name.Equals("Content-Type", StringComparison.OrdinalIgnoreCase))
            { body.Headers.Remove(header.Name); body.Headers.TryAddWithoutValidation(header.Name, header.Value.GetString()); }
            else request.Headers.Add(header.Name, header.Value.GetString());
        }
        using var response = await storage.SendAsync(request);
        if (response.StatusCode != HttpStatusCode.Created)
            throw new HttpRequestException(await response.Content.ReadAsStringAsync());
    }
}
// Await each file separately; use the returned expiry and renewal endpoint for long/resumed transfers.
var small = await UploadVideo(api, storage, siteId, "small.mp4", useBlocks: false);
var large = await UploadVideo(api, storage, siteId, "large.mp4", useBlocks: true);
```

If `/complete` returns a problem, follow its `detail`: no bytes means send the file or blocks; uncommitted blocks
mean send Put Block List; wrong ids, sizes or order mean correct the blocks and commit; an expired session means
start a new upload. These refusals go through the request dispatcher and are audited once. The response never
publishes unfinished or unchecked video bytes.

## Custom domains: a person's step
Agents and bots cannot add, recheck or remove domains, including with a siteAdmin role: 403 `bots-not-allowed`.
Ask an account owner or site administrator to open **Web address and launch → Add your own domain**.
For example, a person posts `{"hostname":"www.example.com","includeAlternate":true}` to `/api/sites/{siteId}/domains`, receives the
saved pending domain and DNS records plus `alternateDomain` for `example.com`, with its own DNS records. Choosing only www sends `{"hostname":"www.example.com","includeAlternate":false}` and creates www alone. The screen asks which address visitors should see before that post: the first **Add domain** does not create a row, and **Add this address** does. The person copies the records to their DNS provider. Both names are added in one transaction, or neither is saved. Every connecting record is DNS only (grey cloud), never proxied. If your DNS is at Cloudflare and the proxy is on, visitors get Cloudflare error 522. Keel checks the hostname and certificate automatically.
`POST /api/sites/{siteId}/domains/{domainId}/recheck` reads Cloudflare immediately (one check per minute) and
makes a ready domain live. The first own domain becomes the main address when it goes Live, regardless of which certificate finishes first; the alternate then 301 redirects to it, keeping the path and query. A later one does not, until `PUT /api/sites/{siteId}/domains/{domainId}/primary` (**Make main address**). A hostname Cloudflare refuses, such as one ending in example.com, is a problem in plain words ("Custom hostnames ending in example.com are prohibited") rather than waiting forever. The screen updates every
15 seconds while pending. `DELETE /api/sites/{siteId}/domains/{domainId}` removes the domain; the UI asks for
the hostname when removing the main address on a Live site. These routes, including the old `domain-requests` alias,
all refuse tokens. Validation and plan refusals name `errors.hostname`; for example an excluded custom domain
returns 409 `plan-limit`, an invalid `https://example.com/path` returns 400 `validation` for `hostname`, and a taken name returns 409 `hostname-taken` whose detail and `errors.hostname` are the same sentence, `{hostname} is already attached to a site.`
Without `includeAlternate`, Keel serves the address added: redirect the other www/bare address at the DNS provider, or add it separately. Remove old wildcard or A records that still send visitors to an old host. Bare domains need CNAME flattening or ALIAS support.
The screen names DNS, certificate or readiness, shows Last checked, and says it is fine to leave the page.
The ten-per-day refusal includes the reset time and `errors.hostname`. Both names count as adds.
Removal confirms first, warns that visitors will lose a live address, and links the site's remaining Keel address.
Site overview, Billing and Web address display the same server `liveSummary`, also used by domain status;
for example `Live: visitors now reach your site at www.example.com`.
## Accepted embeds
Use an `embed` part with `data.url` and optional `data.title`. Accepted: YouTube, Vimeo and Voomly single videos; Google Maps; Calendly booking pages; Facebook pages; Typeform forms. The server derives `provider` from the URL. This applies to all regions, child pages and Columns; Preview and Live share the same frame renderer.
- Typeform: `https://form.typeform.com/to/AbCd1234` or `https://account.typeform.com/to/AbCd1234`. Code such as `<div data-tf-widget="AbCd1234"></div>` (with or without its script) stores only `https://form.typeform.com/to/AbCd1234`. Only the exact frame host is allowed, and only pages using it gain that CSP permission. Other Typeform paths, non-HTTPS addresses, credentials and ports return 400 naming the part's `data.url` and listing accepted forms.
- Maps Embed API: `https://www.google.com/maps/embed/v1/place?key=YOUR_KEY&q=Toronto` and `v1/search?q=Toronto` rebuild as `https://www.google.com/maps/embed?pb=!1m2!2m1!1sToronto`. `v1/view?center=43.65,-79.38&zoom=15` rebuilds as `https://www.google.com/maps/embed?pb=!1m3!2m1!1s43.65%2C-79.38!6i15`. The key and all other parameters are dropped. An unreadable place or view returns 400 naming `data.url`.
- Voomly: paste the full player code or `https://embed.voomly.com/embed/assets/embed.html?videoId=DSuwwB6WQJrWBynLm07UOrkQCLMqZAM0Q0l6tna0Ze1WGAUfD`. `embed-build.js` alone returns 400 asking for Voomly's embed code.
Save and publish apply the same checks. To delete, omit the part from its region's complete parts array on PUT; in the UI use Remove on the part.
Typeform live embed code (`data-tf-live`) uses a configuration ID, not a form ID, and is refused without a lookup. For example, `<div data-tf-live="01J5X1H8WM5CSXVDN89WXNX5EB"></div>` returns 400 on the part's `data.url`: “We couldn't read this Typeform live embed. Paste its share address, https://form.typeform.com/to/<id> or https://<account>.typeform.com/to/<id>, or its data-tf-widget embed code instead.”

## Throw away changes

Read the item's current `id`, `version` and `hasUnpublishedChanges`. To throw away a published draft, including its address and versioned settings, call `POST /api/sites/{siteId}/pages/{id}/discard` with the current `If-Match`, with `pages` replaced by the item's kind: `theme`, `partials`, `layouts`, `menus`, `globals`, `pages` or `items`; even the singleton theme and globals use their own id. Design kinds need `siteAdmin`; pages and items need `contentCreator`. Approved agent and bot tokens may call these operations. For example, `POST /api/sites/{siteId}/layouts/{id}/discard` with `If-Match: "AAAAAAAAB9E="` returns `{ "kind": "layout", "id": "...", "publication": "live", "hasUnpublishedChanges": false, "latestVersionNumber": 4, "version": "..." }` plus its new ETag. Read the editor resource again for the restored fields. Missing If-Match is 428 `precondition-required`; a stale value is 409 `stale` with `current`. A false mark is 409 `nothing-to-discard`, even if the draft text differs. A true mark is cleared even when the text already matches. The history action is `discard` (stored value 7). No live output or visitor cache changes. For a batch, `POST /api/sites/{siteId}/changes/discard` with `{ "items": [{ "kind": "layout", "id": "6d0c7a43-3e7c-4bb1-9a6e-0a8b1b2f6c11" }] }` discards every selection in one transaction and one audit event. Pass the `kind` and `id` from GET `/changes`: `layout`, `partial`, `menu`, `page`, `collectionItem`, `theme`, `globals`. The `item` alias and plural route names remain accepted for one release; aliases of one item are duplicates. One unknown, duplicate or already-clean item refuses the whole batch with 400 naming the item and `items[index]` field. A batch containing design requires `siteAdmin`. An address conflict is a named 400 field; move the conflicting draft first. Never-published items have no live version to restore: use their existing delete operation. A never-published theme or set of site-wide details has **Delete theme** or **Delete site-wide details** instead. The confirmation says it is deleted for good and cannot be brought back. The API accepts `DELETE /api/sites/{siteId}/theme/{id}` and `DELETE /api/sites/{siteId}/globals/{id}` with the current `If-Match`, for a Site administrator (including an approved token). For example, read the theme, then send `DELETE /api/sites/{siteId}/theme/{id}` with `If-Match: "AAAAAAAAB9E="`. A published item is refused with 400 naming `id`; use Discard changes for it. A missing If-Match returns 428; a stale one returns 409 with `current`.

Deleted collection items have the same permanent-delete role decision as deleted pages: SiteAdmin people, approved agents and bots can use it. Confirm removal by name first. Read `GET /api/sites/{siteId}/collections/{key}/items/{itemId}/uses` and the deleted list, then send `DELETE /api/sites/{siteId}/collections/{key}/items/{itemId}/permanent` with `If-Match: "{deletedItem.version}"` (replace `{key}` with the collection key, for example `blog`). `uses` lists `{ kind, id, name, collectionKey, deleted, draft, live }` for current draft/live pages, items, layouts, shared design parts, menus and site-wide details, including deleted sources and nested parts (kind: page, item, layout, partial, menu, globals). Exact ids and plain address links count, including rich-text anchors and button/menu URLs: /blog/old?from=menu#main and the same path on this site’s platform/custom hosts match /blog/old, ignoring case and trailing slash; /blog/older and foreign hosts do not. Only link fields, a/area hrefs and values starting /, ./, ../, //, http:// or https:// count as addresses; ordinary titles, headings, labels, alt text and tags do not. Path-relative links resolve only where their source renders. References refuse deletion with a named 409 and `uses`; remove those references first. Earlier versions alone do not block deletion. Missing/stale If-Match gives 428/409; an item not deleted gets a named 409. Success is 204, removes all versions, audits the item name once and queues one whole-site purge. People find **Delete permanently** and **Who uses it** under **Deleted items**; **Bring back** still restores a draft.

A Voomly video address with a short or malformed id, such as `https://share.voomly.com/v/abc123`, returns 400 on the part's `data.url` on save and publish: “This doesn't look like a Voomly video id. Paste the video's share link or embed code.” Voomly collection and other page links keep the explanation that Keel embeds single videos, not collections or other Voomly pages.

Earlier saves alone never block deleting a layout. The Delete layout dialog names their pages:
“Earlier saves of Home used this layout. Restoring one of them keeps its content and uses the page's current layout.” For example, `GET /api/sites/{siteId}/layouts/{layoutId}` returns
`"earlierSavePages": [{"id":"6d0c7a43-3e7c-4bb1-9a6e-0a8b1b2f6c11","title":"Home","deleted":false}]`. `DELETE` with the layout's `If-Match` returns 204 when no current draft, live page, deleted page or collection uses it. Publish the restored draft when ready.

Google Fonts work with no setup on Live sites and in Preview: use fonts.googleapis.com for stylesheets and fonts.gstatic.com for font files. Font Awesome stylesheets work with no setup on Live sites and in Preview from use.fontawesome.com and cdnjs.cloudflare.com; self-hosted font files work too. Font Awesome kits are scripts, which Keel doesn't run. Use the Font Awesome stylesheet link or upload the font files instead. A collection item with a kit in a rich-text field is refused at save, schedule and publish with the same message under values.{fieldKey}; for example, values.body names the body field. For example, use `<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">` in the layout head and `<i class="fa-solid fa-house"></i>` in its body. A kit script is refused on save and publish with a 400 naming its field (for example, `theme.script` in `PUT /design`); nothing is saved. Existing stored kits show the same message in `GET /status` and at their location in Preview; visitors never see that message on Live.

## Theme part styles and site language

Set the site's language with `PUT /api/sites/{siteId}/language` and `{ "locale": "de-DE" }`. Owners, site administrators and agent tokens may set a BCP 47 tag; anything else is 400 naming `locale`. It drives `html lang`, `og:locale` and form messages. For example, the built-in required message becomes "Bitte füllen Sie dieses Feld aus." for `de-DE`; `fr-CA` falls back to English until French translations are available.

A collection list shows its date in that language unless `showDate` is false: `{ "type": "collectionList", "data": { "collection": "<id>", "showDate": false } }`.

### Collection list Date fields

A Collection list part has independent **Date to show** and **Date to sort by** choices. Each offers **Publish date** (the default) and the collection's Date fields. Existing lists keep using Publish date. `dateField` selects the displayed Date field; `sortDateField` selects the Date field for Newest first / Oldest first. Omitted or null uses Publish date. A selected Date is a calendar day, never shifted through a time zone, and uses the site's language: `21. Oktober 2026`, `21 octobre 2026`, or `October 21, 2026`. Missing selected values have no displayed date and sort last in either direction; ties use item id. The limit applies after sorting all candidates. Chosen order keeps the chosen items and ignores the sort choice. Live reads published values; authorized Preview reads drafts. Show the date can still hide the date.

```json
{"type":"collectionList","data":{"collection":"<collection-id>","dateField":"event-date","sortDateField":"closing-date","order":"newest","limit":10}}
```

Unknown or non-date field keys return 400 naming the part's `data.dateField` or `data.sortDateField`: “Choose a Date field from this collection, or use Publish date.” Save and publish use the same check, including parts on nested pages and in item regions. The part's choices do not change the collection's list page, feed or template order. A layout's custom partial still owns its rendering.

## Public plan information
`GET https://app.keelpage.com/api/signup/plans` is anonymous and cacheable for 60 seconds.
For example, `{"plans":[{"key":"launch","name":"Launch","monthlyCadCents":2900,"includedSites":1}]}`
shows selected fields: `monthlyCadCents` means CAD cents per month, and null limits mean unlimited. Published prices
follow the next paid-account cohort, so paid sign-ups can change the next buyer's price; free sign-ups do not lock a price.
A public-site script uses `credentials: 'omit'`, no extra request headers, and an origin in `Cors:PublicPlanOrigins`.
Keel automatically adds the configured admin origin (today `https://app.keelpage.com`) to `connect-src` for site origins in `Cors:PublicPlanOrigins`, without saving it in `allowedSources`. No owner setup is needed for Keel’s own sites. Other sites still need that admin origin in their per-site `allowedSources`; only a person can change these in **Connected services**. Tokens cannot change it.
Public hosts never serve `/api`; other endpoints and methods, including OPTIONS, have no CORS allowance. Every response from the plans endpoint carries `Vary: Origin`. See the full example in OpenAPI.

## Draft layouts and pages

Page and collection item saves accept the union of the published and draft layout schemas, including draft-only region keys and allowed part types. Unknown regions/types return 400 naming the field, such as `regions.unknown`. Edit preview uses the draft layout only when the content needs a draft-only region or part type; otherwise it uses the published layout. Design review links keep their existing draft design behaviour.
For example, save a design draft adding region `title` and `{% region 'title' %}` to Article, then PUT the page with `{"regions":{"title":[{"type":"heading","data":{"text":"Ink Lab","level":1}}]}}` and the page's `If-Match`. Saving succeeds. Publishing before the layout returns 409 `needs-other-changes`, with `layout: {id,name}`, `regions: ["title"]` and `errors.regions.title`; nothing is published. Items and draft-only allowed types follow the same rule. Publish in two steps, each with its resource's current `If-Match`: first POST `/api/sites/{siteId}/layouts/{layoutId}/publish` (site administrator), then POST `/api/sites/{siteId}/pages/{pageId}/publish` or `/api/sites/{siteId}/collections/{key}/items/{itemId}/publish` (content creator). Approved agents retain the same reach. Publishing refuses content that needs the layout draft; other saved content publishes as before. A second-step failure leaves the layout published: retry only the content. Scheduling content that needs the draft is refused with the same 409 before any schedule changes. The editor's one confirmation lists the layout and the real other live pages and items it changes (`publishedPageCount`, `publishedItemCount`); `publishedLayoutId` identifies the item's actual live layout.
Discarding or restoring the layout draft while content needs its draft-only regions/types returns 409 `layout-draft-in-use`, naming dependent drafts in `pages: [{kind,id,name,regions}]`, for example `{"kind":"pages","id":"…","name":"Ink Lab — Page","regions":["title"]}`. Change those drafts first; no content is removed. GET layout includes `dependentDrafts` for the discard confirmation. The page/item editor's signed Preview link sends `contentLayout: true`: POST `/api/sites/{siteId}/preview` with `{"pageId":"…","contentLayout":true}`, or POST the item's `/preview` with `{"contentLayout":true}`. It uses Edit preview's conditional layout choice with ordinary preview presentation and safety rules. Omit the flag for existing design-review behaviour; `readOnlyFrame` and `editMode` retain their roles. Agents may use `contentLayout` with content-creator reach.

## Pages using a layout

`GET /api/sites/{siteId}/pages` includes `publishedLayoutId` (null without a live version) beside the draft `layoutId`. Example: `{ "title": "About", "layoutId": "new-layout-id", "publishedLayoutId": "live-layout-id" }`. Both layouts remain in use until publication. Disabled Delete layout names up to eight pages using its draft or live version, then “and N more”; Show all lists the rest. Address errors keep API field names (`slug`), with owner wording such as `errors.slug: ["This address belongs to the item slash-test."]`.

## System site creation (people only)

`POST /api/system/sites` requires an explicit `accountId`, including for Internal. Example: `{ "name": "Acme", "slug": "acme", "firstAdminEmail": "<the first site administrator's email>", "accountId": "8f6b1d2a-6c1e-4f0b-9a57-1d0c5b3e7a01" }`. A missing, null, empty or unknown account returns 400 with `errors.accountId` and creates no site or invitation. Only a system administrator may send this request. Agents and bots cannot create sites through this route. A keelpage.com address is taken while a site that is not deleted has it; a deleted site's address is free at once. Creating a site with a taken address answers 409 `slug-taken` with the first free one in `suggestion` and in `errors.slug`, for example `{ "suggestion": "acme-2", "errors": { "slug": ["That address is taken. Try acme-2."] } }`; send it again with that slug. People see the same answer as they type (`GET /api/sites/address?slug=acme`, people only). Deleting, restoring and deleting a site permanently are people-only: restore answers the address it used, `{ "hostname": "acme-2.keelpage.com", "addressChanged": true, "previousHostname": "acme.keelpage.com" }` when the old one was taken.

## Design history and publication times
Theme, partial, layout, menu and globals `publishedAt` keeps the first publication date, as for pages and collection items. Each publish that changes the live design moves `modifiedAt` and is its version's time, for people, agents and bots. `GET /api/sites/{siteId}` `updatedAt` is the latest of those publish times, for example `"updatedAt": "2026-10-24T19:00:00Z"`. A publish does not rewrite the site row or its version. An unchanged publish leaves these times alone. Restore and discard change the draft, preserving the live times until a changed draft is published. Page and collection item version lists and individual versions use the same `createdBy` meaning as design history: a human author’s email, null for the system, or the helper name. For new helper-authored page, item and design versions, history `createdBy` is the helper's name, for example `{ "number": 4, "createdBy": "Claude Code", "createdAt": "2026-10-24T19:00:00Z", "publishedAt": "2026-10-24T19:00:00Z" }`. It does not substitute the approving person's email. People viewing Activity history or System audit see the helper name and, for an agent, its approving person. Each design event can include `changes` (kinds `theme`, `partial`, `layout`, `menu`, `globals`), for example `{ "kind": "partial", "key": "header", "name": "header", "fromVersion": 2, "toVersion": 4 }`. Versions describe metadata, never a second copy of the design source. Audit reads remain people-only. Helpers must not call the audit endpoints. Both histories and the CSV hide successful views and previews before counting and paging; `showPreviews=true` includes them. Refused or failed reads stay visible. Activity history and System audit use backup words for `snapshot.*`, `page.snapshot.*` and `collection.item.snapshot.*`, and saved site copy words for `staging.*`. For example, `snapshot.created` appears as **Backup created** and `staging.copy.completed` as **Saved site copy completed**. The Action filter and event rows share these words. The system CSV retains its technical `action` column and appends `actionLabel` with the same product words. Filters still send the unchanged action codes. For example, an export row with `action=snapshot.created` ends with `actionLabel=Backup created`. These audit routes remain people-only. Every history row (`GET .../pages/{pageId}/versions`, `.../collections/{key}/items/{itemId}/versions`, `.../theme/versions`, `.../layouts/{layoutId}/versions`, `.../partials/{partialId}/versions`, `.../navigation/{key}/versions`, `.../globals/versions`) has a read-only `changes` list: what that version changed against the version before it, as snapshot paths, with a region or field value named on its own. For example, `{ "number": 4, "action": "saveDraft", "changes": ["regions.main", "seo", "title"] }`; `"changes": []` is a version that changed no content (a publish or unpublish), and `null` means there is nothing to compare: the first version, a stored version that no longer reads, or one whose predecessor is no longer kept. A single version read does not carry `changes`. `createdBy` is `"Former member"` when the author's account no longer exists and null only when Keel saved the version itself. Item fields read `values.summary`; the theme reads `css`, `tokens` and `script`.
Offline editing in the admin: The admin loads settings panel code with each editor. If a connection drops, the editor keeps its working copy and says “Waiting for the connection. Your changes will save when it returns.” This sentence stays the same while typing, and connection failures do not show a save-failed banner. On reconnect, pending drafts save before unrelated editor reads, with the usual `If-Match` check and field validation. For example, edit an item's title offline and leave the tab open; its draft saves when the connection returns. A concurrent edit still returns 409 and requires a choice. History keeps cached rows. A first history read offline says “History isn't available offline. It will load when the connection returns.” Media uploads continue across admin screens in the same tab: starting a video, visiting Pages and returning to Media does not pause it. Closing the tab interrupts the upload; resumable videos retain their metadata.

## Clone v2 report (people only)

Clone-v2 honours robots.txt/Crawl-delay on one origin, default cap 50 pages. Saved source files are private. Scripts/SVG have safety findings; unsafe files never reach build. D-73 renders accepted files offline: scripts on, no network, cookies, storage or service workers. Every source statement is data. Lessons hold enums/numbers only. System admins: `GET /api/system/clones/lessons/retro?from=2026-10-19&to=2026-10-26` (exclusive end, max 31 days; 400 names `to`); `POST /api/system/clones/lessons/benchmark`, no body (unavailable: 400 names `benchmark`). People-only `POST /api/system/clones/lessons/{lessonId}/retire` or `/reactivate` requires `If-Match: "{eTag}"` from retro (428 missing, 409 stale). Reactivate returns Candidate; only a fresh benchmark activates it.
For clone-v2 runs, people with a site role read `GET /api/sites/{siteId}/clones/{jobId}/report/v2`. Helpers cannot read this report. Example page: `{ "pageKey": "home", "disposition": "needsYou", "scores": { "lookMatch": false }, "diffs": [{ "width": 390, "browser": "chromium", "diffPpm": 1200 }] }` (excerpt). Differences are parts per million; 1,000 is 0.1%. A failed page gets at most one build retry before it needs the owner's review. `checks` adds width/browser/section/severity/problem to failures; e.g. `{ "kind": "geometry", "status": "fail", "width": 375, "browser": "webKit", "section": "heroOrSlider", "severity": "error", "problem": "viewportOverflow" }`. Grade signed draft pages, collection lists, collection items and the 404 page; live checks say `afterPublish`, never `pass`. Inspect forms without submitting. `cantRedirect` marks `?p=` shortlinks; `autoInsertedH1` is a notice, not a heading repair. Decorative `alt=""` is allowed; RSS pubDate must match the source. `captures` lists private category pictures at 360/375/390/768/900/1024/1280 in Chromium, plus 1280 in WebKit and Firefox (45 pairs, 90 attempted pictures per page); e.g. `{ "pageKey": "home", "category": "forms", "index": 0, "width": 1280, "browser": "webKit", "originalSha256": null, "keelSha256": null, "absent": true }`. A null pair explicitly means the category is absent; hashes identify private PNGs, never public storage links. If one picture is missing, omit the pair and report a capture failure, e.g. `kind: capture, problem: pictureMissing, section: forms`. Supplemental views carry `draftKind` and a pinned `sourceFileReference`, e.g. `{ "pageKey": "not-found", "draftKind": "notFound", "sourceFileReference": "404.html" }` (excerpt). Picture attempts and bytes count against the run limits, including superseded retries; `stop: requests` or `stop: artifactBytes` means a partial report. Repair receipts are unique by page and kind. A page is saved at a Keel address made from its old one (`/services.html` at `/services`); a page whose old address has none (`/?p=12`) is `declined` with needsYou `addressNotUsable`, and one whose address another page already takes gets `addressShared`. Neither blocks launch, e.g. `{ "key": "address-p12", "pageKey": "p12", "kind": "addressNotUsable", "blocksLaunch": false }`. A page's old addresses that no redirect rule carries to it (its own, or ones that led to it) are one `addressNotCarried` task naming them in `addresses`; the page itself may still be carried, and it does not block launch, e.g. `{ "key": "redirect-about", "pageKey": "about", "kind": "addressNotCarried", "blocksLaunch": false, "addresses": ["/about-us.php?id=3"] }`. A page with more than 201 such addresses names the first 201 and gives the total in `addressCount`; addresses for a page the report does not list are one site-wide task with key `redirects-not-carried` and no `pageKey`. When the crawl found more pages than a clone copies, one site-wide task with key `pages-not-copied` and kind `pagesNotCopied` blocks launch until the owner acknowledges it; `addresses` names the first 200 and `addressCount` how many there were, e.g. `{ "key": "pages-not-copied", "pageKey": null, "kind": "pagesNotCopied", "blocksLaunch": true, "addresses": ["/news/2019/01", "/news/2019/02"], "addressCount": 340 }`. When the crawl used a browser (a site drawn by JavaScript), the report carries `rendering`, copied from the crawl: the `decision` (`method` fetch, render or mixed, `reason`, `decidedBy` model or rule), `renderedPages`, `pagesNotDrawn` (each also listed by `pages-not-copied`, with `reason` `noPageThere`, `tooLong`, `tooLarge`, `needsOutsideService`, `couldNotDraw` or `plainHttp`), `refusedHosts` (host names only, at most 64, `an IP address` for an address) and `phaseCapReached` (the 15-minute drawing limit), e.g. `"rendering": { "decision": { "method": "render", "pagesToRender": [], "reason": "identicalShells", "decidedBy": "model" }, "renderedPages": 6, "pagesNotDrawn": [{ "sourcePath": "/pricing", "reason": "noPageThere" }], "refusedHosts": [{ "host": "api.zoomvault.io", "requests": 3 }], "phaseCapReached": false }`; it is absent when no browser was involved. A crawl where no page could be drawn stops with `siteRefused` and category `pages-not-drawn`. A clone whose container Keel could not start (Azure refused it for authorization or configuration) stops at once with `workerUnavailable` and category `container-start-refused`: a problem on Keel's side, not the site's; it is not retried, the owner cannot resume it, and a system administrator retries it once fixed. A container lost twice before it claimed its step stops the same way with `container-not-started`. A clone stopped because the clone service was off or not ready carries `keelRefused` with `disabled-service` and resumes once it is back; one that waited on Keel's capacity until its approval ran out carries `keel-busy`. These Keel-side stops give the free clone back at once and a resume takes it again. A queued clone's status may say why it waits, e.g. `{ "status": "queued", "waiting": "Keel is busy with other clones right now, so this one hasn't begun yet. ..." }`.

## Importing a site

1. Back up the destination first: approved siteAdmin tokens may `POST /api/sites/{siteId}/snapshots` with `{"name":"Before import"}`. A 202 queues it; poll `GET /api/sites/{siteId}/snapshots/{snapshotId}` until ready before writing. For site imports and custom designs, also read the skills at `/openapi/skills/site-import.md` and `/openapi/skills/web-design.md` (index: `/openapi/skills`).
2. Read design and Sizes and limits; batch within them. Layouts allow 50 regions, e.g. `{"regions":[{"key":"hero","label":"Hero"},{"key":"main","label":"Main"}]}`. Use returned ETags as If-Match on updates. Operator archive starts require a system administrator who owns an internal account; agents and bots cannot start them. For example, an operator names `archives/11111111-1111-1111-1111-111111111111/manifest.json` and its SHA-256 in `sourceArchive` at `POST /api/system/clones/accounts/{accountId}/archive-start`. An operator can instead list saved copies at `GET /api/system/clones/accounts/{accountId}/saved-copies` and send only `"savedCopyId":"11111111-1111-1111-1111-111111111111"`; the server re-reads that copy's manifest. Internal starts add `"reason":"North Shore Bakery migration"` (3 to 200 characters, else 400 naming `reason`) and need no TXT record. A customer start has no archive input or reason. Redesign reference evidence contains home plus two pages per site; RD2 derives style separately.
3. Convert `<p style="color:red">Words</p>` to `<p class="intro">Words</p>` plus Theme CSS `.intro { color: red; }`. Otherwise 400 names e.g. `regions.hero[2].data.html`, `values.body`, `partials[0].source` or `layouts[0].source`: "Inline styles aren't kept. Give the element a class and style it in the theme." Admin paste removes styles and says "Text formatting from the pasted text wasn't kept. Use the text tools or the theme." Unchanged stored parts, layouts and shared design parts are exempt; word edits keep existing page-part styles, but new or changed styles are refused.
4. Remove `<script src="source.js"></script>`, `onclick="run()"` and javascript:/vbscript: links: named 400, "Scripts aren't kept in page content. For a widget, use an Embed part. For a script on every page, move it to Theme > Site script." Theme script, platform JSON-LD and analytics keep their paths; Preview excludes analytics. JSON-LD bodies keep valid literal JSON (including `<` in strings), and allow mixed JSON, Liquid outputs and tags, e.g. `<script type="application/ld+json">{%- include 'software-json-ld' -%}</script>`. Literal JSON `<` is escaped as `\u003c` on output, including a `</script>` inside a JSON string. For example, `<script type="application/ld+json">{"name":"<"}</script>` keeps the name `<` after JSON decoding. Invalid JSON returns 400 naming `source` (or `layouts[i].source` / `partials[i].source` in PUT /design): "This structured data isn't valid JSON. Fix the JSON inside the application/ld+json script." Mixed Liquid bodies still allow no raw <; the resulting JSON is checked on save and publish.
5. Keep clean icons, e.g. `<svg viewBox="0 0 1 1"><path d="M0 0h1v1z"/></svg>`. SVG references allow only #fragments or data images; `<svg><use href="https://other.example/icon.svg#x"/></svg>` is refused. `<h{{ level }}>` is refused at save; use `{% if level == 3 %}<h3>Words</h3>{% else %}<h2>Words</h2>{% endif %}`.
6. Create parent pages first: `/about` before `/about/team`. `PUT /api/sites/{siteId}/pages/by-slug` with `{"path":"/about/team","title":"Team","layoutKey":"homepage"}` returns 400 `parent-page-missing` with `parentPath: "/about"` if missing. Create parentPath, retry; publish parents first too.
7. Send known members, including nested bodies. No typed agent API body is exempt. Strict member checks apply to site API writes and agent/bot access request bodies. Account, passkey, webhook and provider payloads keep their contracts. `POST /api/agent/token` with `{"proof":{"unexpected":true}}` returns 400 at `proof.unexpected`. Raw PUT /design uses DesignDocumentReader and accepts documented GET read-only members; dynamic data, values, schemas, menus and theme tokens use schema validators. `PUT /api/sites/{siteId}/pages/{pageId}` with `{"layoutId":"00000000-0000-0000-0000-000000000001"}` returns 400 at layoutId naming `POST /api/sites/{siteId}/pages/{pageId}/layout`; send that body there with If-Match. That PUT takes only `title`, `regions`, `seo`, `isNotFoundPage` and `dropOrphanedRegions`; `slug` returns 400 naming `.../rename` (send `{ "slug": "shop" }` there) and `parentPageId` names `.../move`. By-slug, item create/upsert and design writes also refuse unknown members.
8. Preserve dates as siteAdmin: `{"publishedAt":"2020-01-02T10:00:00Z","modifiedAt":"2021-03-04T12:00:00Z"}` on page/item publish; omitted dates use normal dating. Item create/by-slug upsert also accepts both with `{"slug":"first","title":"First"}`; these save draft metadata, so publish separately. Crawl/archive pages carry source `publishedAt` (including RSS `pubDate`) and `sourceAliases`, e.g. `["/?p=231"]`, for reporting addresses that cannot redirect. A same-day RSS time fills day-only metadata; explicit source times stay. Missing source dates stay unknown. Saved HTML keeps decorative `alt=""` distinct from missing alt; preserve it. Crawl/archive `originAliases` records bare/www or HTTP-to-HTTPS addresses, e.g. `{"sourceOrigin":"https://www.example.com","originAliases":["https://example.com"]}`. At most three redirects resolve the origin before exact-origin crawling. `ScanTooLarge` means too large to scan and refuses that file; scanner outages stop the source.
9. Set `"pathStylePagination":true` in the complete current `PUT /api/sites/{siteId}/collections/{key}` body for `/news/2`; false uses `/news?page=2`. Move page/redirect conflicts first. Required acknowledgement uses `{"name":"terms","type":"agreement","label":"I agree to the terms."}`: always required, never pre-ticked. Marketing consent stays optional.
10. Preview: `POST /api/sites/{siteId}/collections/{key}/items/{itemId}/preview` with `{}` or `POST /api/sites/{siteId}/preview/not-found` without a body; open the returned url. Publish design, parents, pages, items; check Live too. Remove unused design using `DELETE /api/sites/{siteId}/layouts/{layoutId}` or `DELETE /api/sites/{siteId}/partials/{partialId}`, with current If-Match, no body. Read id/ETag and inspect uses first: referenced design is refused with usage information; deletion is immediate.
