The Event Stream Isn't Your API
LangGraph v3 normalizes tokens, tools and tasks. A chat UI needs turns, rooms, replay and retraction. We put a projection layer between the stream and the UI.
The stream is a projection, not a contract
streamEvents(input, { version: 'v3' }) returns a GraphRunStream — an async iterable of protocol events with a small, engine-oriented envelope: seq, method, and params containing namespace, timestamp, and data. LangChain still calls v3 experimental/beta (v3 was added in langgraph 1.2.0 and langchain 1.3.0 in May 2026). Our code is pinned to @langchain/langgraph ^1.7.5; check the channel names again when you upgrade.
The engine has no concept of an agent turn. It doesn’t know which browser should see an event, what the UI must rebuild after a reload, or that the harness sometimes throws away a half-written answer. There is no stable ordering key either: upstream docs warn that params.timestamp is wall-clock milliseconds and can drift.
We project the stream into typed wire events carrying our own fields: threadId, agentTurnId, traceId, agentNodeId, observabilityRunId, a monotonic per-turn seq and an ISO timestamp. A Zod boundary validates each payload. A feature descriptor supplies the transport contract, the emitter publishes to one Socket.IO room, and a persistence observer writes the replay log.
graph LR
A["LangGraph v3<br/>messages / tools / tasks"] --> B["createAgentProtocolEventMapper()"]
B --> C["Typed wire events<br/>Zod validated"]
C --> D["SKILL_BUILDER_PROTOCOL_DESCRIPTOR<br/>channel + event + room + scope"]
D --> E["Socket.IO /realtime<br/>skill-builder:thread:THREAD_ID"]
C --> F["AgentTurnEventStorage<br/>turn replay log, live-only filtered"]
What LangGraph v3 actually emits
V3 exposes nine channels: values, updates, messages, tools, lifecycle, checkpoints, input, tasks and custom. We listen to three. messages gives us message-start, content-block-start, content-block-delta, content-block-finish, message-finish; deltas arrive as text-delta, reasoning-delta, data-delta, tool-call-delta and block-delta. We read only the first two delta kinds. tools emits tool-started, tool-output-delta, tool-finished, tool-error — we take the start, finish and error events. Unknown delta types and tool-output-delta are ignored on purpose: a new provider feature should not break a live turn.
// ProtocolEvent from streamEvents(..., { version: 'v3' })
{
seq: 41,
method: 'messages',
params: {
namespace: ['agent:5f1c', 'tools:91ac'],
timestamp: 1774363200123, // wall-clock ms, may drift
data: {
event: 'content-block-delta',
delta: { type: 'text-delta', text: 'Updated the surcharge to 12%.' },
run_id: 'run_7f3a',
},
},
}// SkillBuilderProtocolEvent, validated in toWireEvent()
{
type: 'agent_delta',
threadId: '66c9...', // thread document id
agentTurnId: 'turn_8a1b',
seq: 41, // our own per-turn counter
timestamp: '2026-11-24T12:00:00.123Z',
traceId: '019a...',
checkpointerThreadId: 'checkpoint-uuid',
actor: 'main-agent',
agentNodeId: 'turn_8a1b',
delta: 'Updated the surcharge to 12%.',
kind: 'text',
messageId: 'm2', // engine model-message id
}SKILL_BUILDER_PROTOCOL_DESCRIPTOR = {
feature: AgentProtocolFeature.SKILL_BUILDER,
busChannel: 'skill-builder:stream:event',
wsEventName: 'skill-builder:event',
roomPrefix: 'skill-builder:thread:',
streamScope: AgentProtocolStreamScope.THREAD,
toWireEvent: toSkillBuilderProtocolEvent,
// + buildModelRetryPayload / buildAgentMessageDiscardedPayload
// + buildDecisionPayload (decision features only)
};
LIVE_ONLY_AGENT_PROTOCOL_EVENT_TYPES = new Set([
'agent_delta', 'model_retry',
'decision_started', 'decision_finished',
'agent_message_discarded',
]);The wire sample uses two id spaces. threadId is the agent-thread document id, and it keys the room. checkpointerThreadId is the LangGraph checkpointer thread_id — the key checkpoints and observability runs are stored under. Mix them up, and the event goes nowhere.
The mapper: three channels, one identity space
createAgentProtocolEventMapper translates events rather than passing them through. For each turn, it holds state shared with the emitter: a namespace→delegated-run index and the message each agent node is currently streaming.
- 01
Consume only three channels
`tasks` registers delegated runs without returning a wire event; `messages` and `tools` are projected. Everything else falls through to `NO_EVENTS`.
- 02
Resolve identity
`message-start` records engine message ids by model run id and marks non-ai roles. A one-shot tool-run bridge joins `tool_call_id` to its observability span; `tasks` events and dispatching tool calls populate the namespace registry.
- 03
Project and validate
`text-delta` and `reasoning-delta` map to `kind='text'` / `kind='reasoning'`; tool events gain normalized `ToolCallMetadata`; `toWireEvent` parses one schema per event (a single schema on the delta hot path).
- 04
Fail open without stopping the turn
We log any unmappable event with its method and error, then drop it. One provider quirk cannot abort a live agent turn.
That shared state also makes retraction work: every delta calls observeDelta(agentNodeId, messageId), so the emitter knows which bubble to remove before a retry.
One emitter, two products: live rooms and a replay log
AgentProtocolTurnEventEmitter.emit() bumps seq, stamps the envelope, publishes to the typed in-process bus, then calls onWireEvent. Each bus adapter binds one listener per registered descriptor and emits to io.of('/realtime').to(room). If a conversation-scoped stream has no conversationId, the descriptor constructor throws and protocolRoom() returns null; the adapter logs and drops the event instead of broadcasting to the wrong room.
One object serves both paths: the event sent to the bus also reaches the persistence observer, so live and replay share ids, seq and shape. The observer drops the five live-only types and keeps the rest. AgentTurnEventStorage upserts one document per settled turn. Storage failures are swallowed in two places — the emitter’s observer and the thread service’s persistTurnEvents — and the final flush runs in finally, after the terminal events have been emitted.
Event-time makes replay coherent
Manual events never come from the engine, so without an explicit timestamp they would sort as “now” — even when they belong at the tail of an older stream. We track lastOccurredAtMs, the engine timestamp of the most recent mapped delta, and stamp turn_completed, input_requested, cancellation and turn_failed with it. A committed ai_message uses its first delta’s timestamp or falls back to lastOccurredAtMs.
Ordering never depends on that timestamp. The wire seq is ours, monotonic per turn, and it carries the same number in the live stream and the stored log. That’s why reconnect and replay can’t disagree about order, even when upstream wall clocks drift.
Retraction is a wire event, not a UI hack
A model call can fail halfway through an answer. You can’t un-send those bytes, but you can tell the client which segment to delete. claimStreamingMessageId() returns — and forgets — the id of the message a node is streaming. publishRetryNotice() emits agent_message_discarded with that id before model_retry. The ask-user enforcement middleware provides a second path: it throws away a response the agent isn’t allowed to keep, with no retry involved.
private publishRetryNotice(notice: ModelRetryNotice): void {
const node = this.noticeNode(notice);
const failed = this.p.state.claimStreamingMessageId(node.agentNodeId);
if (failed !== undefined) {
this.emit(buildAgentMessageDiscardedPayload({
agentNodeId: node.agentNodeId,
actor: node.actor,
messageId: failed,
}));
}
this.emit(buildModelRetryPayload({
agentNodeId: node.agentNodeId,
actor: node.actor,
attempt: notice.attempt,
maxRetries: notice.maxRetries,
delayMs: notice.delayMs,
retryAt: retryAtIso,
}));
}for (const response of responsesByNodeAndMessage.values()) {
if (discardedMessageIds.has(response.messageId)) continue;
if (response.text === '' && response.thinking === '') continue;
emit({
type: 'ai_message',
agentNodeId: response.agentNodeId,
aiMessageId: response.messageId,
text: response.text,
...(response.thinking ? { thinking: response.thinking } : {}),
}, response.firstOccurredAtMs ?? lastOccurredAtMs);
}// deltas open a segment per messageId
// agent_message_discarded removes that segment by id,
// regardless of event ordering or retries
on('agent_message_discarded', (event) => {
removeBubble(event.agentNodeId, event.messageId);
});
on('ai_message', (event) => {
replaceWithCommitted(event.agentNodeId, event.aiMessageId, event.text);
});We made this choice deliberately. The Vercel AI SDK documents the opposite trade-off: non-tool output already emitted before a provider error can’t be retracted, so a retried step may append repeated or divergent text. One extra wire type gives us a retraction event and, with it, a correct conversation.
Switch to Replay log: deltas, the retry notice and the discard notice disappear, but the committed answer survives with the same seq it had in the live stream.
Nested agents need a namespace tree
We derive delegation identity from engine signals, not naming conventions. A tasks event registers a node when its data carries metadata.lc_agent_name (set by createAgent({ name })) and its checkpoint namespace already holds a dispatching tool_call_id. namespaceKey() joins segments with NUL for the in-memory index. Checkpoint namespace strings from runtime.configurable.checkpoint_ns use | instead, so a retry can append |retry-N without changing the parent it resolves to.
const registerDelegatedRun = (event: ProtocolEvent): void => {
if (delegation === undefined) return;
const namespace = event.params.namespace;
if (namespace.length === 0 || state.nodes.has(namespace)) return;
const name = readSubagentName(event.params.data); // metadata.lc_agent_name
if (name === undefined || !delegation.isSubagentTool(name)) return;
const subagentNodeId = dispatchingToolCallIdByNamespace
.get(namespaceKey(namespace));
if (subagentNodeId === undefined) return; // stays unattributed
state.nodes.register(namespace, {
subagentNodeId, name, parentSubagentNodeId: parent?.subagentNodeId,
depth: parent === undefined ? 0 : parent.depth + 1,
});
};findDeepest(namespace: readonly string[]) {
for (let length = namespace.length; length > 0; length -= 1) {
const registration = this.byNamespace
.get(namespaceKey(namespace.slice(0, length)));
if (registration !== undefined) return registration;
}
return undefined;
}
findDeepestForCheckpointNamespace(checkpointNs?: string) {
// e.g. 'agent|tools|editor-call' -> ['agent','tools','editor-call']
return checkpointNs ? this.findDeepest(checkpointNs.split('|')) : undefined;
}function delegatedRunConfigForAttempt(base, attempt) {
if (attempt <= 0) return base;
return {
...base,
configurable: {
checkpoint_ns: base.configurable.checkpoint_ns + '|retry-' + attempt,
},
};
}
// A fresh checkpoint means a failed attempt's half-finished
// conversation is never replayed, while the base prefix still
// resolves to the same subagent node.Subagent output uses the same envelope and rooms, with two additional event types — subagent_node_started and subagent_node_finished — so the UI can nest decision cards under the right editor node.
- Tool cards show raw tool_call_id
- A failed retry leaves a half-sentence
- Reload replays every token delta
- Nested events land on the parent node
- Stable agentNodeId and ToolCallMetadata
- Retraction by messageId before model_retry
- Append-only log excluding five live-only types
- Namespace tree uses longest-prefix matching
Two supporting pieces: trace joins and typed HITL
The protocol also joins trace spans and validates human-in-the-loop interrupts.
AgentToolRunBridge joins two systems that share only an id. The LangChain callback handler calls recordStart(tool_call_id, observabilityRunId). The v3 mapper, on seeing tool-started, calls consumeStart(tool_call_id), consumes the value once and stamps it as observabilityRunId on the tool metadata. A chat tool card can now deep-link to its exact span in the turn trace.
For human-in-the-loop flows, we read LangGraph’s untyped checkpoint writes but do not trust them verbatim. extractPendingInterrupt collects the task ids already resumed via __resume__, skips their __interrupt__ writes, validates the remaining writes against a Zod schema, and keeps the newest pending question along with its response_schema. On reload, shouldReportPendingInterrupt only shows the prompt when no run is active and the last turn’s status is interrupted — a stale interrupt from a cancelled run stays hidden. extractInterruptedToolCalls re-seeds the interrupted askUser tool call so its start metadata is available when the resumed stream begins.
Rollout and rules of thumb
We assembled the contract a layer at a time, each piece testable on its own:
LangGraph v3 stream
Protocol events with seq, method and params.namespace / timestamp / data. Experimental upstream; pinned and isolated.
event-transformer.ts
Three channels mapped, role-based delta filtering, delegated-run registration and fail-open NO_EVENTS.
realtime-event-bus.ts
Typed wire events, per-turn seq, feature descriptors, synchronous retry and discard notices, live-only filter.
agent-turn-event-storage.ts
One upserted document per settled turn; live and replay keep identical ids, envelopes and seq.
Back to Cheap router, strong writer — the orchestrator whose decisions produce these events.
Share this article
Common questions
Is the output of LangGraph's streamEvents v3 a stable public API?
Which LangGraph v3 channels do we consume?
What is excluded from the persisted replay log?
How do we retract a partially streamed LLM answer when a call is retried?
How do we attribute subagent events to the right UI node?
How do we route LangGraph agent events to Socket.IO rooms?
Related articles
Keep reading
Cheap Router, Strong Writer: Decision Models in the ReAct Loop
A decision model picks the next tool call, a chat call writes the arguments, and fail-closed guards keep edits from being dropped.
Read#03 · Decision models & orchestrationA Guardrail That Edits the Action Space
Re-ask with end_agent_run removed and the reason stated. No louder prompt.
Read#02 · Decision models & orchestrationNot Every Tool Argument Needs the Same Model
Deterministic code, one decision call, or a chat model — chosen by argument shape.
Read