WebSocket Protocol Reference¶
This document is the complete reference for the WebSocket protocol between the Modeling Agent (backend) and the BESSER Web Modeling Editor (frontend). For JSON schema details, see Schema Reference. For the end-to-end flow including frontend processing, see End-to-End Flow.
On this page
Connection¶
The agent listens on a WebSocket endpoint (default ws://localhost:8765).
The frontend connects and communicates using JSON messages in the v2 protocol
format.
Protocol Version¶
The current protocol version is 2.0. All messages include a
protocolVersion field. The backend detects the version and adapts response
formatting accordingly.
Inbound Messages (Frontend → Backend)¶
Most frontend messages use the user_message action, wrapped in a
BESSER framework envelope. The other inbound actions are listed below.
Envelope Structure¶
BAF’s Payload.decode() reads only three top-level keys off a message —
action, message and history — so the v2 payload is
JSON-stringified into the ``message`` field of a user_message
envelope. The wire payload is therefore double-JSON-encoded:
{
"action": "user_message",
"message": "<JSON string of v2 payload>",
"history": false
}
_unwrap_v2_envelope() in src/protocol/adapters.py recovers the inner
payload and merges it over the outer one.
Note
Session identity does not travel in the envelope. The frontend appends a
persisted ?user_id= query parameter to the WebSocket URL, and the
platform reads it off the HTTP request that opened the socket
(_extract_user_id_from_request in patches/websocket_platform.py).
Inside the payload, continuity comes from the v2 sessionId field.
Note
The same double-encoding applies in reverse to streamed replies: each
chunk arrives wrapped as {"action": "agent_reply_str", "message":
"<JSON string>", "history": false}, where the inner string is the
stream_start / stream_chunk / stream_done payload. When probing
the agent directly (bypassing the browser), replicate and unwrap both
layers — a single-level unwrap silently treats every response as an
unrecognized action and hangs waiting for a message that already arrived.
Other inbound actions¶
Not every message from the frontend is a user_message:
Action |
Purpose |
|---|---|
|
A text turn, optionally with base64 |
|
Base64 audio, transcribed by OpenAI speech-to-text. The workspace
context is sent just before it as a |
|
Sets a BAF session variable, to pass |
|
Reports the outcome of an action the frontend executed (e.g. a generator finishing). Routed deterministically to the generation state — never classified. |
|
Asks the agent to re-send buffered terminal replies after a reconnect
that dropped a long-running reply mid-flight. With |
V2 Payload Structure¶
{
"action": "user_message",
"protocolVersion": "2.0",
"clientMode": "workspace",
"message": "create a User class with id and email",
"context": {
"activeDiagramType": "ClassDiagram",
"activeDiagramId": "550e8400-e29b-41d4-a716-446655440000",
"activeModel": { "...model JSON..." },
"projectSnapshot": {
"name": "MyProject",
"diagrams": {
"ClassDiagram": [{ "id": "diag-1", "title": "Main", "model": {} }],
"StateMachineDiagram": null
}
},
"diagramSummaries": [
{ "diagramType": "ClassDiagram", "summary": "3 classes, 2 relationships" }
],
"sessionId": "abc-123",
"currentDiagramIndices": { "ClassDiagram": 0 }
},
"attachments": [
{
"filename": "model.puml",
"content": "QGN0YXJ0dW1s...",
"mimeType": "text/plain"
}
]
}
Field Reference¶
Field |
Required |
Description |
|---|---|---|
|
Yes |
Always |
|
Yes |
|
|
No |
Which surface sent the message: |
|
Yes |
The user’s natural-language message (max 12,000 characters) |
|
No |
Client-generated id of this turn (string, at most 128 characters). Echoed on every reply frame of the turn; see Turn ids and replay. |
|
No |
Currently active diagram tab type (e.g., |
|
No |
UUID of the active diagram |
|
No |
Deprecated and ignored. The agent resolves the active model from
|
|
No |
Full project state. |
|
No |
Array of |
|
No |
Active tab index per diagram type (for multi-tab support) |
|
No |
Opt-in study participant label (e.g. |
|
No |
The GitHub repo the project is linked to: |
|
No |
What the next Spec-Driven run would use: |
|
No |
The editor’s last Spec-Driven run of this project:
|
|
No |
Array of uploaded files (PlantUML, images, RDF, XMI, PDF, text) |
|
No |
The latest turns of the conversation as the client shows them, oldest
first: an array of |
Supported Diagram Types¶
SUPPORTED_DIAGRAM_TYPES in src/protocol/types.py. An
activeDiagramType outside this set is normalized to ClassDiagram.
ClassDiagram
ObjectDiagram
StateMachineDiagram
AgentDiagram
GUINoCodeDiagram
QuantumCircuitDiagram
BPMN # NOT "BPMNDiagram" — the editor's converter sets that itself
UserDiagram # User Profile models
ComponentDiagram
DeploymentDiagram
Outbound Messages (Backend → Frontend)¶
All responses are JSON objects with an action field that determines the
message type.
Every action name, inbound and outbound, is a member of Action in
src/protocol/actions.py (a StrEnum, so json.dumps writes the bare
string). Code uses the members, never the string literals
(tests/test_protocol_actions.py checks), and builds the repeated envelopes
with its builders: assistant_message, inject_element,
inject_complete_system and model_reply. A builder keeps the key order of
the literal it replaced, so the JSON is byte-identical
(tests/test_handler_envelopes.py pins every handler’s envelopes).
Action index¶
Action |
Terminal? |
Meaning |
|---|---|---|
|
Yes |
Add one element to the canvas |
|
Yes |
Inject a full diagram |
|
Yes |
Apply one or many modifications |
|
Yes |
Text-only reply (also the shape of a structured error) |
|
Yes |
Error the frontend surfaces with a recovery affordance |
|
Yes |
Create a new tab for a diagram type |
|
Yes |
Run a deterministic BESSER generator |
|
Yes |
Hand off to the LLM-authored Spec-Driven Agent |
|
Yes |
Import a BESSER project from a GitHub repo and resume work on it |
|
Yes |
Export the project |
|
Yes |
Open the deploy dialog |
|
Yes |
Deterministically build the GUI diagram from the class diagram |
|
No |
Progress / keep-alive tick |
|
|
Streamed free-text reply |
A subset of the terminal replies is buffered per stable session key so a reply
completed while the socket was reconnecting can be replayed on request:
inject_complete_system, modify_model, auto_generate_gui,
trigger_generator, trigger_github_import and assistant_message
(_TERMINAL_REPLY_ACTIONS / replay_last_reply in
src/conversation/session_helpers.py). A turn-scoped replay (see below) also covers
inject_element, trigger_smart_generator, agent_error,
trigger_export, trigger_deploy, create_diagram_tab and stream_done
(_TURN_REPLY_ACTIONS). These are kept out of the legacy replay because it
has no dedupe, so a trigger could fire twice.
Turn ids and replay¶
On reconnect the client’s first heartbeat flushes the platform outbox, which may deliver the reply the dead socket missed, and the client asks for a replay in the same tick. A replay that is not tied to a turn can therefore deliver the same reply twice, or the previous turn’s reply while the current one is still running. Turn ids prevent both:
The frontend puts a fresh
turnIdon every v2user_message.Every frame the agent sends for that turn (terminal replies,
progress,stream_*) carriesturnIdandreplySeq, a per-turn counter starting at 1.replay_last_responsecarries the awaitedturnIdandappliedSeqs. The agent re-sends only that turn’s buffered terminal replies whosereplySeqis not inappliedSeqs, in order, with their original stamps.The client applies each
(turnId, replySeq)at most once. It drops frames for a turn it did not send, and frames for a turn older than the newest turn that has already replied. The agent answers a session’s turns in order, so such a frame can only be a replay.A stamped stream keeps its turn awaited until
stream_done, whosefullTextis what a replay re-sends if the reconnect cut the stream.Starting a new conversation (
resetSession) forgets all earlier turns, so a late reply to the old conversation is dropped.
Both directions stay compatible. A request without turnId, from an older
frontend or a voice turn, gets unstamped frames and the legacy replay of the
session’s last terminal reply. Frames without turnId, from an older agent,
are applied exactly as before.
inject_element¶
Adds a single element to the diagram canvas.
{
"action": "inject_element",
"diagramType": "ClassDiagram",
"diagramId": "diagram-001",
"element": {
"className": "User",
"attributes": [
{"name": "id", "type": "String", "visibility": "public"}
],
"methods": [],
"position": {"x": 100, "y": 200}
},
"message": "Created the **User** class.",
"suggestedActions": [
{"label": "Add Order class", "prompt": "Add an Order class"}
]
}
inject_complete_system¶
Injects a full diagram (all elements + relationships) at once.
{
"action": "inject_complete_system",
"diagramType": "ClassDiagram",
"diagramId": "diagram-001",
"systemSpec": {
"systemName": "E-commerce System",
"classes": [
{
"className": "User",
"attributes": [
{"name": "id", "type": "String", "visibility": "public"},
{"name": "email", "type": "String", "visibility": "public"}
],
"methods": [],
"position": {"x": 100, "y": 200}
}
],
"relationships": [
{
"type": "Association",
"source": "User",
"target": "Order",
"sourceMultiplicity": "1",
"targetMultiplicity": "0..*",
"name": "creates"
}
]
},
"replaceExisting": false,
"createNewTab": false,
"message": "Built the **E-commerce System** with 2 classes.",
"suggestedActions": [
{"label": "Add Product class", "prompt": "Add a Product class"}
]
}
Field |
Description |
|---|---|
|
|
|
|
|
Optional list of |
Note
systemSpec is the handler’s simple format (classes /
relationships arrays for a class diagram, and the per-type equivalent
for the others), not the editor’s Apollon element/relationship maps. The
frontend’s ConverterFactory performs that translation — see
End-to-End Flow.
Class-diagram systemSpec objects may also carry a constraints list
of OCL invariants. The frontend persists these as ClassOCLConstraint
elements with ClassOCLLink attachments to their context classes. A
persisted constraint is not necessarily enforced by a target generator;
unsupported rules remain work for the spec-driven agent.
An Association may carry associationClass: "Enrollment". Declare
Enrollment in classes with the attributes belonging to the pairing,
and attach it to exactly one direct relationship (for example
Student–Course). The frontend emits a ClassLinkRel whose source
is the attribute class and whose target is that relationship’s ID. BESSER
converts this to a native AssociationClass; no two extra ordinary
endpoint associations are needed. Compact LLM output uses ac for the
same attachment, expanded before this message is sent. Missing or null
associationClass preserves the ordinary relationship behavior.
This attachment is supported by complete-system generation; the existing incremental modification protocol does not yet expose it. Deploy the matching frontend converter with the agent schema change: older converters ignore this field and lose the native attachment.
modify_model (single)¶
Apply a single modification to an existing element.
{
"action": "modify_model",
"diagramType": "ClassDiagram",
"diagramId": "diagram-001",
"modification": {
"action": "modify_class",
"target": {"className": "User"},
"changes": {"name": "Customer"}
},
"message": "Renamed **User** to **Customer**."
}
modify_model (batch)¶
Apply multiple modifications in a single message.
{
"action": "modify_model",
"diagramType": "ClassDiagram",
"diagramId": "diagram-001",
"modifications": [
{
"action": "add_attribute",
"target": {"className": "User"},
"changes": {"name": "phone", "type": "String", "visibility": "public"}
},
{
"action": "remove_method",
"target": {"className": "Order"},
"changes": {"name": "deprecatedMethod"}
}
],
"message": "Added **phone** to User and removed **deprecatedMethod** from Order."
}
Nested Modification Actions¶
The valid nested actions are Literal types on each diagram’s Pydantic
modification schema (src/schemas/), so the LLM cannot hallucinate one —
Structured Outputs rejects the response and the call retries.
Diagram Type |
Valid nested actions |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Any (generic) |
|
assistant_message¶
Text-only message displayed in the chat panel.
{
"action": "assistant_message",
"message": "The User class represents authenticated users in the system."
}
Streaming Protocol¶
For long LLM responses, the backend streams text chunk-by-chunk:
{"action": "stream_start", "streamId": "abc12345"}
{"action": "stream_chunk", "streamId": "abc12345", "chunk": "The class diagram ", "done": false}
{"action": "stream_chunk", "streamId": "abc12345", "chunk": "represents the core ", "done": false}
{"action": "stream_chunk", "streamId": "abc12345", "chunk": "domain model.", "done": false}
{"action": "stream_done", "streamId": "abc12345", "fullText": "The class diagram represents the core domain model.", "done": true}
Buffer threshold: ~200 characters. Chunks are buffered until they reach this
threshold or hit a natural break (., !, ?, :, newline), balancing
between WebSocket flood and perceived latency.
progress¶
Loading/progress indicator update.
{
"action": "progress",
"message": "Generating class diagram...",
"step": 1,
"total": 3
}
agent_error¶
Error payload sent when something goes wrong and the frontend should surface a
recovery affordance (for example an inline “Add your API key” button, which it
keys on rate_limit / auth_error).
{
"action": "agent_error",
"errorCode": "rate_limit",
"message": "We've hit the shared free usage limit for the AI service...",
"suggestedRecovery": "Add your own API key",
"retryable": true
}
The editor’s “Try again” chip appears when retryable is true and
suggestedRecovery is set, and sends that text as the next prompt.
Most structured errors are instead sent as an assistant_message carrying
the same fields plus "error": true — see build_error_response() in
src/common/errors.py:
{
"action": "assistant_message",
"error": true,
"errorCode": "parse_error",
"message": "I had trouble structuring that response.",
"suggestedRecovery": "try rephrasing your request more specifically",
"retryable": false,
"diagramType": "ClassDiagram"
}
Error codes¶
ErrorCode in src/common/errors.py. Values are lowercase snake_case. Each code
carries a default user-facing message, a recovery hint, and a retryable
flag that the caller may override.
Error Code |
Retryable |
Description |
|---|---|---|
|
yes |
The AI service is temporarily unavailable |
|
yes |
The model returned something that could not be structured |
|
yes |
The generated model had structural issues |
|
— |
Structured output failed schema validation |
|
— |
Generation failed for another reason |
|
— |
The generation handler raised |
|
yes |
The request was too complex to process in time |
|
yes |
Provider rate limit or shared quota reached. On the user’s own key it
always arrives as |
|
— |
The API key was rejected. The provider refusing the user’s own key (401
or 403) always arrives as |
|
— |
Required workspace context was missing or unusable |
|
— |
The request asks for something the agent does not support |
|
— |
A generator’s required diagram does not exist yet |
|
— |
No handler registered for the target diagram type |
|
— |
Unclassified failure |
create_diagram_tab¶
Create a new tab for a diagram type. Emitted when the user answers a
replace/keep confirmation with “new tab”; the injection payload that follows
carries replaceExisting: true so it fills the freshly created tab.
{
"action": "create_diagram_tab",
"diagramType": "ClassDiagram"
}
trigger_generator¶
Trigger code generation from the current model. The frontend should invoke the appropriate generator with the provided config.
{
"action": "trigger_generator",
"generatorType": "django",
"config": {
"project_name": "hotel_app",
"app_name": "core_app",
"containerization": false
},
"message": "Starting **django** code generation — this may take a moment."
}
trigger_export¶
Trigger model export.
{
"action": "trigger_export",
"format": "json",
"message": "Exporting your project as **JSON** — the download should start shortly."
}
trigger_deploy¶
Open the deploy dialog on the frontend.
{
"action": "trigger_deploy",
"platform": "render",
"config": {},
"message": "Opening the **Deploy to Render** dialog..."
}
trigger_smart_generator¶
Hand off to the LLM-authored Spec-Driven Agent. Emitted when the request names a
stack BESSER has no deterministic generator for, or a BESSER stack plus
extras the template cannot produce (auth, JWT, Docker, migrations, tests, …).
Built by build_trigger_smart_generator_payload() in
src/codegen/smart_generation_handler.py.
{
"action": "trigger_smart_generator",
"instructions": "Rails 7 with PostgreSQL via Active Record and Devise auth",
"provider": "anthropic",
"message": "Generating your application from your specs…"
}
Field |
Description |
|---|---|
|
The polished prompt for the generator. Required — the frontend aborts on an empty value. Names the stack and any non-functional requirements the user mentioned; it does not restate the class diagram, which the generator already has. |
|
Suggested provider. The frontend’s BYOK selection can override it. |
|
Optional. |
The action names no model: the run uses the model the user picked in the
editor, else the BESSER backend’s default for the provider (the deployment’s
model catalog first, see BESSER_MODEL_CATALOG in Configuration).
The Spec-Driven Agent itself does not run over this WebSocket — the frontend calls the BESSER backend’s spec-driven HTTP/SSE endpoints with the user’s key. This action only hands it the instructions.
trigger_github_import¶
Resume work on a project that was previously generated and pushed to GitHub. The agent never touches GitHub itself: the frontend calls the backend’s import endpoint, loads the returned project, and arms the incremental-modify machinery.
{
"action": "trigger_github_import",
"owner": "besser-pearl",
"repo": "my-generated-app",
"branch": null,
"message": "Importing **besser-pearl/my-generated-app** from GitHub..."
}
branch is null when the user named none; the backend then uses the
repository’s default branch.
Note
This route is matched deterministically by regex, not inferred by the
classifier — an import must never be invented, missed, or swallowed. The
bare owner/repo form only fires alongside an explicit continuation verb,
so “create a diagram like github.com/x/y” is never hijacked.
auto_generate_gui¶
Deterministically build the GUI diagram from the class diagram — one page per
class, no LLM call. The frontend does the building via
autoGenerateGUIFromClassDiagram; message confirms completion and names
the pages that were created.
{
"action": "auto_generate_gui",
"diagramType": "GUINoCodeDiagram",
"message": "I created screens for Book, Author and Member.",
"suggestedActions": [
{"label": "Generate the web app", "prompt": "generate the web app"}
]
}
Message Flow Examples¶
Simple Class Creation¶
Frontend → Backend:
{ "action": "user_message", "message": "create a User class with id and email",
"context": { "activeDiagramType": "ClassDiagram" } }
Backend → Frontend:
{ "action": "progress", "message": "Generating class diagram..." }
{ "action": "inject_element", "diagramType": "ClassDiagram",
"element": { "className": "User", "attributes": [...] },
"message": "Created the User class." }
Multi-Step: Create Model → Generate Code¶
Frontend → Backend:
{ "message": "create a library system and generate django" }
Backend → Frontend:
{ "action": "progress", "message": "Thinking about your Class Diagram design..." }
{ "action": "inject_complete_system", "diagramType": "ClassDiagram",
"systemSpec": { ... } }
{ "action": "assistant_message",
"message": "Your model is ready. Shall I generate the Django project?",
"suggestedActions": [ { "label": "Generate", "prompt": "generate" } ] }
Frontend → Backend:
{ "message": "generate" }
Backend → Frontend:
{ "action": "trigger_generator", "generatorType": "django",
"config": { "project_name": "library", "app_name": "library_app",
"containerization": true } }
Important
A mixed “design X and generate Y” plan deliberately pauses after the
modeling step instead of running the generator straight through. The
generator is stashed behind PLAN_GENERATION_CONFIRM_FLAG and only runs
once the user explicitly confirms, so a user who only wanted the model does
not get a code-generation run they never asked for.
Generators with required config (sql needs dialect, sqlalchemy
needs dbms, qiskit needs backend and shots, export needs
format) ask for those values in the same way before the
trigger_generator payload is emitted; GENERATOR_REQUIRED_FIELDS in
src/codegen/generation_handler.py is the source of truth.
Streaming Response (Help/Explanation)¶
Frontend → Backend:
{ "message": "explain what is an association in UML" }
Backend → Frontend:
{ "action": "stream_start", "streamId": "a1b2c3d4" }
{ "action": "stream_chunk", "streamId": "a1b2c3d4",
"chunk": "An association in UML represents..." }
{ "action": "stream_chunk", "streamId": "a1b2c3d4",
"chunk": "a structural relationship between..." }
{ "action": "stream_done", "streamId": "a1b2c3d4",
"fullText": "An association in UML represents a structural..." }