Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

30.0 KB
Raw Blame

kwant 0.7.7 API: ready-made teams (T) and team discovery (D)

Lin, 2026-11-07 (revised with the tests: clashes list, edit codes, limits; then decisions.md: A5 needs_done, the tighter Q-D10, the shared clock in §7). Branch lin-077-teams (from main 266032e). Spec: next-077/spec.md §T, §D. Design: next-077/design/design.md. Tests: next-077/qa/test-plan.md §1, §1b. Where this file and design.md disagree on a field name, this file is what the server does; the differences are listed in §8.

Conventions (same as the rest of /api):

  • Every route takes ?space=<id> (default spc_default), the usual Scope.
  • Errors are {"error": "<plain sentence>", "code": "<snake_case>"}, plus field and suggestion where §5 says so.
  • Person only means a bot's turn token or a connected agent's token gets 403 {"error": "only the person can do this"} before the handler runs (the person_only list in src/server/auth.rs).
Route Who
GET /api/team-templates anyone with the API token, agents too (Q-T9)
GET /api/team-templates/:id/preview person only
POST /api/teams/from-template person only
POST /api/teams/suggest person only
DELETE /api/teams/suggest person only (0.9.5: stops a draft from words)
GET /api/teams/:id/template person only
POST /api/bot-actions/:action_id/undo person only (unchanged route; Undo for a template team goes through it)

1. GET /api/team-templates?space=

The catalogue. Static data from src/teams/templates.rs (which embeds Mira's generated templates.json byte for byte), plus one per-space flag. Cache it on the client for the offline preview.

{
  "templates": [
    {
      "id": "inbox",
      "label": "Inbox",
      "icon": "inbox",
      "handle": "inbox",
      "card_line": "Sorts your mail and drafts replies for you to send.",
      "mission": "Keeps one inbox under control: …",
      "used_in_space": false,
      "bots": [
        {
          "slot": "InboxManager",
          "preset": "support",
          "name": "InboxManager",
          "title": "Inbox Manager",
          "line": "Reads new mail, sorts it, and tells you what needs you today.",
          "avatar_sprite": "tech_lead",
          "lead": true,
          "good_for": ["Sorting new email", "…"],
          "not_for": ["Sending or forwarding email on its own", "…"]
        }
      ],
      "needs": [
        {"id": "email", "label": "Connect email", "why": "So InboxManager can read new mail. Read-only (IMAP).",
         "required": true, "opens": "loose_ends_imap", "done_when": "An IMAP source in Loose ends checks OK"}
      ],
      "never": ["Sends, forwards or replies to mail. It drafts; you send.", "…", "…"],
      "skills": [
        {"owner": "InboxManager", "name": "Morning inbox digest", "description": "…", "body": "Goal\n…"}
      ],
      "routine": {"name": "Inbox digest", "when": "Weekdays at 8:00", "bot": "InboxManager", "enabled": false},
      "first_prompts": ["What needs me today?", "Here's how I usually sound in email: ", "Draft a polite no to the latest invitation"]
    }
  ]
}
  • Order: inbox, sales, coding. routine is null for Coding.
  • slot is the bot's key in names (§3). It is the template's own name for that bot and never changes. Not the preset: Coding has two backend bots (TechLead and Backend), so a preset can't be a key.
  • skills[].body is included so the preview's Read works offline.
  • used_in_space: a team in this space was made from this template and not undone (T10's "already used here").
  • Persona, SOUL and the pinned instructions are not served; the server writes them at create.
  • Sales' required need (A5): {"id": "what_you_sell", "label": "Tell the team what you sell", "why": "Three short answers in this chat. Leads are only as good as this.", "required": true, "opens": "composer_prompt", "done_when": "The person has posted a message in @sales"}. composer_prompt means: focus the team chat's composer (with the Sell starter). It is the only composer_prompt need. The server reports it done in needs_done (§6) once the person has posted in the team chat; a bot's message doesn't count.
  • No taken list: the client uses the bots and teams it already has (design's preferred option). …/preview gives the server's answer.

2. GET /api/team-templates/:id/preview?space=

The server's free names for this space, for the sheet's clash state (T9). Read-only; makes nothing.

{
  "template_id": "inbox",
  "handle": "inbox2",
  "handle_wanted": "inbox",
  "names": {"InboxManager": "InboxManager", "Drafter": "Drafter2", "Researcher": "Researcher"},
  "clashes": [
    {"field": "handle", "wanted": "inbox", "suggestion": "inbox2"},
    {"field": "names.Drafter", "wanted": "Drafter", "suggestion": "Drafter2"}
  ]
}
  • Taken names: any bot in the space with that name ignoring case, plus a pending hire proposal of that name (the create_clash rule, Q-T11).
  • Taken handles: a live team in the space with that name ignoring case, or a live channel called team-<handle>. An archived team chat is renamed archived-team-…, so it doesn't hold the handle.
  • Next free: Drafter → Drafter2 → Drafter3 …; inbox → inbox2 …. A name that already ends in a number counts on from it instead of gaining a digit: TechLead4 → TechLead5 (or the next free one), Agent007 → Agent008, inbox-2 → inbox-3. No space before the number (design A3).
  • 404 {"code": "unknown_template"} for an unknown id.

3. POST /api/teams/from-template?space=

Creates the whole team in one transaction: bots, their Good for / Not for, the team and its chat, pinned instructions, starter skills (on, owned by one bot each, A7), and the routine (off). Then one logged action (team_template) for Undo. Nothing on disk. Never turns Dev mode on (Q-T12), never adds tools or changes approvals (T6).

Header Idempotency-Key: <client uuid> (optional, recommended): the same key in the same space within 24 h returns the first result (201 with the same body) and creates nothing new. A double click is safe. The same key with a different body is refused with 422 idempotency_key_reused and nothing is made: a new team needs a new key. Bodies are compared as JSON, so spacing and key order don't count.

3a. From a template (T)

{
  "template_id": "inbox",
  "handle": "inbox",
  "names": {"Drafter": "ReplyDrafter"}
}
  • handle optional, default the template's. Lower-case slug: [a-z0-9-]{1,40}, starting with a letter or digit. The client slugs as you type ("Inbox Team" → inbox-team); the server doesn't, it refuses (400 bad_handle).
  • names optional; keys are slots from §1, missing slots keep the template name. Same rules as any bot name: no whitespace, no @, 1–40 characters.
  • Never renames silently (Q-T7): a taken name or handle is a 409 with the server's suggestion (§5), and nothing is made.

3b. From a suggestion (D)

{
  "suggestion_id": "sug_7f3c…",
  "edits": {
    "handle": "shop",
    "rows": {
      "lead":     {"name": "TechLead"},
      "frontend": {"use_existing": "<kwant_id>"},
      "qa":       {"on": false},
      "writer":   {"on": true},
      "sre":      {"preset": "backend", "name": "Platform"}
    }
  }
}
  • rows keys are the keys from the suggestion (§4), for bots[] and also_possible[] alike. A row not mentioned keeps its suggested state: bots[] on, also_possible[] off.
  • Per row, all optional: on (bool), name, preset (one of the D presets, §4), use_existing (a live bot id in this space, or null for New bot).
  • edits and each row are strict: any other field (persona, soul, instructions, title, …) is a 400 unknown_field (Q-D6a). The server builds every persona from the preset plus its own facts.
  • The lead row can't be turned off (400 lead_required, A14), and keeps its preset (400 bad_row). At most 6 bots on (400 too_many_bots); at least 2 for a new team and 1 when adding to a team (400 too_few_bots).
  • A row key that isn't in the suggestion, or a row that isn't an object: 400 bad_row. One bot can fill one row: the same use_existing twice is 400 bad_existing.
  • handle or names at the top level next to suggestion_id: 400 unknown_field (they go in edits). edits next to template_id: 400 unknown_field.
  • A refused create (any 4xx, a clash, or a failed transaction) gives the suggestion back; only a 201 uses it up.
  • use_existing (D6, A16): that bot joins the team unchanged; its persona is not touched. The stack line goes into the team instructions instead.
  • A suggestion made for an existing team (team_id in §4) adds the ticked bots to that team (A18). handle is then refused (400 unknown_field), and Undo removes only the bots it added.
  • A suggestion is used up by the first successful create (Q-D6c). Using it again, or after 1 hour, is 410 suggestion_expired (A17: the client reads the project again and re-applies its edits).
  • template_id: "coding" with suggestion_id is the Coding template with a project (T1): the roster comes from the suggestion and the team also gets the Coding starter skills, each on the row that took that bot's role. Any other template_id with suggestion_id is 400 bad_request; neither of them is 400 bad_request too.

Response 201

{
  "team": { "...": "the usual Team row (GET /api/teams/:id)" },
  "channel_id": "…",
  "action_id": "…",
  "template_id": "inbox",
  "bots": [{"slot": "InboxManager", "id": "…", "name": "InboxManager", "preset": "support", "lead": true, "existing": false}],
  "skills": [{"id": "…", "name": "Morning inbox digest", "owner_id": "…"}],
  "routine": {"id": "…", "name": "Inbox digest", "enabled": false},
  "undo_until": "2026-11-08T10:00:00Z"
}
  • For D, template_id is "coding" when it came from the Coding template, else null, and slot is the row key.
  • channel_id is the team chat to open. The Needs card is the client's overlay (Q-T5), not a message, so the chat starts empty.
  • The client gets the usual team, kwant and bot_action events too.

4. POST /api/teams/suggest?space=

Reads the project. No model call. Nothing is made, and nothing stays on disk.

{"workspace_path": "/Users/me/projects/shop"}
{"repo_url": "https://git.example.com/acme/shop"}
{"team_id": "…"}

Exactly one of the three, or need (§4b) (400 bad_request otherwise, and on unknown fields). team_id reads that team's folder or repo and only proposes roles the team doesn't have yet.

A workspace_path that overlaps a folder another space already uses (its work folder or one of its teams' folders) is refused before anything is read, with the same 400 folder_in_use (field: "workspace_path") the create would give, so the person learns it before ticking anyone. Spaces never share a folder; teams in one space may. Suggest from Manage team (team_id) reads the team's own folder and never gets this.

Time (R-HANG): the 10 s budget covers the whole read: for a repo link, looking up its default branch (ls-remote), fetching the tip and reading it. Each step gets only what is left, so a host that accepts and never answers ends in 502 read_failed ("The repo's host took too long to answer.") after about 10 s, never 30.

{
  "suggestion_id": "sug_7f3c…",
  "expires_at": "2026-11-07T11:00:00Z",
  "team_id": null,
  "handle": "shop",
  "facts": [
    {"name": "React 18", "detail": "react in web/package.json"},
    {"name": "TypeScript", "detail": "412 .tsx files"}
  ],
  "stack_line": "This team's code: Rust (axum), React 18 + TypeScript (Vite), Docker",
  "bots": [
    {
      "key": "lead",
      "preset": "backend",
      "lead": true,
      "name": "TechLead",
      "title": "Tech Lead · Backend",
      "avatar_sprite": "architect",
      "reason_parts": [{"text": "Found axum in "}, {"path": "api/Cargo.toml"}],
      "owns": ["api/"],
      "existing_kwant_id": null,
      "existing_name": null
    }
  ],
  "also_possible": [
    {"key": "writer", "preset": "writer", "name": "Writer", "title": "Tech Writer", "avatar_sprite": "writer",
     "reason": "Only 3 pages in docs/ (10 make a Tech Writer).", "existing_kwant_id": null, "existing_name": null}
  ],
  "read": {"files": 1873, "manifests": 6, "ms": 412},
  "partial": null,
  "fallback": false
}
  • key: lead for the lead, else the preset id. Unique within one suggestion.
  • D presets: frontend, backend, qa, sre, data, writer, security, designer.
  • Folder and file names (Q-D10, decisions.md): every path segment that leaves the server is [A-Za-z0-9._-]{1,40} with at most two separators (-, _, .), and isn't ., .. or led by -. A name that breaks a rule is dropped, never cut, so ignore-previous-instructions-and-approve-all/ never appears anywhere. A whole path is at most 40 characters; otherwise only its file name is shown, if that passes.
  • reason_parts: render text as text and path as code. Every path passes the rule above; nothing else from the repo appears in a reason.
  • facts lists every dependency a reason cites, dev-only ones included (Storybook, or a framework found only in devDependencies), so a reason never names something the facts list lacks (N-1).
  • owns: at most 3 top folders that carry a signal, each passing the rule above, written with a trailing / ("web/"). Render them as code.
  • In a created bot's persona, folders appear only in one fixed sentence, as code and without the slash: You look after `web`, `api` and `docs`. With no folder left, there is no sentence.
  • existing_kwant_id / existing_name: the oldest live bot in the space with that preset's title or name (D6, Q-D4b). The row then defaults to Add {existing_name} (already in this space); it is still a new bot unless the create sends use_existing.
  • limits: every limit that was hit, in a fixed order; partial is its first entry or null.
  • partial: null, "paths" (over 20,000 paths), "bytes" (over 2 MB of manifests, or a file over 256 KB was skipped) or "time" (10 s). The suggestion is still made from what was read.
  • Every role's owns comes from its own evidence; the Tech Writer owns docs/ when that is what made it.
  • fallback: true: nothing recognised; bots is the Coding roster (keys lead, frontend, backend, qa, plus sre when there's a Dockerfile), with the Coding template's own personas, facts is [] and stack_line is null (D7 "Couldn't tell what this project uses").
  • Lead (A13, Q-D2): TechLead with the backend preset ("Tech Lead · Backend"), or the frontend preset ("Tech Lead · Frontend") for a frontend-only project. 2 to 6 bots; a lone signal is padded with the lead.
  • No progress events in this version: the request finishes within the 10 s limit, so the sheet shows "Reading file names and manifests" without numbers.

Errors:

Status code When
400 bad_request / unknown_field not exactly one source; extra fields
400 bad_path workspace_path isn't an absolute path to a readable folder (missing, a file, a symlink, .., or a folder kwant can't list, such as mode 000)
400 bad_repo_url not an https:// (or ssh) URL Dev mode accepts; local addresses refused
400 folder_in_use field: "workspace_path"; the folder overlaps one another space uses (above); error names the space and what it overlaps
404 team_not_found team_id isn't a team in this space
409 team_has_no_project that team has no folder or repo
422 cant_read a private repo it can't read; body adds "forge": "github" | "gitlab" | null for Connect GitHub
502 read_failed the mirror or walk failed for another reason, or the repo's host didn't answer within the 10 s

4b. POST /api/teams/suggest?space= with need (0.9.5, team from words)

{"need": "I run a small bakery and drown in orders and emails."}

Drafts a team from the person's own words in one model call, on the first ready account of the space in the Accounts order failover uses (priority, then oldest). The call has no tools, sees no chat history, runs in an empty scratch folder that is removed afterwards, and must answer one JSON object within about 90 s. An answer that can't be used (no JSON object, no bots, fewer than 2 usable bots) is asked for once more with the reason; a second bad answer is 502 draft_failed. An account that refuses (usage limit, signed out) is recorded like a failed turn and the next ready account is tried (at most 3).

The words are 10 to 1000 characters after trimming. The model's answer is untrusted text; the server keeps only what passes:

  • 1 lead and 2 to 6 bots. The first bot marked lead (else the first bot) leads and comes first. More than 6 are trimmed to the lead and the first 5 others, and trimmed says how many were dropped (a refusal would cost the person another 90 s for something the server can fix).
  • Names are one word (letters, digits, -, _, at most 40), from the title when the name is unusable, then made free in the space (TechLead → TechLead2), and unique within the draft. Titles at most 60 characters, reasons 200, the description 160; at most 4 owns and 4 avoids of 60 characters. Instructions (the bot's soul) at most 4096 bytes. A bot without a title or instructions is dropped.
  • preset is a known preset id, else custom; avatar one of the presets' avatars, else the preset's own.
  • Nothing else is read from the answer: no tools, accounts, logins, schedules or routines.
  • The handle is server-picked: the team name's slug made free (bakery-desk, bakery-desk2), else team.

The answer is the §4 shape with need (the trimmed words), facts: [], stack_line: null, also_possible: [], read: {"files": 0, "manifests": 0, "ms": …}, partial: null, limits: [], fallback: false, trimmed, and each bot row carrying owns, reason, reason_parts (one text part) and read-only instructions. Row keys are lead, else the name's slug (orderkeeper), unique.

The server keeps the drafted instructions, avoids, description and words with suggestion_id. from-template builds from that copy plus the §3b edits (names, on/off); a preset edit on a drafted bot is 400 bad_row, since the instructions belong to the drafted role. Each bot gets its known preset's persona (or "You are {name}, the team's {title}."), the drafted instructions as its soul, and owns / avoids as its covers and avoids. The team gets icon users, the drafted description, and channel instructions that quote the words and keep sending, spending and deleting with the person. template_id: "coding" with a drafted suggestion is 400 bad_request. Undo is the usual one step.

One draft per space at a time. DELETE /api/teams/suggest?space= stops it and answers 204, also when nothing runs; the stopped request answers 409 cancelled. A client that goes away stops its draft too.

Status code Extra When
400 bad_request need isn't a string
409 busy a draft is already running in this space
409 cancelled DELETE stopped this draft
409 no_ready_account no account is ready (none signed in, all off), or every one tried was signed out
422 need_too_short / need_too_long under 10 or over 1000 characters after trimming
429 account_limited account (name), until (RFC 3339) every account that could run it is out of usage; error says until when, in local time
502 draft_failed two unusable answers, an engine error, or no answer within about 90 s

5. Errors from from-template

Status code Extra When
400 bad_request neither or both of template_id, suggestion_id
400 unknown_field field any field not listed above (top level, edits, a row)
400 bad_name field: "names.<slot>" or "edits.rows.<key>.name" whitespace, @, empty or over 40
400 bad_handle field: "handle" not a lower-case slug
400 bad_preset / bad_row / lead_required / too_many_bots / too_few_bots field D edits
400 bad_existing field use_existing isn't a live bot in this space
400 folder_in_use field: "workspace_path" the new team's folder overlaps one another space uses; Suggest already said so (§4)
404 unknown_template
404 unknown_space ?space= isn't a space
404 team_not_found an add-to-team suggestion whose team was deleted since
409 handle_taken field: "handle" ("edits.handle" for D), suggestion: "inbox2", clashes[] the handle is taken
409 name_taken field: "names.Drafter" ("edits.rows.<key>.name" for D), suggestion: "Drafter2", clashes[] a bot name is taken (or two slots got the same name)
410 suggestion_expired unknown, used, or over 1 hour old
422 idempotency_key_reused this Idempotency-Key already made a team from another body (§3)
423 space_archived
500 create_failed the transaction failed; nothing was made

A 409 names every clash in one answer. code, field and suggestion describe the first (the handle first, then the bots in roster order); clashes[] lists all of them in the preview's shape:

{
  "error": "that team name is taken; coding2 is free",
  "code": "handle_taken",
  "field": "handle",
  "suggestion": "coding2",
  "clashes": [
    {"field": "handle", "wanted": "coding", "suggestion": "coding2"},
    {"field": "names.TechLead", "wanted": "TechLead", "suggestion": "TechLead2"},
    {"field": "names.QA", "wanted": "QA", "suggestion": "QA2"}
  ]
}

Suggestions never repeat within one answer, and never name a bot another slot of the same request asks for. Nothing is made. Sending the suggestions back as handle and names goes through unless something else took them in between.

6. Undo (T4)

POST /api/bot-actions/:action_id/undo with the action_id from §3. The response is the action, status: "undone", as for every bot action.

Before it, the sheet's confirm reads GET /api/teams/:id/template:

{
  "template_id": "inbox",
  "action_id": "…",
  "created_at": "2026-11-07T10:00:00Z",
  "undo_until": "2026-11-08T10:00:00Z",
  "can_undo": true,
  "blocked": [],
  "removes": {
    "bots": ["InboxManager", "Drafter", "Researcher"],
    "skills": 2,
    "routines": 1,
    "handle": "inbox"
  },
  "chat_messages": 4,
  "archived_chat": "archived-team-inbox-2",
  "also_in": [{"bot": "Drafter", "team": "support"}],
  "edited_skills": [],
  "needs_done": []
}

archived_chat: the name Undo will give the team chat when it keeps it (it has messages): archived-team-<handle>, or with -2, -3… when that name is taken, ignoring case. null when Undo deletes the chat (no messages) or doesn't touch it (an existing team). It's worked out from the chats as they are now, so a chat made with that name before the person clicks Undo can still move it on by one.

needs_done: ids of the template's Needs (§1) the server can see are done. Today that's only the composer_prompt need, Sales' what_you_sell (A5): done once the team chat has a message from the person. The other Needs (connect email, a CRM, a repo) are ticked by the client from its own state, as before.

404 not_a_template_team when the team wasn't made by a template or a suggestion (or was made before 0.7.7).

What Undo does, in one transaction:

  • Removes the bots it made (renamed or not), their skills and routines, the team and the routine. Bots reused with use_existing are left alone and only leave the team.
  • The team chat: deleted when it has no messages, otherwise archived as a team delete does today (archived-team-<handle>). Its own path; the hire Undo is unchanged (Q-T3).
  • A bot that was added to another team since leaves that team (also_in).
  • Edited starter skills are removed too; edited_skills names them so the confirm can say so (Q-T2).

Undo refuses (409, nothing changes) when:

code When
undo_expired over 24 hours since create (Q-T1)
bot_leads_elsewhere a bot it made now leads another team or channel; blocked lists them. An archived team chat (#archived-team-…, left when its team was deleted) doesn't count (T-U10): Undo hands its lead to a bot that stays
(existing) the action is already undone, or a newer change to the same team must be undone first

blocked and can_undo in GET …/template say the same before the person clicks.

7. Test seams (only with the test-seams feature; ignored by release and make run builds)

Seam What
fail_after: Option<Step> argument of the create transaction (production passes None; public so integration tests reach it): fails after Bot(n), Team, Skills, Routine or Action, then rolls back (Q-T8)
KWNT_TEST_NOW_OFFSET_SECS shifts "now", in signed seconds, through the one shared clock below (Q-X1)
KWNT_DISCOVER_TIMEOUT_MS shortens the 10 s read budget (Q-D9a)

There is no loopback seam: 127.0.0.1 and other local addresses are refused in every build (git::blocked), so a test of a remote repo serves it on a LAN address.

The one clock (Q-X1): src/clock.rs

Every window a test has to cross reads "now" from kwnt::clock::now(). Nobody adds a second clock.

Who Window Call
T (Lin) 24 h template Undo clock::now() (db::team_templates::now re-exports it)
D (Lin) 1 h suggestion expiry clock::now()
G (Juno, 0.7.8) 10 min pairing code; 5 bad codes in 10 min lock clock::now()
S (Vega, 0.7.9) 7-day deletion of unreviewed steps clock::now()
  • kwnt::clock::now() -> DateTime<Utc>: Utc::now() plus the offset.
  • kwnt::clock::offset_secs() -> i64: the offset. It is always 0 without the test-seams feature.
  • The offset is KWNT_TEST_NOW_OFFSET_SECS (read on every call, so a QA run can move a running server) plus kwnt::clock::set_test_offset(secs) (in-process, for Rust tests; 0 puts it back). Both, and KWNT_DISCOVER_TIMEOUT_MS, are ignored unless the cargo feature test-seams is on. cargo test turns it on through Cargo.toml's dev-dependency on kwnt itself; a QA or e2e server that moves the clock must be built with cargo build --features test-seams (or cargo run --features test-seams -- serve). A plain debug build (make run), a release build and the Docker image ignore them, so nobody who can set the server's environment can move the expiry clock (#399 review H1).
  • set_test_offset is process-wide, so a test that uses it lives in its own test binary (as tests/team_expiry_test.rs does).
  • Store times from clock::now() too, so stored and compared times move together.
  • server::dev::now() (the Dev mode daily cap, 0.7.x) predates this and is unchanged.

8. Where this differs from design.md or the test plan

Topic design / test plan This API Why
Rename map key (A10) names: {preset: name} names: {slot: name}, slot = template bot name Coding has two backend bots
Handle taken (Q-T11) archived teams' handles count only live teams and live team-<handle> chats an archived chat is renamed, so the handle is free again
Undo route "Undo team" the existing bot-action Undo, plus GET /api/teams/:id/template for the confirm one Undo path, already person-only
Clash code (test plan T-A5, T-W9, Q-API1) 409 clash with clashes[] 409 name_taken / handle_taken (name_taken is what imports already answer) plus clashes[] with every clash one code family across kwant; the list is what the sheet needs
Idempotency (test plan §0.5, T-W9) idempotency_key in the body, required optional Idempotency-Key header; 400 bad_request when sent empty or over 200 characters a header keeps the body strict (unknown_field), and an older client without a key still works; the sheet always sends one
Templates source templates-copy.md templates.json embedded byte for byte from design/templates.js no hand copying

9. Errors, everywhere in the HTTP API (14d)

Every refusal under /api/ (any 4xx or 5xx) answers in one JSON shape:

{ "error": "<a plain sentence>", "code": "<snake_case>", "detail": "<optional>" }
  • A route's own code always wins (bad_name, exists, too_large, archived, ...), and so do its other fields (field, suggestion, max_bytes, person_only, ...).
  • A route that sends no code gets one from the status: bad_request (400 and any other 4xx), unauthorized (401), forbidden (403), not_found (404), method_not_allowed (405), conflict (409), too_large (413), unsupported_media (415), unprocessable (422), rate_limited (429), server_error (5xx).
  • A request kwant can't parse (a query, path or JSON body in the wrong form) gets a plain sentence, one of the codes bad_request, bad_json (the body isn't valid JSON), unsupported_media (not sent as application/json), too_large or unprocessable (valid JSON with the wrong fields or types), and the parser's own words in detail (at most 300 characters). For example GET /api/spaces/spc_default/docs/page?file=faq.md&page=abc: 400 {"error": "That request wasn't in the form kwant expected.", "code": "bad_request", "detail": "Failed to deserialize query string: invalid digit found in string"}.
  • A 409 that found a thing in another state names that state in both status and code (a fact accepted, a proposal stale, a suggestion dismissed).
  • Successful answers, downloads, streams (SSE, WebSocket), and error bodies over 64 KB or of unknown length are sent as the route wrote them. JSON-RPC answers (/api/mcp/...) keep their own error object.
  • The MCP transport endpoints (/api/mcp/agents, /api/mcp/gateway, /api/mcp/gateway/grok, /api/mcp/permission/:token, /api/mcp/self) are left alone entirely: MCP clients call them, and an unknown or revoked bearer there is still a bare 401 with an empty body. The management routes under /api/mcp/ (servers, OAuth, registry, suggestions) get the shape like any other route.

The layer is src/server/error_shape.rs, the outermost layer of the router.