The WebSocket
A two-way connection with flags and a heartbeat, for programs that talk to the gateway.
The browser and POST /task follow a run over SSE. The gateway also speaks WebSocket at GET /v1/sessions/{id}/ws: a persistent, two-way connection with flags, a heartbeat and a structured message format, for programs that want more than a one-shot HTTP request. It is a second transport, not a second agent: same conversation, same token, same run slot.
Who may connect
The endpoint sits behind the same token as the rest of the API, in two layers, and both are required:
- The upgrade request carries
Authorization: Bearer <token>. A browser cannot add that header to a WebSocket handshake, so the web interface's own session cookie is accepted instead, and a cookie-authorised request must also come from the server's own origin (another origin gets403). With no credential at all the upgrade is refused with401. - The
authmessage repeats the token inside the protocol. Until it succeeds, aqueryis answered withUNAUTHORIZED; a wrong token getsUNAUTHORIZEDand the connection stays open so the client can retry.
query runs the same read-only planner as POST /plan.The message envelope
Every message, in both directions, is a JSON object:
{
"msg_id": "550e8400-e29b-41d4-a716-446655440000",
"type": "query",
"flags": ["PROCESSING"],
"timestamp": "2026-09-25T12:00:00.000Z",
"payload": {}
}
| Field | Meaning |
|---|---|
msg_id | UUID v4, unique per message. |
type | The kind of message (below). |
flags | List of state indicators (below). |
timestamp | ISO-8601. |
payload | Data specific to the type. |
Message types
| Type | Direction | Use |
|---|---|---|
auth | Client → server | Authenticate with the token. |
auth_response | Server → client | The result of authentication. |
query | Client → server | A question or request. |
query_response | Server → client | Acknowledgement, partial progress or the final answer. |
heartbeat, heartbeat_ack | Both | Keep-alive probe and its answer. |
error | Server → client | Something went wrong. |
notification | Server → client | Reserved, never sent yet. |
Flags
| Flag | Meaning |
|---|---|
AUTHENTICATED, UNAUTHORIZED | Authentication succeeded or failed. |
IDLE, BUSY | The agent is waiting, or already running something. |
PROCESSING, PARTIAL, COMPLETED | A query is being worked on, streams a progress line, or finished. |
ERROR_RECOVERABLE | An error the connection survives. |
Reserved. The type notification and the flags FATAL_ERROR, LOW_MEMORY, RATE_LIMITED, CACHE_HIT, CACHE_MISS and ENCRYPTED are part of the vocabulary but nothing emits them. A client should accept them and must not wait for them.
The conversation
The acknowledgement comes at once, progress lines stream as they happen, and the last message carries the result. A failed query ends in an error with ERROR_RECOVERABLE instead.
Malformed JSON and unknown types get an ERROR_RECOVERABLE error. Several clients may connect at once, but the conversation runs one task at a time: a second client that starts a run while one is going gets BUSY.
What a client must follow
- Only text frames with JSON. A binary or fragmented message gets an
ERROR_RECOVERABLEand the connection stays open. - Client frames must be masked (RFC 6455); an unmasked frame closes the connection with code 1002. Any WebSocket library does this for you.
- A ping is answered with a pong, and a client pong also counts as the answer to a heartbeat.
- A connection that sends nothing for 90 seconds is dropped, and no heartbeat ack closes it too.
- Close code 1000 means the client closed; 1001 means the gateway is shutting down or the heartbeat went unanswered, so reconnect.
- A
queryis read-only and tied to the connection: if the client disconnects, the query is cancelled.
Example clients
The same client in the most used languages. Each one authenticates, asks one question, answers the heartbeat and prints the result. Set MOTITA_TOKEN to the gateway token first.
// npm install ws
import WebSocket from "ws";
import { randomUUID } from "node:crypto";
const TOKEN = process.env.MOTITA_TOKEN; // the gateway token: motita gateway start -token-only
const ws = new WebSocket("ws://127.0.0.1:7477/v1/sessions/default/ws", {
headers: { Authorization: "Bearer " + TOKEN },
});
const send = (type, payload) =>
ws.send(JSON.stringify({
msg_id: randomUUID(), type, flags: [],
timestamp: new Date().toISOString(), payload,
}));
ws.on("open", () => send("auth", { token: TOKEN })); // the server greets first; reply with the token
ws.on("message", (data) => {
const msg = JSON.parse(data.toString());
const has = (flag) => msg.flags.includes(flag);
if (msg.type === "auth_response" && has("AUTHENTICATED")) {
send("query", { query: "what does this project do?" }); // authenticated: now ask something
} else if (msg.type === "auth_response" && has("UNAUTHORIZED")) {
console.error("unauthorized"); // wrong token (the connection stays open)
ws.close();
} else if (msg.type === "heartbeat") {
send("heartbeat_ack", {}); // answer the keep-alive within 10 s
} else if (has("COMPLETED")) {
console.log(msg.payload.result); // the final answer
ws.close();
} else if (msg.type === "error" || has("BUSY")) {
console.error(msg.payload); // an error, or another client is already running a task
ws.close();
}
});// npm install ws @types/ws
import WebSocket from "ws";
import { randomUUID } from "node:crypto";
interface Envelope<P = Record<string, unknown>> {
msg_id: string;
type: string;
flags: string[];
timestamp: string;
payload: P;
}
const TOKEN = process.env.MOTITA_TOKEN ?? ""; // the gateway token: motita gateway start -token-only
const ws = new WebSocket("ws://127.0.0.1:7477/v1/sessions/default/ws", {
headers: { Authorization: "Bearer " + TOKEN },
});
function send(type: string, payload: object): void {
const msg: Envelope<object> = {
msg_id: randomUUID(), type, flags: [],
timestamp: new Date().toISOString(), payload,
};
ws.send(JSON.stringify(msg));
}
ws.on("open", () => send("auth", { token: TOKEN })); // the server greets first; reply with the token
ws.on("message", (data) => {
const msg = JSON.parse(data.toString()) as Envelope<{ result?: string }>;
const has = (flag: string): boolean => msg.flags.includes(flag);
if (msg.type === "auth_response" && has("AUTHENTICATED")) {
send("query", { query: "what does this project do?" }); // authenticated: now ask something
} else if (msg.type === "heartbeat") {
send("heartbeat_ack", {}); // answer the keep-alive within 10 s
} else if (has("COMPLETED")) {
console.log(msg.payload.result); // the final answer
ws.close();
} else if (msg.type === "error" || has("BUSY") || has("UNAUTHORIZED")) {
console.error(msg.payload); // an error, or another client is already running a task
ws.close();
}
});# pip install websocket-client
import datetime
import json
import os
import uuid
import websocket
TOKEN = os.environ["MOTITA_TOKEN"] # the gateway token: motita gateway start -token-only
def send(ws, type_, payload):
ws.send(json.dumps({
"msg_id": str(uuid.uuid4()), "type": type_, "flags": [],
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"payload": payload,
}))
ws = websocket.create_connection(
"ws://127.0.0.1:7477/v1/sessions/default/ws",
header=["Authorization: Bearer " + TOKEN],
)
json.loads(ws.recv()) # the server greets first; reply with the token
send(ws, "auth", {"token": TOKEN})
json.loads(ws.recv()) # auth_response / AUTHENTICATED
send(ws, "query", {"query": "what does this project do?"}) # authenticated: now ask something
while True:
msg = json.loads(ws.recv())
if msg["type"] == "heartbeat":
send(ws, "heartbeat_ack", {}) # answer the keep-alive within 10 s
elif "COMPLETED" in msg["flags"]:
print(msg["payload"]["result"]) # the final answer
break
elif msg["type"] == "error" or "BUSY" in msg["flags"]:
raise SystemExit(msg["payload"]) # an error, or another client is already running a task// go get github.com/gorilla/websocket github.com/google/uuid
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"slices"
"time"
"github.com/google/uuid"
"github.com/gorilla/websocket"
)
type Envelope struct {
MsgID string `json:"msg_id"`
Type string `json:"type"`
Flags []string `json:"flags"`
Timestamp string `json:"timestamp"`
Payload json.RawMessage `json:"payload"`
}
func send(c *websocket.Conn, typ string, payload any) {
body, _ := json.Marshal(payload)
err := c.WriteJSON(Envelope{
MsgID: uuid.NewString(), Type: typ, Flags: []string{},
Timestamp: time.Now().UTC().Format(time.RFC3339Nano), Payload: body,
})
if err != nil {
log.Fatal(err)
}
}
func main() {
token := os.Getenv("MOTITA_TOKEN") // the gateway token: motita gateway start -token-only
header := http.Header{"Authorization": {"Bearer " + token}}
c, _, err := websocket.DefaultDialer.Dial("ws://127.0.0.1:7477/v1/sessions/default/ws", header)
if err != nil {
log.Fatal(err)
}
defer c.Close()
send(c, "auth", map[string]string{"token": token}) // the server greets first; reply with the token
for {
var msg Envelope
if err := c.ReadJSON(&msg); err != nil {
log.Fatal(err)
}
has := func(flag string) bool { return slices.Contains(msg.Flags, flag) }
switch {
case msg.Type == "auth_response" && has("AUTHENTICATED"):
send(c, "query", map[string]string{"query": "what does this project do?"}) // authenticated: now ask something
case msg.Type == "heartbeat":
send(c, "heartbeat_ack", map[string]string{}) // answer the keep-alive within 10 s
case has("COMPLETED"):
fmt.Println(string(msg.Payload)) // the final answer
return
case msg.Type == "error" || has("BUSY") || has("UNAUTHORIZED"):
log.Fatalf("%s", msg.Payload) // an error, or another client is already running a task
}
}
}// Cargo.toml: tungstenite = "0.26", serde_json = "1", uuid = { version = "1", features = ["v4"] }, chrono = "0.4"
use serde_json::{json, Value};
use tungstenite::{client::IntoClientRequest, connect, Message};
fn envelope(kind: &str, payload: Value) -> Message {
Message::text(
json!({
"msg_id": uuid::Uuid::new_v4().to_string(), "type": kind, "flags": [],
"timestamp": chrono::Utc::now().to_rfc3339(), "payload": payload,
})
.to_string(),
)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let token = std::env::var("MOTITA_TOKEN")?; // the gateway token: motita gateway start -token-only
let mut request = "ws://127.0.0.1:7477/v1/sessions/default/ws".into_client_request()?;
request.headers_mut().insert("Authorization", format!("Bearer {token}").parse()?);
let (mut socket, _) = connect(request)?;
socket.send(envelope("auth", json!({ "token": token })))?; // the server greets first; reply with the token
loop {
let text = socket.read()?.into_text()?;
let msg: Value = serde_json::from_str(text.as_str())?;
let has = |flag: &str| msg["flags"].as_array().is_some_and(|f| f.iter().any(|x| x == flag));
if msg["type"] == "auth_response" && has("AUTHENTICATED") {
socket.send(envelope("query", json!({ "query": "what does this project do?" })))?; // authenticated: now ask something
} else if msg["type"] == "heartbeat" {
socket.send(envelope("heartbeat_ack", json!({})))?; // answer the keep-alive within 10 s
} else if has("COMPLETED") {
println!("{}", msg["payload"]["result"].as_str().unwrap_or_default()); // the final answer
return Ok(());
} else if msg["type"] == "error" || has("BUSY") || has("UNAUTHORIZED") {
return Err(msg["payload"].to_string().into()); // an error, or another client is already running a task
}
}
}Authorization header to a WebSocket, so it relies on the web interface's cookie and must be served by the gateway itself.Off loopback the gateway speaks plain HTTP, so use wss:// behind one of the options in Network and remote access rather than sending the token in the clear.