Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chat API

Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.

ZERG provides two chat transports: WebSocket (bidirectional, recommended for UI) and SSE (unidirectional, for simple integrations).

WebSocket Transport

The primary chat interface. Authenticates via zerg_session cookie (set on Mango login), Authorization header, or a one-time WS ticket minted at POST /api/v1/chat/:id/ws-ticket and presented on the upgrade via the zerg_ticket, <ticket> Sec-WebSocket-Protocol subprotocol — so the long-lived bearer never rides the WS handshake (the ticket is single-use and short-TTL; Limon mints a fresh one per reconnect).

Connect

ws://host:21434/api/v1/chat/:session_id/ws

The session_id is obtained from POST /api/v1/chat.

Client → Server Messages

Send a message

{ "type": "message", "content": "Explain quicksort" }

Interrupt streaming

{ "type": "interrupt" }

Request message history

{ "type": "history" }

Heartbeat

{ "type": "ping" }

Server → Client Messages

TypeFieldsDescription
connectedsession_idConnection confirmed
historymessages[]Last 50 messages (on connect/reconnect)
tokendataStreaming token fragment
doneusageGeneration complete with token usage
errorerrorError message
interrupted—Generation was interrupted
pongtsHeartbeat response

Example

const ws = new WebSocket(
  `ws://${host}:21434/api/v1/chat/${sessionId}/ws`
)

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data)
  switch (msg.type) {
    case 'token':
      appendText(msg.data)
      break
    case 'done':
      finishGeneration(msg.usage)
      break
    case 'error':
      showError(msg.error)
      break
  }
}

ws.send(JSON.stringify({
  type: 'message',
  content: 'Write a Fibonacci function'
}))

Auth Refresh

Auth is validated at upgrade time and re-resolved every 5 minutes (AUTH_REFRESH_MS). The contract differs by credential form:

Bearer / session-cookie sockets re-resolve the principal on the refresh; a transient auth-store outage keeps the socket alive, a genuine revocation/disable closes it with 4401 unauthorized (terminal). One-time-ticket sockets have no credential left to re-resolve (the ticket is spent at open), so they carry an absolute 5-minute lifetime (TICKET_ABSOLUTE_LIFETIME_MS). At the boundary the server closes with 4401 reauthenticate; Limon treats that specific code/reason as a re-mint-and-reconnect signal, mints a fresh single-use ticket and re-handshakes automatically. The spent ticket is never reused.

Only 4401 reauthenticate is non-terminal. Every other 4xxx close (including 4401 unauthorized, 4403, 4404) is terminal and surfaces the Reconnect affordance. There is no 4001 close code.

Heartbeat

The SERVER pushes pong frames every 30 seconds (HEARTBEAT_INTERVAL_MS=30000) as liveness signals; there is no miss-counting disconnect policy on the server side.

SSE Transport

Fallback transport for simple integrations. Unidirectional: client sends messages via REST, receives tokens via SSE.

Create Session

POST /api/v1/chat

model is required (missing/empty answers 400 model_required); mode defaults to "build".

{ "model": "glm-4.7-flash", "mode": "build" }

Response:

{
  "ok": true,
  "data": {
    "id": "a1b2c3d4e5f6",
    "worker_id": "chat-a1b2c3d4e5f6",
    "model": "glm-4.7-flash",
    "mode": "build",
    "status": "active",
    "created_at": 1745600000000
  }
}

Capacity errors:

CodeBodyCondition
429{"ok":false,"error":"seat_cap_reached"} + Retry-After: 1Seat cap saturated
429{"ok":false,"error":"max_workers_reached"} + Retry-After: 1Worker ceiling
429{"ok":false,"error":"too_many_sessions"}Session cap: 20 active sessions per user, or 500 active sessions globally
503{"ok":false,"error":"license_unavailable"}License service down (block mode)
503{"ok":false,"error":"session_table_unavailable"}Session registry write failed
413{"ok":false,"error":{"code":"body_too_large","message":"body_too_large"}}Body over 10 MB

Shape note: the 429/503 capacity arms predate the nested envelope and still carry the string error field shown above ({"ok":false, "error":"<code>"}); the 413 arm answers the nested {code,message} envelope. Both are ok:false — dispatch on the code, not the shape. The SSE-budget refusal (sse_limit_reached, 429 + Retry-After: 1) shares the string form.

Streamed turns persist a checkpoint every chat_checkpoint_tokens (64) tokens / chat_checkpoint_ms (2000 ms) — a mid-stream crash loses at most one window.

Stream Tokens

GET /api/v1/chat/:id/stream

Returns an SSE stream. Events: connected, token, done, error.

curl -N http://127.0.0.1:21434/api/v1/chat/a1b2c3d4e5f6/stream \
  -H "Authorization: Bearer $TOKEN"

Send Message

POST /api/v1/chat/:id/message
{ "content": "Explain quicksort" }

A missing/empty content answers 400 content_required; a read timeout on the body answers 408 request_timeout; a client disconnect mid-read answers 499 client_disconnect.

End Session

DELETE /api/v1/chat/:id

Session Management

List Sessions

GET /api/v1/chat

Returns active sessions for the authenticated user. Admin users see all sessions.

Get Session Details

GET /api/v1/chat/:id

Message History

GET /api/v1/chat/:id/history?limit=50

Messages are stored for 30 days in Mnesia. limit defaults to 50 and is clamped to 1..200 (hostile values degrade to the default, never an error).

Response:

{
  "ok": true,
  "data": [
    {
      "id": "msg-abc123",
      "session_id": "a1b2c3d4e5f6",
      "role": "user",
      "content": "Hello",
      "timestamp": 1745600000
    }
  ]
}

Permissions

Chat endpoints require chat:read permission. Sessions are scoped to the authenticated user — non-admin users can only access their own sessions.

Architecture: Luna Harness, Not a Thin Proxy

The web chat does NOT talk directly to LLM providers. Every message flows through the full Luna agent harness — the same runtime used by the TUI and CLI. This means web chat users get the complete agent experience: tool execution, session persistence, memory, MCP servers, compaction, and multi-provider failover.

Limon is a thin UI shell. Sol is the message bus. Luna is the brain.

Data Flow

┌──────────┐       ┌──────────┐       ┌──────────┐       ┌──────────┐
│  Limon   │       │   Sol    │       │   ZMQ    │       │   Luna   │
│ (Browser)│       │(Erlang)  │       │(ROUTER)  │       │(LuaJIT)  │
└────┬─────┘       └────┬─────┘       └────┬─────┘       └────┬─────┘
     │                  │                  │                  │
     │  WS connect      │                  │                  │
     │─────────────────►│  spawn worker    │                  │
     │                  │─────────────────►│  DEALER connect  │
     │                  │                  │─────────────────►│
     │                  │                  │                  │
     │  {type:message}  │                  │                  │
     │─────────────────►│  task msgpack    │                  │
     │                  │─────────────────►│  JSONL stdin     │
     │                  │                  │─────────────────►│
     │                  │                  │                  │
     │                  │                  │                  │  ┌─────────────┐
     │                  │                  │                  │  │ Agent Loop  │
     │                  │                  │                  │  │ ┌─────────┐ │
     │                  │                  │                  │  │ │Provider │ │
     │                  │                  │                  │  │ │(Anthropic│ │
     │                  │                  │                  │  │ │OpenAI   │ │
     │                  │                  │                  │  │ │z.ai)    │ │
     │                  │                  │                  │  │ └─────────┘ │
     │                  │                  │                  │  │ ┌─────────┐ │
     │                  │                  │                  │  │ │  Tools   │ │
     │                  │                  │                  │  │ │(71+MCP) │ │
     │                  │                  │                  │  │ └─────────┘ │
     │                  │                  │                  │  │ ┌─────────┐ │
     │                  │                  │                  │  │ │ Session  │ │
     │                  │                  │                  │  │ │(JSONL+   │ │
     │                  │                  │                  │  │ │ SQLite)  │ │
     │                  │                  │                  │  │ └─────────┘ │
     │                  │                  │                  │  │ ┌─────────┐ │
     │                  │                  │                  │  │ │ Memory   │ │
     │                  │                  │                  │  │ │(KV+TTL)  │ │
     │                  │                  │                  │  │ └─────────┘ │
     │                  │                  │                  │  └─────────────┘
     │                  │                  │                  │
     │                  │                  │  token (JSONL)   │
     │                  │  {sol_token}     │◄─────────────────│
     │  {type:token}    │◄────────────────│                  │
     │◄─────────────────│                  │                  │
     │                  │                  │  ...more tokens  │
     │                  │                  │                  │
     │                  │                  │  done (JSONL)    │
     │                  │  {sol_done}      │◄─────────────────│
     │  {type:done}     │◄────────────────│                  │
     │◄─────────────────│                  │                  │

What Luna Provides in Web Chat Mode

Every web chat session runs a complete Luna agent. When Limon sends a message, the Luna worker:

  1. Appends to session — JSONL + SQLite dual-write, same as TUI/CLI
  2. Builds context — system prompt, session history, memory injection, context file scanning
  3. Calls provider — multi-provider failover (Anthropic → OpenAI → z.ai → Ollama)
  4. Streams tokens — each token fragment sent back to Limon via ZMQ → Sol → WS
  5. Executes tools — tools=92 registered built-in + MCP tools, parallel execution for async tools
  6. Manages memory — cross-session KV+TTL, heuristic extraction on session close
  7. Compacts when needed — multi-strategy compaction at 70% context threshold
  8. Persists checkpoints — automatic checkpoint before risky operations

What Sol Does NOT Do

Sol does not call LLM providers directly for chat Sol does not execute tools or manage conversation state Sol does not handle sessions or memory Sol is a message bus: it receives WS messages, dispatches to Luna via ZMQ, and relays streaming tokens back

Why This Matters

Consistency: Same agent behavior whether using TUI, CLI, or web chat Full tool access: Web chat users can run bash, edit files, search code — not just talk Session portability: Start in web, resume in TUI with --resume — same JSONL session Provider independence: Swap providers without touching Limon or Sol