Skip to content
Docs
GitHub

Stream events

Consume a session's SSE event stream from the Python SDK or any HTTP client, with reconnection via since_id, heartbeats, and event filtering.

5 min readEdit on GitHub

Applies toFramework (not available)Self-hostedEverruns Demo

Every session publishes its events as a Server-Sent Events (SSE) stream. Use the Python SDK when you can: it handles reconnection, heartbeat-based stale detection, backoff, and resumption with since_id. Use the raw SSE protocol from any other client, such as a non-Python service, a browser, or curl.

client.events.stream(session_id) returns an async iterator over typed events.

async for event in client.events.stream(session.id):
if event.type == "output.message.delta":
print(event.data.get("delta", ""), end="", flush=True)
elif event.type == "turn.completed":
print()
break
elif event.type == "turn.failed":
print(f"\n[failed: {event.data.get('error')}]")
break

For a UI, render the accumulated text keyed by message_id rather than blindly appending delta. A provider retry can restart the same message, and the completed message remains authoritative.

To show what the agent is doing while it works, listen for tool.started and tool.completed:

async for event in client.events.stream(session.id):
if event.type == "tool.started":
tool_call = event.data.get("tool_call", {})
print(f" [tool] {tool_call.get('name')}")
elif event.type == "tool.completed":
status = "ok" if event.data.get("success") else "error"
print(f" [tool] {event.data.get('tool_name')}: {status}")
elif event.type == "turn.completed":
break

output.message.completed carries a complete assistant message after streaming finishes. A turn can produce several such messages, including commentary and tool calls; turn.completed marks the end of the turn:

async for event in client.events.stream(session.id):
if event.type == "output.message.completed":
message = event.data.get("message", {})
for part in message.get("content", []):
if part.get("type") == "text":
print(part["text"])
elif event.type == "turn.completed":
break
  • Reconnection. The control plane cycles SSE connections every 5 minutes; the SDK reconnects transparently using since_id.
  • Stale detection. The server sends a heartbeat every 30s; the SDK treats >45s of silence as a dead connection and reconnects.
  • Backoff. Network errors trigger exponential backoff with jitter.
  • Typing. Each event has .type and .data attributes parsed from SSE.

While a stream is open the SDK manages reconnection internally. You only need since_id when restarting your application and resuming from a previously recorded durable event ID. With no cursor, the stream is live-only; use a stored input event ID to include responses that arrived before you subscribed:

# Persisted somewhere — file, DB, etc.
last_seen_id = load_cursor()
async for event in client.events.stream(session.id, since_id=last_seen_id):
handle(event)
if event.sequence is not None: # only persisted events are replay cursors
save_cursor(event.id)

The saved cursor is for application restart recovery. A JSON payload ID on an ephemeral delta is not a replay cursor. Use an SDK version that tracks durable SSE IDs for internal reconnection; older versions that track every payload ID can resume incorrectly after a delta. A durable-event-only stream avoids that ambiguity.

Terminal window
curl -N "https://your-host/api/v1/sessions/$SESSION_ID/sse" \
-H "Authorization: Bearer $EVERRUNS_API_KEY"

Each event arrives as:

event: turn.completed
id: event_01933b5a00007000800000000000001
data: {"id":"event_...","type":"turn.completed","data":{...}}

(Blank line terminates each event, per the SSE spec.)

Pass since_id to pick up where you left off:

SSE reconnect sequence: the client subscribes and receives connected, events with ids, heartbeats and a disconnecting notice; the stream closes; it reconnects with since_id set to the last event id; the server replays the stored events after that id from PostgreSQL, then continues with live events.

Terminal window
curl -N "https://your-host/api/v1/sessions/$SESSION_ID/sse?since_id=event_..." \
-H "Authorization: Bearer $EVERRUNS_API_KEY"

Event IDs are UUIDv7 and durable events have an atomic per-session sequence number. Resume with the last durable SSE id: field to replay stored events, not the JSON payload id. Ephemeral frames omit id:; keep the previous durable cursor when handling them. Streaming deltas are ephemeral when NATS is enabled and are not part of PostgreSQL replay; use the durable completed-message event to reconcile the full content.

The server sends a heartbeat every 30 seconds as a comment line:

: heartbeat

Comments are invisible to SSE event parsers, they don’t appear as events. Their only purpose is to keep the TCP connection alive and let your client distinguish “idle” from “dead.”

Client requirement: treat the connection as stale if no data (event or heartbeat) arrives within 45 seconds. Reconnect with the last durable SSE id: value.

To avoid stale connections through proxies, the server gracefully cycles SSE connections every 5 minutes. Before closing, it sends:

event: disconnecting
data: {"reason":"connection_cycle","retry_ms":100}

Clients should reconnect immediately using the last durable SSE id: value as since_id. Stored events are replayed; a missed ephemeral delta is recovered from its corresponding completed event.

function connect(sessionId, lastEventId) {
const url = new URL(`/api/v1/sessions/${sessionId}/sse`, API_BASE);
if (lastEventId) url.searchParams.set("since_id", lastEventId);
const es = new EventSource(url, { withCredentials: true });
es.addEventListener("connected", () => console.log("SSE connected"));
es.addEventListener("disconnecting", (e) => {
const { retry_ms } = JSON.parse(e.data);
es.close();
setTimeout(() => connect(sessionId, lastEventId), retry_ms);
});
["input.message", "output.message.delta", "turn.completed"].forEach((t) => {
es.addEventListener(t, (e) => {
const data = JSON.parse(e.data);
if (e.lastEventId) lastEventId = e.lastEventId; // SSE cursor, not data.id
// handle event...
});
});
es.onerror = () => {
es.close();
setTimeout(() => connect(sessionId, lastEventId), 2000);
};
}

The native EventSource API uses the retry: field that every event includes (100ms during active streaming, up to 500ms while idle). You don’t need to set retry yourself.

If your environment can’t hold long-lived connections (some serverless runtimes), poll instead:

Terminal window
curl "https://your-host/api/v1/sessions/$SESSION_ID/events?since_id=$LAST_ID" \
-H "Authorization: Bearer $EVERRUNS_API_KEY"

The same since_id resumption works; latency increases by the polling interval.