Chat protocol
The wire protocol between the browser and the Worker is defined once, as zod schemas, in packages/shared/src/chat.ts and packages/shared/src/feedback.ts. Both sides import the same definitions.
ChatRequest
The body of POST /api/chat.
const ChatRequest = z.object({
claim: Claim.optional(),
claimId: z.string().optional(),
messages: z.array(ChatMessage).min(1).max(60),
capability: z.string().optional(),
promptOverrides: z.record(z.string(), z.string()).optional(),
locale: Locale.optional(), // 'en-GB' | 'en-US'
brand: Brand.optional(), // 'claimpilot' | 'clonepilot'
screenActions: z.boolean().optional(),
}).refine((r) => Boolean(r.claim ?? r.claimId), { message: 'Provide either claim or claimId' });
const ChatMessage = z.object({
role: z.enum(['user', 'assistant']),
content: z.string().max(20_000),
attachments: z.array(Attachment).max(5).optional(), // files attached to a user message
});
claimorclaimId, at least one.claimis how the demo and every host work: the page sends the document it is showing.claimIdloads from the store; the Prompt Lab uses it.messagesis the visible conversation: text, and the files attached to each question. Tool round-trips never appear here; they live inside one request.capabilitymakes the last user message a quick action: the system prompt carries that capability's playbook.promptOverridesare the browser's active Prompt Lab versions, plus any per-run edits. The server applies them unlessPROMPT_OVERRIDESisoff, never tosystem.safety, and drops unknown ids and over-long values.screenActionssays the caller can carry outclient_actionevents. Without it, the model is never offeredhighlight_panel.
Attachment
A file attached to a question (packages/shared/src/attachments.ts). See Attached files.
const Attachment = z.object({
id: z.string(), // minted by the browser; attachment_read names it
name: z.string(),
kind: z.enum(['image', 'pdf', 'text', 'audio', 'video']),
mimeType: z.string(), // for a binary kind, one of BINARY_MIME_TYPES
size: z.number(), // bytes sent (after shrinking), or characters of text
pages: z.number().optional(), // a PDF's page count
data: z.string().optional(), // base64: a binary kind, on the latest question only
text: z.string().optional(), // a text kind (email, Word and Excel arrive already converted)
digest: z.string().optional(), // a binary kind on an earlier question: its note, from attachment_read
from: z.string().optional(), // where it came from when it is not the file itself: "the email hire.eml"
});
- A
textfile carriestextand neverdata; any other kind carriesdata(on the latest question) ordigest(on earlier ones). - At most 5 files, and 14 MB of them, on one question; a PDF of at most 50 pages. The limits are
MAX_ATTACHMENTS,MAX_ATTACHMENT_BYTESandMAX_PDF_PAGES, and/api/healthreports them. - The Worker checks only the latest question's files. Earlier questions carry no file data, and any they did carry is ignored.
Events
ChatEvent is a discriminated union on type. The Worker writes one per SSE data: line, in the order they happen.
type | Fields | Meaning |
|---|---|---|
text_delta | text | A chunk of the answer, to append |
activity | tool, label | A tool started. label is the present-tense chip: Reading the policy… |
tool_result | tool, summary | A tool finished. summary is its result, truncated to 400 characters, for the lookups trace |
client_action | action | Something for the browser to do on the screen |
attachment_read | id, digest | An attached file has been read: digest is its note, cleaned. Keep it on the attachment and send it on later questions in place of the file |
done | usage?, model?, turnId?, prompts?, unmatched?, unmatchedInContext?, workedOut? | The turn is complete |
error | message | The turn failed; no done follows |
done
{
type: 'done',
usage?: { inputTokens: number; outputTokens: number; cacheReadTokens: number }, // summed over the turn's rounds
model?: string,
turnId?: string, // identifies this answer for feedback
prompts?: { fingerprint: string; overridden: string[] }, // 'default', or a 12-hex hash of the overrides that applied
unmatched?: string[], // figures in the answer that match nothing the model was given
unmatchedInContext?: { figure: string; before: string; after: string }[], // the same figures, each with the words around it
workedOut?: { figure: string; working: string; before: string; after: string }[], // figures found as a one-step sum, with it
}
The fields are optional in the schema so an older Worker remains readable; the current Worker always sends all seven. workedOut lists figures that match no lookup but are a sum or difference of two figures near them that do, with the sum in working ("£35,000 − £2,500"), quoted like unmatchedInContext. They are not in unmatched; the widget shows them as "Worked out: £32,500 = £35,000 − £2,500". unmatched is empty when every figure matched; the widget shows "Check before sharing" when it is not. unmatchedInContext has the same figures in the same order, each with up to six words either side of it in its sentence (markdown removed, … where the sentence goes on), so before + figure + after reads as it does in the answer. The widget quotes each one that way, and falls back to the bare unmatched list from a Worker that does not send the context. See the figure check. An answer without a turnId cannot be rated.
Ordering
A turn with one tool round looks like this:
activity → tool_result → (client_action…) → [next round] → text_delta… → done
With files attached, each binary file is read first, before the first round:
activity (read_attachment) → attachment_read → tool_result (read_attachment) → … the turn as above
Activity for every call in a round comes before the next round's text. The browser inserts each activity chip before the streaming answer, so the answer reads as the conclusion.
Refusals
A request that is refused never becomes a stream. POST /api/chat answers with JSON and a status instead: {"error": "<a sentence>", "code": "invalid_request" | "unknown_capability" | "attachment_not_accepted" | "attachment_invalid" | "attachment_too_large" | "claim_not_found" | "not_configured"} with 400, 400, 400, 400, 413, 404 or 503. The client turns it into an ApiError carrying status and code (frontend/src/lib/api.ts).
ClientAction
const ClientAction = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('highlight_panel'), panel: z.string() }),
z.object({ kind: z.literal('navigate'), path: z.string() }),
]);
highlight_panelscrolls to, pulses and outlines[data-panel="<panel>"]in the page.panelis one ofMATTER_PANELS:home,schedule,documents,finance,involvements,proceedings,strategy,finance_resolution,mi,system_checks,key_facts,schedule_table,proceedings_table,notes.navigateis defined for later use. The demo passes its router'snavigate; an embedded host passes nothing, so it is ignored there. No tool emits it today.
FeedbackRequest
The body of POST /api/feedback.
| Field | Type | Notes |
|---|---|---|
turnId | string, 8 to 64 | From the done event; minted by the browser for voice answers |
rating | up | down | null | null withdraws |
reasons | FeedbackReason[] | Default []. Kept only for down |
note | string ≤ 2,000 | Kept only for down |
claimId | string ≤ 100 | |
capability | string ≤ 64 | |
channel | text | voice | required |
surface | app | embed | required |
locale, brand | as in ChatRequest | |
model | string ≤ 100 | |
promptFingerprint | string ≤ 32 | |
promptOverridden | string[] ≤ 50 | The prompt ids behind the fingerprint |
question | string ≤ 20,000 | Omitted for embed votes without feedback-content |
answer | string ≤ 40,000 | Likewise |
tools | { tool, summary }[] ≤ 40 | Likewise |
FeedbackReason is one of incorrect, missed, off_target, unclear, unsafe, other. See Answer feedback.
The embed's DOM event
<claimpilot-assistant> dispatches claimpilot-feedback (bubbling, composed) with the full FeedbackRequest as event.detail, including the question and answer whatever is stored.