Streaming protocol
The HTTP wire protocol for delivering messages to an agent conversation and reading it back by offset, over JSON or SSE.
Every persistent agent conversation is an append-only, offset-addressed record
stream. Delivery and reading are separate operations. A POST durably admits a
message and returns immediately, and the reply arrives in the conversation,
which you read from an offset.
@fabric-harness/client and @fabric-harness/react wrap this surface, and most
applications should use them. Read this page when you are writing a client in
another language, debugging a transport, or building your own UI layer.
Opt-in inline stream recovery
This opt-in API is pending the next SDK release; it is not in the published 6.7 line.
For inline Native and Pi sessions, streamRecovery: 'replace' records content-free
attempt markers in the session store. Configure it in init(), session options,
or the persistent createAgent() configuration:
const fabric = await init({ store, streamRecovery: 'replace' });
const session = await fabric.session('support-ticket');
await session.prompt('Summarize the case.', {
submission: { submissionId: 'stable-delivery-id' },
});After a worker restart, the next prompt emits a model_attempt event with
status: 'superseded', supersededAttemptId, recovery: true, and mode: 'replace'
before new deltas. Discard the old attempt's display buffer. The model regenerates
from canonical history; partial text is excluded from ordinary model context
and compaction summaries. This is
replacement, not lossless delta replay or automatic retry scheduling. Retry the
original delivery with the same submissionId to avoid duplicating its user
message. Serialize execution per session, including across processes: this inline
option does not acquire a session lease or distinguish a live concurrent attempt
from an interrupted one.
The first canonical assistant message, result, or committed tool call closes
that attempt's marker atomically. A crash after a tool call is committed does
not invalidate its display or authorize re-executing it.
The option requires SessionStore.appendEntry; use a durable store to survive
process exit. Memory stores only exercise the contract within one process.
Delegated durable runtimes, including Temporal, reject this inline option and
retain their own recovery contract. Custom inline loops must explicitly declare
supportsStreamRecovery: true and honor the runtime's emit/recordEntry
contract. A custom loop that retries after visible output must give its deltas
a stable attemptId, then emit model_attempt with status: 'superseded' and
the matching supersededAttemptId before emitting replacement output.
Defaults remain unchanged. On the opt-in Pi path, reasoning deltas use text_delta
with kind: 'thinking'; keep them separate from answer text. Pi does not emit
these reasoning deltas by default.
Recovery only deduplicates an interrupted delivery's input. Hosts must inspect
durable submission completion before redispatching completed work; calling
prompt() again is not a cached-result replay API.
A canonical result may be committed before finish callbacks complete. This inline
option does not resume unfinished lifecycle callbacks or turn result persistence
into submission completion. Use a durable runtime when lifecycle restart recovery
is required.
The journal adds one store write before each attempt's first visible text,
reasoning, or tool-call delta. It saves identifiers only, never text, reasoning, or tool
arguments. It fails before exposing that delta if persistence fails or the
invocation exceeds 256 KiB of marker metadata or 2048 attempt markers
(STREAM_RECOVERY_LIMIT_EXCEEDED). Token
counts and response sizes do not consume that metadata budget. Journal entries
follow normal session retention/deletion and access controls. The
with-stream-recovery runnable example proves a real
process restart using the public SDK and file store.
Routes
Relative to a persistent agent instance at /agents/:name/:instanceId, the routes are these.
| Route | Purpose |
|---|---|
POST /agents/:name/:instanceId | Deliver one message. Returns 202 on durable admission. |
GET /agents/:name/:instanceId/conversation | Offset-based catch-up read (JSON). |
GET /agents/:name/:instanceId/history | Bounded, message-windowed read of the active path (JSON). |
GET /agents/:name/:instanceId/stream | Catch-up plus live tail (SSE). |
GET /agents/:name/:instanceId/submissions/:submissionId | One submission's status. |
POST /agents/:name/:instanceId/abort | Abort in-flight and queued work. |
conversation and stream both accept session (default default) and
offset. conversation also accepts limit. history accepts session,
limit, before, and from; see Bounded history.
Delivering a message
POST /agents/support/ticket-8472
Content-Type: application/json
{ "message": { "kind": "user", "body": "Summarize the open issues on my case." } }message accepts a full DeliveredMessage as above, or a bare string as
shorthand for { "kind": "user", "body": "..." }. The body also accepts
session (default default), initialData for instance creation, and uid
to pin a generation.
The response is 202 as soon as the message is durably admitted and before the
model runs.
{
"submissionId": "sub_01HZX...",
"streamUrl": "/agents/support/ticket-8472/conversation?session=default&offset=42",
"conversationUrl": "/agents/support/ticket-8472/conversation?session=default&offset=42",
"updatesUrl": "/agents/support/ticket-8472/stream?session=default&offset=42",
"offset": "42"
}offset is the stream position before this delivery, so reading from it
returns this message and everything the agent produces in response, with no
race against the agent starting. uid is present when the instance has a
resolved generation.
There is no "wait for the reply" mode on this route in the durable path; read the outcome from the conversation, or poll the submission.
Reading by offset
GET /agents/support/ticket-8472/conversation?offset=42&limit=100{
"incarnation": "inc_01HZ...",
"batches": [{ "offset": "42", "records": [] }],
"nextOffset": "57",
"upToDate": true
}Pass nextOffset as the next request's offset to continue. upToDate is
true when the read reached the tail. A conversation that does not exist yet
returns incarnation: null with an empty batches array instead of a 404, so
a reader can start before the first message lands.
Offsets are opaque strings. Compare them for equality. Ordering them is undefined numerically or arithmetically.
Incarnation
incarnation identifies the stream's producer generation. If it changes between
reads, the stream was rebuilt and offsets from the previous incarnation are
meaningless. Discard projected state and re-read from "0".
Bounded history
A long conversation does not have to be folded from offset zero before a client
can render the latest exchange. history returns a window of the conversation's
active path, selected by projected message count:
| Query | Returns |
|---|---|
?limit=N | The newest N messages through the head, with offset. |
?before=<cursor>&limit=N | An older page strictly before the cursor. No offset. |
?from=<cursor> | Everything from the cursor's entry through the head, with offset. |
| (none) | The whole active path, with offset. |
GET /agents/support/ticket-8472/history?limit=20{
"v": 1,
"incarnation": "stream_01HZ...",
"records": [{ "kind": "entry", "entry": { "type": "user_prompt" } }],
"settlements": [],
"before": "hc1.WyJzdHJlYW1f...",
"anchor": "hc1.WyJzdHJlYW1f...",
"offset": "57"
}records holds only entry records in path order, so the same projection
(projectConversationRecords) renders a window. Fold settlements first:
it carries the submission_settled entries that sit before the window but
settle a submission the window mentions, so an old submission never looks
active. conversationHistoryRecords(window) returns both in fold order, and
projectConversationHistoryWindow(window) projects them.
A window never splits a dependency. Its start moves back until no entry in it
depends on an earlier one (a tool result on its tool call, message data and
response metadata on the assistant message they decorate) and until it holds
every message that can still change: open tool calls, and the prompt and
current assistant message of every unsettled submission that is still active.
An unsettled submission counts as active while its newest entry lies within the
newest 200 messages. A submission that stopped recording without settling (for
example, after its worker crashed) ages out, so it cannot pin every later window
back to its prompt. A window can therefore hold more than limit messages. Pages are disjoint; concatenated oldest-first
they equal the full projection.
before is the cursor for the next older page, or null at the start of the
conversation. anchor names the window's first entry; pass it as from to
re-read everything a client holds after a reconnect. To follow live after a
limit or from window, open stream?offset=<offset>&incarnation=<incarnation>.
A before page has no offset and cannot seed a live read.
Cursors are opaque, versioned tokens bound to the stream incarnation. Do not build or parse them.
| Status | error.code | When |
|---|---|---|
400 | invalid_history_request | Malformed cursor, limit outside 1-1000, a repeated parameter, before with from, or from with limit. |
410 | history_cursor_not_found | The cursor belongs to another incarnation (the stream was deleted and recreated) or names an entry a truncation removed from the active path. |
503 | history_read_incomplete | The backing stream returned a page that was not up to date but did not advance its offset, or the read passed the scan bound (250,000 records by default). The server refuses to build a window from a partial read. Retry a stalled read; a conversation past the bound needs a fold checkpoint. |
On 410, read the newest window again. The /conversation offset read is
unchanged and remains the byte-compatible full read.
The server builds a window from the full active path, the fold checkpoint
plus the log suffix, so bounding saves transfer and client work. It does not
save server-side reads. The read stops paging as soon as the caller disconnects.
The Node server, the generated Cloudflare worker, and createFabricAgentRouter
all pass the request's abort signal into the history read.
Live tail over SSE
GET /agents/support/ticket-8472/stream?offset=42
Accept: text/event-streamThe server replays from offset, then tails. Every frame is a JSON object in
data:; : keepalive comments are sent periodically and carry no data.
Frame type | Payload | Meaning |
|---|---|---|
stream_checkpoint | incarnation, offset | Producer generation. A change means re-read from "0" (or, for a bounded client, the newest history window). |
conversation | offset, records | Durable records. offset is the next offset to resume from. |
delta | eventId, kind (text | reasoning), delta, submissionId?, turnId?, attemptId? | Token-level text or reasoning fragment. |
toolcall_delta | eventId, toolCallId, toolName, argumentTextDelta, submissionId?, turnId?, attemptId? | Streaming tool-call arguments. |
attempt_superseded | eventId, attemptId, submissionId?, turnId? | A streamed model attempt failed after partial output and is being retried. Discard every live delta and toolcall_delta with this attemptId. |
Only conversation frames are durable. delta and toolcall_delta are
presentation-only: they let a UI render tokens as they arrive, are not replayed
on reconnect, and are always superseded by the conversation records covering
the same turn. A client that ignores them loses nothing but interactivity; a
client that persists them will double-count.
Model attempt replacement
A streamed model call that fails with a transient provider error (rate limit,
5xx, dropped connection) is retried with the same bounded retries and backoff
as non-streaming calls. Every attempt has its own attemptId, stamped on its
delta and toolcall_delta frames. When the failed attempt had already
streamed output, the server sends attempt_superseded for that attempt
before the replacement attempt streams anything; the replacement re-streams
the response from the beginning. Drop the superseded attempt's text and
tool-call fragments so the answer is not shown twice. Durable conversation
records only ever contain the successful attempt, and tool calls from a failed
attempt are never executed.
Cancellation, authentication, invalid-request, and context-overflow failures are
never retried. Deltas are not replayed on reconnect, so a client that misses an
attempt_superseded frame while disconnected keeps the partial text only until
the durable record for the turn arrives.
The Responses-compatible /responses stream cannot retract deltas it already
sent. After a superseded attempt its response.output_item.done event carries
the settled text, which is authoritative.
Reconnect by re-requesting stream with the last offset you received in a
conversation frame. @fabric-harness/client reconnects after 90 seconds of
transport silence by default (idleTimeoutMs), and falls back to JSON polling
when SSE is unavailable (live: 'auto' | 'sse' | 'poll').
Records
Each record in a records array is a ConversationStreamRecord.
type ConversationStreamRecord =
| { kind: 'entry'; entry: SessionEntry }
| { kind: 'truncated'; rewoundTo: string; newLeafId: string; reason: string };A truncated record means the conversation path branched, a replay, a
checkpoint restore, or a fork. Drop every projected record after rewoundTo and
continue from the records that follow. Ignoring truncated leaves a client
showing messages that are no longer on the active path.
Projecting records for display
Raw entries are the canonical log, not a render-ready view. projectConversationRecords
from @fabric-harness/sdk/conversation reduces a record sequence into a stable
UI protocol:
import { projectConversationRecords } from '@fabric-harness/sdk/conversation';
const { messages, settlements } = projectConversationRecords(records);A ConversationMessage carries id, role, purpose, display, optional
createdAt/submissionId/turnId/metadata, and an ordered parts array.
createdAt is the server-authored ISO-8601 time the durable entry that created
the message was recorded. Order messages by position, not by time.
Part type | Shape |
|---|---|
text | text, state: 'streaming' | 'done' |
reasoning | text, state: 'streaming' | 'done' |
file | mediaType, optional id, digest, size, filename; emitted for image and PDF attachments on user messages |
dynamic-tool | toolName, toolCallId, and a state-specific payload (input-streaming, input-available, output-available, output-error) |
data-${name} | data, agent-authored structured parts written with useDataWriter() |
Honor display, because hidden messages are not for users and diagnostic ones
belong behind a debug affordance. purpose distinguishes a user turn from a
dispatched signal or an advisory injection.
settlements reports terminal submission outcomes, completed, failed, or
aborted, with error and answeredBySubmissionId where they apply, and a
server-authored timestamp for when the settlement was recorded. A
submission that joined a busy conversation is answered by another submission's
assistant turn, which answeredBySubmissionId names.
Implementation checklist
For a client in another language:
POSTthe message; keepsubmissionIdandoffsetfrom the202.- Read from that
offset. SSE if you want live tokens, JSON polling otherwise. - Treat offsets as opaque; resume from
nextOffsetor aconversationframe'soffset. - Re-read from
"0"wheneverincarnationchanges. - Apply
truncatedrecords by discarding everything afterrewoundTo. A bounded client that does not holdrewoundTore-reads its window. - Render from
deltaframes if you want streaming, but persist onlyconversationrecords. Onattempt_superseded, drop the deltas carrying thatattemptId. - Stop when a settlement for your
submissionIdappears, or when the submission status is terminal.
See also
- Events: the session entry types that appear inside records.
- Agent behavior: built-in tool semantics reflected in tool parts.
- React: the hook layer built on this protocol.
Agent Events
Subscribe to a typed event stream from any TechFabric Harness agent. Text deltas, tool calls, shell commands, approvals, tasks and errors.
Context Compaction
Automatic, event-emitting context compaction for long sessions. Default import enables it; /strict opts in explicitly. Threshold and overflow modes.