Skip to main content

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
});
  • claim or claimId, at least one. claim is how the demo and every host work: the page sends the document it is showing. claimId loads from the store; the Prompt Lab uses it.
  • messages is the visible conversation: text, and the files attached to each question. Tool round-trips never appear here; they live inside one request.
  • capability makes the last user message a quick action: the system prompt carries that capability's playbook.
  • promptOverrides are the browser's active Prompt Lab versions, plus any per-run edits. The server applies them unless PROMPT_OVERRIDES is off, never to system.safety, and drops unknown ids and over-long values.
  • screenActions says the caller can carry out client_action events. Without it, the model is never offered highlight_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 text file carries text and never data; any other kind carries data (on the latest question) or digest (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_BYTES and MAX_PDF_PAGES, and /api/health reports 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.

typeFieldsMeaning
text_deltatextA chunk of the answer, to append
activitytool, labelA tool started. label is the present-tense chip: Reading the policy…
tool_resulttool, summaryA tool finished. summary is its result, truncated to 400 characters, for the lookups trace
client_actionactionSomething for the browser to do on the screen
attachment_readid, digestAn 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
doneusage?, model?, turnId?, prompts?, unmatched?, unmatchedInContext?, workedOut?The turn is complete
errormessageThe 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_panel scrolls to, pulses and outlines [data-panel="<panel>"] in the page. panel is one of MATTER_PANELS: home, schedule, documents, finance, involvements, proceedings, strategy, finance_resolution, mi, system_checks, key_facts, schedule_table, proceedings_table, notes.
  • navigate is defined for later use. The demo passes its router's navigate; an embedded host passes nothing, so it is ignored there. No tool emits it today.

FeedbackRequest​

The body of POST /api/feedback.

FieldTypeNotes
turnIdstring, 8 to 64From the done event; minted by the browser for voice answers
ratingup | down | nullnull withdraws
reasonsFeedbackReason[]Default []. Kept only for down
notestring ≤ 2,000Kept only for down
claimIdstring ≤ 100
capabilitystring ≤ 64
channeltext | voicerequired
surfaceapp | embedrequired
locale, brandas in ChatRequest
modelstring ≤ 100
promptFingerprintstring ≤ 32
promptOverriddenstring[] ≤ 50The prompt ids behind the fingerprint
questionstring ≤ 20,000Omitted for embed votes without feedback-content
answerstring ≤ 40,000Likewise
tools{ tool, summary }[] ≤ 40Likewise

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.