← All lessons/Real-Time
40
Real-Time

Per-Agent SSE Stream

Stream every new record written to a specific agent in real time.

Prerequisite: Lesson 5 complete

What you'll learn

  • GET /v1/agents/:id/stream — open SSE connection
  • Each written record emitted as event: record
  • Stream format: event: record\ndata: {content_hash, ts_hlc, payload}
  • Last-Event-ID header for reconnect and replay
  • EventSource API in browsers — automatic reconnect
Challenge

Open SSE stream in one terminal. Write 10 records in a loop in another. Confirm all 10 appear in order.

What you'll learn

Stream every new record written to a specific agent in real time using Server-Sent Events.

Open the stream

# Streams all new records written to 'orders' agent
curl -N "http://localhost:7475/v1/agents/orders/stream" \
  -H "Authorization: Bearer spx_root_YOUR_ROOT_KEY"

Keep this running. In another terminal, write a record:

curl -s -X POST http://localhost:7475/v1/agents/orders/records/json \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer spx_root_YOUR_ROOT_KEY" \
  -d '{"data": {"amount": 99.00, "status": "paid"}}' \
  | python3 -m json.tool

You'll see the record appear in the SSE stream terminal immediately.

Stream event format

event: record.written
data: {
  "agent_id":     "orders",
  "event_type":   "record.written",
  "record_id":    "018f3c2a-...",
  "content_hash": "b3a7c2...",
  "timestamp_ms": 1754481600000,
  "flags":        0,
  "payload":      {"amount": 99.00, "status": "paid"}
}

flags = 0 is a normal write. flags = 2 is a TOMBSTONE (logical delete).

Reconnect and replay

SSE clients automatically reconnect on disconnect. Pass ?since=<timestamp_ms> to backfill records written after that HLC timestamp before going live:

curl -N "http://localhost:7475/v1/agents/orders/stream?since=1754481600000" \
  -H "Authorization: Bearer spx_root_YOUR_ROOT_KEY"

The timestamp_ms value to use as since is the timestamp_ms from the last event you received.

Challenge

Open an SSE stream in a terminal. Write 10 records using a loop. Confirm all 10 events arrive with event: record.written and that flags is 0 for each.

---

← Previous
Lesson 39: Mutants (AI Schema Evolution)
Next →
Lesson 41: Global Broadcast Bus & Publications