Skip to content

Live events over WebSocket

Each document keeps an ordered log of events. Every event has a sequence number, starting at 1 for the document. You can read the log over HTTP, or subscribe over WebSocket to receive past events followed by live ones. Both deliver the same Event records.

Events tell you what changed. The status snapshot stays authoritative: when you need counts, failure details or delivery history, read it.

  1. Read the snapshot at links.status and note last_sequence.

  2. Get a ticket. POST to links.event_tickets with an empty body. The response contains a single-use ticket that expires after 60 seconds. Request tickets from your server; the browser or worker that connects never needs the API key.

    api/specs/examples/ticket.json (contract fixture)
    {
    "ticket": "example-single-use-ticket",
    "expires_at": "2026-11-30T20:01:00Z"
    }
  3. Connect and subscribe. Open a WebSocket to links.events and, within five seconds, send one subscription frame with the ticket and the last sequence you have applied. Use 0 to replay from the start.

    api/specs/examples/subscribe.json (contract fixture)
    {
    "type": "subscribe",
    "ticket": "example-ticket",
    "after_sequence": 4
    }
  4. Receive events. The server replies {"type":"ready","document_id":"…"}, then sends every retained event with a higher sequence, in order, and continues live.

    api/specs/examples/event.json (contract fixture)
    {
    "type": "event",
    "document_id": "a~d17",
    "sequence": 5,
    "occurred_at": "2026-11-30T20:00:05Z",
    "reason": "chunk_succeeded",
    "range": {
    "first_page": 1,
    "last_page": 2
    },
    "attempt": 1
    }

Events that concern a chunk carry its page range; document-wide events have range: null. The WebSocket reference lists every event reason and its fields. Events never contain document text or secrets.

Connections can drop. To resume, get a new ticket and subscribe with the last sequence you applied. You receive only the events after it, so nothing is duplicated or missed. Record events by document ID and sequence so a repeated event is harmless.

If your cursor is older than the retained history, or ahead of the current sequence, the server sends resync_required and closes normally:

api/specs/examples/resync.json (contract fixture)
{
"type": "resync_required",
"status_url": "https://api.sonicdocs.ai/v1/documents/a~d17"
}

Read the snapshot at status_url, then subscribe again with its last_sequence.

docs/public/examples/javascript/events.mjs
// Sonic Docs contract example: follow a document's events over WebSocket and resume
// after disconnects. Written against the planned v1 contract; not yet run against a live API.
// Usage: SONIC_API_KEY=... node events.mjs DOCUMENT_ID
import { API_BASE, api } from './client.mjs';
const documentId = process.argv[2];
if (!documentId) throw new Error('Pass a document ID');
const TERMINAL = new Set(['succeeded', 'failed']);
// The HTTP snapshot is authoritative; events say what changed after a sequence.
let snapshot = await (await api(`${API_BASE}/documents/${encodeURIComponent(documentId)}`)).json();
let after = snapshot.last_sequence;
while (!TERMINAL.has(snapshot.state)) {
// A ticket is single-use and expires after 60 seconds, so request one per connection.
const { ticket } = await (await api(snapshot.links.event_tickets, { method: 'POST' })).json();
const outcome = await new Promise((resolve) => {
const socket = new WebSocket(snapshot.links.events);
socket.onopen = () => socket.send(JSON.stringify({ type: 'subscribe', ticket, after_sequence: after }));
socket.onmessage = ({ data }) => {
const frame = JSON.parse(data);
if (frame.type === 'event' && frame.sequence > after) {
after = frame.sequence;
console.log(frame.sequence, frame.reason, frame.range ?? '');
if (TERMINAL.has(frame.reason)) socket.close(1000);
} else if (frame.type === 'resync_required') {
resolve('resync');
}
};
socket.onclose = ({ code }) => resolve(code === 1008 ? 'refused' : 'closed');
});
if (outcome === 'refused') throw new Error('Subscription refused (close code 1008): check the key and document');
// Refresh the snapshot after every disconnect. After resync_required, continue from
// the snapshot's cursor; otherwise resume after the last event already applied.
snapshot = await (await api(snapshot.links.status)).json();
if (outcome === 'resync') after = snapshot.last_sequence;
}
console.log(`Document ${snapshot.state} at sequence ${snapshot.last_sequence}`);
Code Meaning What to do
1000 Normal close, including after resync_required Resume from your cursor, or from the snapshot after a resync
1008 Policy violation: expired, reused, revoked or wrong-document ticket; malformed or late subscription; access revoked; document deleted Do not retry blindly. Check the key and the document.
1013 You fell behind: more than 1 MiB of data was waiting to be sent Reconnect with a fresh ticket and your last sequence

Browser connections must come from an origin configured for your tenant’s dashboard.

GET /documents/{document_id}/events returns the same events in pages. Pass after_sequence to start after a cursor, or omit it to start at the oldest retained event. limit is 1 to 500, default 100.

docs/public/examples/curl/events-history.sh
#!/usr/bin/env bash
# Sonic Docs contract example: page through a document's retained event history.
# Written against the planned v1 contract; not yet run against a live API.
set -euo pipefail
API_BASE="${SONIC_API_BASE:-https://api.sonicdocs.ai/v1}"
: "${SONIC_API_KEY:?Set SONIC_API_KEY to a key with documents:read}"
DOCUMENT_ID="${1:?Usage: events-history.sh DOCUMENT_ID [AFTER_SEQUENCE]}"
AFTER="${2:-}"
while :; do
PAGE=$(curl -sS --fail-with-body -G "$API_BASE/documents/$DOCUMENT_ID/events" \
-H "Authorization: Bearer $SONIC_API_KEY" \
--data-urlencode "limit=100" ${AFTER:+--data-urlencode "after_sequence=$AFTER"})
jq -c '.events[] | {sequence, reason, range}' <<<"$PAGE"
AFTER=$(jq -r .next_after_sequence <<<"$PAGE")
[ "$(jq -r .has_more <<<"$PAGE")" = true ] || break
done
echo "Resume after sequence $AFTER"

next_after_sequence is the cursor for the next page and has_more tells you whether to continue. first_available_sequence is null when no events remain; a value above 1 means older events have expired.

Events are kept for 24 hours on a rolling basis, and never longer than the document. A cursor outside the retained window returns 409 event_cursor_unavailable: read the snapshot, then request history without a cursor.