#!/usr/bin/env python3 """WebSocket protocol page for BotBook, derived from the chat transport code. Imported by ``scripts/gen_api_reference.py``; it is not a standalone entry point (the generator owns the write/--check loop). Sources: ``botserver/src/core/bot/ws/**`` (frames), ``botlib/src/message_types.rs`` (``message_type`` 0-9), ``botlib/src/models/messaging.rs`` (``BotResponse``) and ``botui/ui/suite/chat/**`` (control frames the client sends). """ from __future__ import annotations import glob import os import re from collections import defaultdict ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def read(path: str) -> str: with open(os.path.join(ROOT, path), encoding="utf-8", errors="ignore") as handle: return handle.read() def repo_path(path: str) -> str: return os.path.relpath(path, ROOT).replace(os.sep, "/") def files(*patterns: str) -> list[str]: found: list[str] = [] for pattern in patterns: found.extend(glob.glob(os.path.join(ROOT, pattern), recursive=True)) return sorted(set(found)) CONST_RE = re.compile(r"pub const ([A-Z_0-9]+): Self = Self\((\d+)\);") FRAME_TYPE_RE = re.compile(r'frame_type == "([^"]+)"') JSON_TYPE_RE = re.compile(r'"type":\s*"([^"]+)"') CLIENT_TYPE_RE = re.compile(r'type:\s*"(run_[a-z_]+)"') QUERY_FIELD_RE = re.compile(r"^\s*pub ([a-z_]+): Option,$", re.M) def bot_response_fields() -> list[tuple[str, str, bool]]: """(field, rust type, optional) for the serialized chat frame.""" text = read("botlib/src/models/messaging.rs") start = text.index("pub struct BotResponse {") body = text[start: text.index("\n}", start)] fields = [] optional = False for line in body.splitlines(): stripped = line.strip() if stripped.startswith("#[serde(") and "skip_serializing_if" in stripped: optional = True continue match = re.match(r"pub ([a-z_]+): (.+),$", stripped) if match: fields.append((match.group(1), match.group(2), optional)) optional = False return fields def read_all_ws() -> str: return "".join(read(path) for path in files("botserver/src/core/bot/ws/**/*.rs")) def build_ws() -> str: message_types = CONST_RE.findall(read("botlib/src/message_types.rs")) handshake = QUERY_FIELD_RE.findall(read("botserver/src/core/bot/ws/handler.rs")) inbound: dict[str, set[str]] = defaultdict(set) outbound: dict[str, set[str]] = defaultdict(set) for path in files("botserver/src/core/bot/ws/**/*.rs"): text = read(path) source = repo_path(path) for frame in FRAME_TYPE_RE.findall(text): inbound[frame].add(source) for frame in JSON_TYPE_RE.findall(text): outbound[frame].add(source) for path in files("botui/ui/suite/chat/**/*.js"): text = read(path) for frame in CLIENT_TYPE_RE.findall(text): inbound[frame].add(repo_path(path)) lines = [ "\n\n", "# WebSocket Protocol 🟡 BETA\n\n", "The chat transport. One socket carries every chat frame; control frames\n", "are distinguished by a `type` field.\n\n", "## Handshake\n\n", "| Item | Value | Source |\n|---|---|---|\n", "| Path | `/ws` (bot from the query string) or `/ws/{bot}` | `botserver/src/main_module/server/run_axum_server.rs` |\n", "| Reserved segments | `attendant` — the console stream lives at `/api/attendance/ws`, not under `/ws` | `botserver/src/core/bot/ws/handler.rs` |\n", "| Unknown bot | `404` with `{\"error\": \"bot_not_found\", \"message\", \"bot_name\"}` | `botserver/src/core/bot/ws/handler.rs` |\n\n", "Query parameters (`WsQuery` in `botserver/src/core/bot/ws/handler.rs`):\n\n", "| Parameter | Meaning |\n|---|---|\n", ] for field in sorted(handshake): meaning = { "session_id": "session to resume; a fresh UUID is generated when absent or invalid", "user_id": "guest identity hint — never trusted for an authenticated session", "bot_name": "bot name or slug when the path does not carry it", "access_token": "suite/cloud token; when valid it determines the identity", }.get(field, "see the source") lines.append(f"| `{field}` | {meaning} |\n") lines += [ "\n## `message_type` values\n\n", "From `botlib/src/message_types.rs`:\n\n", "| Value | Constant | Meaning |\n|---:|---|---|\n", ] for name, value in sorted(message_types, key=lambda pair: int(pair[1])): lines.append(f"| {value} | `{name}` | {meaning_for(name)} |\n") lines += [ "\n## Chat frame (`BotResponse`)\n\n", "Every chat message, in both directions, is this JSON object\n", "(`botlib/src/models/messaging.rs`):\n\n", "| Field | Type | Always present |\n|---|---|---|\n", ] for field, rust_type, optional in bot_response_fields(): lines.append( f"| `{field}` | `{rust_type.replace('|', chr(92) + '|')}` | " f"{'no' if optional else 'yes'} |\n" ) lines += [ "\n## Control frames (client → server)\n\n", "| `type` | Sent by |\n|---|---|\n", ] for frame in sorted(inbound): sources = ", ".join(f"`{s}`" for s in sorted(inbound[frame])[:3]) lines.append(f"| `{frame}` | {sources} |\n") lines += [ "\n## Frames the server emits\n\n", "| `type` | Emitted from |\n|---|---|\n", ] for frame in sorted(outbound): sources = ", ".join(f"`{s}`" for s in sorted(outbound[frame])[:3]) lines.append(f"| `{frame}` | {sources} |\n") custom_names = sorted( {name for name in re.findall(r'"name":\s*"(gb\.[a-z_]+)"', read_all_ws())} ) if custom_names: lines += [ "\n`CUSTOM` is an envelope: the interesting part is `data.name`.\n\n", "| `data.name` | Meaning |\n|---|---|\n", ] for name in custom_names: meaning = { "gb.steer": "steering notice published on the run bus", "gb.takeover": "takeover state change (`payload.state`, `payload.surface`)", }.get(name, "see the emitting file above") lines.append(f"| `{name}` | {meaning} |\n") lines += [ "\n## Delivery rules\n\n", "| Rule | Evidence |\n|---|---|\n", "| A turn is acknowledged with `message_received`; the client clears its retry timer only on that frame | `botserver/src/core/bot/ws/session/inbound.rs` |\n", "| A message that arrives while a run is active is queued as steering and acknowledged with `gb.steering_queued` | same file |\n", "| `run_cancel` cancels the thread and answers `run_cancelled` | same file |\n", "| `run_resume` replays only frames after `last_seq` and finishes with `run_resume_done` | `botserver/src/core/bot/ws/session/resume.rs` |\n", "| `run_takeover` requires the session owner and answers `run_takeover_ack` (or a denial frame) | `botserver/src/core/bot/ws/session/takeover.rs` |\n\n", "Frame bodies are built with `serde_json::json!` at each call site, so no\n", "single Rust struct describes them; the tables above list the `type` values\n", "the code actually emits. Fields not shown here are not part of a contract.\n\n", "## See also\n\n", "- [Network Contract](../02-architecture-packages/network-contract.md)\n", "- [REST reference](../08-rest-api-tools/generated/README.md)\n", ] return "".join(lines) def meaning_for(name: str) -> str: return { "EXTERNAL": "message from an external system", "USER": "user message — the default for an inbound chat frame", "BOT_RESPONSE": "bot answer, streamed as chunks", "CONTINUE": "keep processing", "SUGGESTION": "suggestion button", "CONTEXT_CHANGE": "context switch", "TOOL_EXEC": "run the tool directly — bypasses the LLM", "SYSTEM": "system notice", "SWITCHER_TOGGLE": "switcher UI toggle", "UI_ACTION": "UI action plan (`__ui_plan__`)", }.get(name, "see `botlib/src/message_types.rs`")