@flow-state-dev/core/items
Type Aliases
BlockTraceItem
type BlockTraceItem = OutputItemBase & object;
Type Declaration
blockInstanceId
blockInstanceId: string;
blockKind
blockKind: "generator" | "evaluator" | "handler" | "sequencer" | "router";
blockName
blockName: string;
completedAt?
completedAt?: number;
declaredResources?
declaredResources?: string[];
Accessor/storage keys this block declares at build time
(ownDeclaredResources). Surfaced so the DevTool can show
"declared but not loaded" (over-declaration). Present only under trace
observability.
duration?
duration?: number;
error?
error?: object;
error.code?
code?: string;
error.details?
details?: Record<string, unknown>;
Open structured payload attached at failure time. Runtime auto-populates
well-known keys (rawOutput, issues, phase) for generator
output-validation failures; author-thrown FlowError.details flows
through verbatim.
error.message
message: string;
evaluator?
evaluator?: object;
What an evaluator block asked: the requested model (a model string, or
provider/modelId for an evaluation model instance) and the question
set, keyed by question id. Absent for other kinds.
evaluator.model
model: string;
evaluator.questions
questions: Record<string, EvaluatorTraceQuestion>;
generator?
generator?: object;
generator.history?
history?: unknown[];
generator.model
model: string;
generator.prompt
prompt: string;
generator.templateFrontmatter?
templateFrontmatter?: Record<string, unknown>;
Parsed, Zod-validated frontmatter, present for PromptFile prompts.
generator.templateSource?
templateSource?: string;
Raw .md source, present when the prompt was authored via a PromptFile
(definePromptFile). Absent for inline-string/function prompts.
generator.tools
tools: string[];
generator.user?
user?: unknown[];
harnessSpend?
harnessSpend?: object[];
The harness runs this block settled, each as its harness reported it. Present only on a completed block that settled one: a continuation replays the block without running it again, so this is how that run's spend still reaches the request's ending after its process died.
input?
input?: object;
input.connected?
connected?: unknown;
input.source
source: BlockValueInternal<unknown>;
lean?
lean?: true;
true on the lean completion record the runtime writes when trace
observability is off: identity, output, rescued, and a generator's or
evaluator's modelUsage without its provider metadata, so a continuation
after the process died still counts what the block spent. Absent on full
traces and on records written before lean records existed.
model?
model?: ModelIdentity;
Resolved identity of the model that actually ran for generator and
evaluator blocks.
Sibling of generator.model (the requested string) and
modelUsage.model (the token-accounting key, also requested-string).
Populated even when the generator emits no items, so audit/replay/billing
have a durable record of the concrete model. Absent for non-generator
blocks and for generators that errored before any AI SDK call returned.
modelUsage?
modelUsage?: object;
modelUsage.cacheCreationTokens?
cacheCreationTokens?: number;
modelUsage.cacheReadTokens?
cacheReadTokens?: number;
modelUsage.completionTokens
completionTokens: number;
modelUsage.model
model: string;
modelUsage.promptTokens
promptTokens: number;
modelUsage.providerMetadata?
providerMetadata?: Record<string, Record<string, unknown>>;
modelUsage.totalTokens
totalTokens: number;
output?
output?: BlockValueInternal<unknown>;
rescued?
rescued?: true;
true when the block threw and a .rescue() handler produced its output.
Recorded whatever the trace-observability setting, so a resume that
replays the block keeps ctx.wasRescued() unchanged. Absent otherwise.
resourceLoads?
resourceLoads?: ResourceLoadRecord[];
Resource loads attributable to this block's dispatch window: wave-3
eager preloads of ownDeclaredResources, plus lazy reads issued inside
execute(). On the request's entry block_trace this also carries the
orphan wave-1 (flow-eager) and wave-2 (action-eager) loads. Present only
when trace observability is enabled and at least one load was recorded.
startedAt?
startedAt?: number;
status
status: "in_progress" | "completed" | "failed" | "planned";
toolCall?
toolCall?: object;
toolCall.arguments
arguments: string;
toolCall.callId
callId: string;
toolCall.generatorBlock
generatorBlock: string;
type
type: "block_trace";
BlockValue
type BlockValue<T> =
| {
kind: "inline";
value: T;
}
| {
kind: "structure";
shape: StructureShape;
}
| OmittedValue;
Discriminated union describing how a block's output item carries its content.
inline— the block produced novel content. Leaves (generators, handlers) and explicit transforms (.map,connectOutput) use this kind.ref— the block's output is reference-identical to another item's content. Pass-through composers (.step,.sideChain,.tap, routers,.rescue) use this kind to avoid duplicating content at every nesting level.structure— the block produced a novel container whose slots are refs or inlines. Aggregators (.stepAll,.parallel,.forEach) use this kind.
Invariants:
- Every
refpoints one hop to a content-bearing item (never another ref). This is guaranteed by flatten-at-emit in the executor. - The union kind is determined by the builder step that constructed the block,
not by runtime equality. Consumers can reason about composition intent from
the shape:
inlineon a sequencer means a transform happened at that node.
Type Parameters
T
T = unknown
ContainerItem
type ContainerItem = OutputItemBase & object;
Visual grouping emitted by sequencers and routers that declare a container
config. Lifecycle: item.added with status: "in_progress" when the
sequencer scope opens; item.updated patching status, completedAt,
duration (and error on failure) when the scope closes; finally
item.done with the terminal status. Public-stream consumers see a live
in-flight signal for sequencer execution.
Type Declaration
blockName
blockName: string;
completedAt?
completedAt?: number;
Wall-clock time the scope closed (success or failure).
component?
component?: string;
duration?
duration?: number;
completedAt - startedAt, in ms.
error?
error?: object;
Set on failure with the throwing error's message.
error.message
message: string;
label?
label?: string;
metadata?
metadata?: Record<string, unknown>;
startedAt?
startedAt?: number;
Wall-clock time the sequencer/router scope opened.
type
type: "container";
Content
type Content =
| OutputTextContent
| ReasoningTextContent
| RefusalContent
| FileContent
| OutputAudioContent;
ContentAudioDeltaEvent
type ContentAudioDeltaEvent = RequestEventBase & object;
A chunk of synthesized audio for an OutputAudioContent part that is being
streamed. Live-only — not replayed on Last-Event-ID resume; the durable
snapshot is the eventual OutputAudioContent delivered via
content.added / content.done. Chunks do not carry mediaType because
it is stable across the stream and declared on the parent content part.
Set isLast: true on the final chunk so clients can flush their decode
pipeline without waiting for content.done.
Type Declaration
audio
audio: string;
Base64-encoded audio chunk bytes.
contentIndex
contentIndex: number;
isLast?
isLast?: boolean;
itemId
itemId: string;
type
type: "content.audio.delta";
ContentBase
type ContentBase = object;
Base properties shared by all content types.
ephemeral content is streamed to the client via SSE but stripped
before items are persisted to the store, avoiding storage of large
binary payloads like audio.
Properties
ephemeral?
ephemeral?: boolean;
ContentPartAddedEvent
type ContentPartAddedEvent = RequestEventBase & object;
Type Declaration
content
content: Content;
contentIndex
contentIndex: number;
itemId
itemId: string;
type
type: "content.added";
ContentPartDeltaEvent
type ContentPartDeltaEvent = RequestEventBase & object;
Type Declaration
contentIndex
contentIndex: number;
delta
delta: string;
itemId
itemId: string;
type
type: "content.delta";
ContentPartDoneEvent
type ContentPartDoneEvent = RequestEventBase & object;
Type Declaration
content
content: Content;
contentIndex
contentIndex: number;
itemId
itemId: string;
type
type: "content.done";
ContinuationItem
type ContinuationItem = OutputItemBase & object;
Emitted when a durable action re-enters after a crash mid-execution (DevTool continuation). Marks the seam between the prior durable log and the live re-run that followed. Not a HITL item — no suspension is involved.
Visibility: client=true, history=false — structural, falling through to
STRUCTURAL_DEFAULT. Non-transient, so a GET returns the crash-recovery
boundary as part of the audit trail.
Type Declaration
continuedAt
continuedAt: number;
priorItemCount
priorItemCount: number;
Count of items already in the durable log at re-entry (the seam position). Named "prior", not "replayed": the prior log may include retained partial/in-progress rows, not only injected completed outputs.
resumedAtPath?
resumedAtPath?: string;
Logical block path where live execution resumed (the in-flight block re-run).
trigger
trigger: "recovery";
Why re-entry happened. Crash-recovery /continue today; reserved for future triggers.
type
type: "continuation";
DataItem
type DataItem = OutputItemBase & object;
Structured content at this point in the conversation, emitted with
ctx.emit.data(dataType, value). The one item kind for it: code reads a
data item back by dataType (a routing decision, a task change), and a
client draws one only when it registers a renderer for its dataType
(generative UI such as a link card is a dataType that ships with one). A
data item with no renderer is still on the stream and in the session, and
draws nothing.
Reaches the client and not model history by default; itemVisibility
overrides that (see resolveItemVisibility).
Type Declaration
dataType
dataType: string;
What kind of record this is, e.g. "task-change". Readers match on it.
key?
key?: string;
Caller-provided stable identity for deduplication.
Combined with transient: false, this expresses the keyed snapshot
pattern — one logical entity whose latest state replays on reload.
Keyed emissions upsert: the item ID is derived from key, the persisted
record holds one entry per (requestId, key), and value is replaced
(not merged) on each emission. The SSE event log still appends per
emission. See apps/docs/docs/streaming/emitting-items.md.
type
type: "data";
value
value: Record<string, unknown>;
The record. Replaced wholesale, never merged, on a keyed re-emission.
DebugEvent
type DebugEvent = RequestDebugEvent;
ErrorItem
type ErrorItem = OutputItemBase & object;
Type Declaration
code?
code?: string;
details?
details?: Record<string, unknown>;
Open structured payload attached at failure time. Same shape and
well-known keys as block_trace.error.details / tool_output.error.details
(e.g. cause for the serialized cause chain, httpStatus / responseBody
/ errorType from the fetch tool) so every error surface renders
identically in the devtool.
message
message: string;
type
type: "error";
EvaluatorTraceQuestion
type EvaluatorTraceQuestion = object;
One question as recorded on an evaluator's block_trace row. Mirrors the
question the block asked: its type, its instructions, and its options
(choice), levels (score) or true/false descriptions (boolean).
Properties
criteria?
criteria?: unknown;
instructions
instructions: unknown;
type
type: "choice" | "score" | "boolean";
EventBase
type EventBase = RequestEventBase;
FileContent
type FileContent = ContentBase & object;
Type Declaration
data
data: string;
filename?
filename?: string;
mediaType
mediaType: string;
type
type: "file";
GeneratorStepItem
type GeneratorStepItem = OutputItemBase & object;
Replay-only per-step record of a generator's owned tool loop.
Written by the framework-owned generator loop BEFORE it dispatches a
tool-calling step's tools, one per tool-calling step, keyed by the
generator's logical path + stepNumber (accumulating — never overwritten).
It is the ONLY durable record of a step's assistant turn: per the
byte-identical-emissions rule the loop buffers per-step text in memory and
never emits an assistant message/reasoning per step, and tool_output
only becomes durable once a specific call starts dispatching. This artifact
closes both gaps for resume:
- it carries the step's buffered pre-tool
textso a turn that emitted assistant text then suspended reconstructs with that text intact; - it carries the step's full
toolCallsarray (ids/names/aliases/args) so reconstruction can group by step (one assistant message per step) and a crash between the model step returning and anytool_output.item.addedis still recoverable without re-calling the model. On step 0 it also carries the compiled initialprelude(the messages fromassembleMessages) so resume reads the original prompt/context rather than re-running resolvers that may have observed different state after the human-approval wait.
Visibility is { client: false, history: false } (a TRACE_TYPE): it is
purely a resume substrate and must never surface via GET/useSession or
enter LLM history. collapseToCanonicalLog retains it (like block_trace)
so it survives across resume cycles.
Type Declaration
blockInstanceId
blockInstanceId: string;
The generator block's logical instance id (${requestId}:${path}:${attempt}).
prelude?
prelude?: unknown[];
The compiled initial messages (assembleMessages output). Present ONLY on
the step-0 artifact; resume reads it instead of recomputing the prelude.
stepNumber
stepNumber: number;
0-based index of this model step within the generator's owned loop.
systemPrefixCount?
systemPrefixCount?: number;
The number of leading system-prefix messages in prelude.
Present ONLY on the step-0 artifact. On resume the loop seeds messages
from the persisted prelude, so prepareStep must slice off THIS prefix
length — not a freshly-assembled one, which can differ if a dynamic
prompt/context changed the prefix during the approval wait.
text?
text?: string;
The step's buffered pre-tool assistant text/reasoning, when any.
toolCalls
toolCalls: object[];
The step's full requested tool-call array, in call order.
type
type: "generator_step";
InvalidationItem
type InvalidationItem = OutputItemBase & object;
Shared base for stream items that signal "something changed in a scope" and
that clients use as invalidation cues. Carries the fields common to
state_change and resource_change. Not a member of the OutputItem union —
only its typed leaves are. The base is the loosest supertype: scope holds the
widest set and version is optional, so each leaf can tighten exactly the
fields its contract narrows (intersection types narrow, never widen).
Type Declaration
delta?
delta?: unknown;
scope
scope: "request" | "session" | "user" | "org" | "block_instance";
version?
version?: number;
ItemAddedEvent
type ItemAddedEvent = RequestEventBase & object;
Type Declaration
item
item: OutputItem;
type
type: "item.added";
ItemDoneEvent
type ItemDoneEvent = RequestEventBase & object;
Type Declaration
item
item: OutputItem;
type
type: "item.done";
ItemLookup
type ItemLookup = (itemId) =>
| OutputItem
| BlockTraceItem
| undefined;
Lookup signature used by resolveBlockValue. Returns any item type — the
resolver branches on target.type. The wider union accepts trace items
(BlockOutputItem) since refs may target them internally.
Parameters
itemId
string
Returns
| OutputItem
| BlockTraceItem
| undefined
ItemProvenance
type ItemProvenance = object;
Properties
attempt?
attempt?: number;
blockDefinitionId?
blockDefinitionId?: string;
blockInstanceId
blockInstanceId: string;
blockName
blockName: string;
parentBlockInstanceId?
parentBlockInstanceId?: string;
phase
phase: "main" | "sideChain";
sideChainGroupId?
sideChainGroupId?: string;
stepIndex?
stepIndex?: number;
ItemStatus
type ItemStatus = "in_progress" | "completed" | "incomplete" | "failed";
ItemUpdatedEvent
type ItemUpdatedEvent = RequestEventBase & object;
Shallow top-level merge update for a previously-emitted item. Each
top-level key in patch replaces the existing value at that key on
the consumer's tracked item. Nested updates require re-supplying the
full nested object as the new top-level value.
Identity-invariant keys (see ITEM_UPDATE_INVARIANT_KEYS) are stripped
both server-side and client-side before the patch is applied.
Type Declaration
itemId
itemId: string;
patch
patch: Record<string, unknown>;
type
type: "item.updated";
MessageItem
type MessageItem = OutputItemBase & object;
Type Declaration
content
content: Content[];
Message content parts. output_text parts accumulate text in-place
during streaming: each content.delta event mutates the current
snapshot held inside the emitter, and consumers reading
response.getItems() observe the latest accumulated text. The final
item.done payload supersedes any mid-stream accumulation, so the
authoritative final text always comes from the generator's terminal
emission. Aborted streams may leave a partial-token tail in the
persisted snapshot — this is a deliberate trade-off.
metadata?
metadata?: Record<string, unknown>;
Structured data a handler attached to the message with
ctx.emit.message(text, { metadata }), or an action's userMessage
returned with its echo's text, for a client to read instead of
parsing content. Opaque to the engine and never sent to a model: the
package that emits the message owns the keys it writes, and exports the
reader for them. Absent when nothing was attached, and on every
generator-emitted message.
model?
model?: ModelIdentity;
Resolved identity of the generator model that produced this message.
Stamped only when emitted by a generator block; handler-emitted
messages (via ctx.emit.message) leave this field absent.
role
role: "assistant" | "user" | "system" | "developer" | "tool";
type
type: "message";
OmittedValue
type OmittedValue = object;
What the record holds in place of a value it left out. The response emitter
writes it when a block output or a tool result is over the server's
maxRecordedValueBytes (256 KiB by default) once serialized, or cannot be
serialized at all. The run itself keeps the real value; only the log, the
stream and later prompts see this. Resume never hands it on: a replay that
would inject it fails with RECORDED_VALUE_OMITTED.
The same object is a BlockValue case on block_trace.output and the
outputOmitted field of a tool_output.
Properties
bytes
bytes: number | null;
Serialized UTF-8 size in bytes, or null when the value could not be serialized.
kind
kind: "omitted";
preview
preview: string;
The first 512 characters of the serialized value.
OutputAudioContent
type OutputAudioContent = ContentBase & object;
Type Declaration
audio
audio: string;
mediaType
mediaType: string;
transcript?
transcript?: string;
type
type: "output_audio";
OutputItem
type OutputItem =
| MessageItem
| ReasoningItem
| ToolOutputItem
| DataItem
| ContainerItem
| SourceItem
| StatusItem
| ErrorItem
| StateChangeItem
| ResourceChangeItem
| SuspensionItem
| SuspensionResumeItem
| ContinuationItem;
OutputItemBase
type OutputItemBase = object;
Properties
agentName?
agentName?: string;
Stable name of the producing agent. Defaults to the generator's block
name when itemVisibility is set. Multiple generators that share an
agentName collaborate (same logical agent across instances); distinct
names stay isolated.
id
id: string;
Stable identity for the item. Most items mint a fresh random ID per emission; keyed data items are an exception (see DataItem.key).
itemIndex
itemIndex: number;
itemVisibility?
itemVisibility?: ItemVisibility;
Transport and memory visibility for this item. Conversational items
(message, reasoning, tool_output) carry this from the producing
generator; structural items ignore it (they have fixed per-type defaults).
{ client: true, history: true }— normal conversational turn.{ client: true, history: false }— observable work (sub-agent output).{ client: false, history: true }— private/injected context.{ client: false, history: false }— trace (devtool only).
When absent on a conversational item, resolveItemVisibility falls back
to { client: true, history: true } (handler-emit ergonomics).
ownedBy?
ownedBy?: string;
When set, this item was emitted inside a container scope. The value is the
blockInstanceId of the sequencer/router that declared the container.
provenance
provenance: ItemProvenance;
requestId
requestId: string;
status
status: ItemStatus;
taskId?
taskId?: string;
Id of the task this item was emitted under, when produced inside a worker
scope that marked its active task via ctx._markTaskScope (the task-board
worker body does this per claimed task). Captured at emit time from the
nearest enclosing marked scope, so concurrent sibling workers and
sequential turns of one worker attribute correctly even when their
execution paths collide. Undefined for items emitted outside any task
scope. Read by the task-attribution helpers in @flow-state-dev/core/items.
transient?
transient?: boolean;
When true, the item is delivered to live SSE consumers but never persisted to the session log or replayed on history reload.
Composes orthogonally with DataItem.key: see the "keyed
snapshot" pattern in apps/docs/docs/streaming/emitting-items.md for
the full transient × key matrix.
ts
ts: number;
type
type: string;
OutputTextContent
type OutputTextContent = ContentBase & object;
Type Declaration
annotations?
annotations?: Record<string, unknown>[];
text
text: string;
type
type: "output_text";
PingEvent
type PingEvent = RequestPingEvent;
ReasoningItem
type ReasoningItem = OutputItemBase & object;
Type Declaration
model?
model?: ModelIdentity;
Resolved identity of the generator model that produced this reasoning.
summary
summary: Content[];
Reasoning summary parts. reasoning_text parts accumulate text
in-place during streaming via the same content.delta channel as
message text (see MessageItem.content).
type
type: "reasoning";
ReasoningTextContent
type ReasoningTextContent = ContentBase & object;
Type Declaration
text
text: string;
type
type: "reasoning_text";
RefusalContent
type RefusalContent = ContentBase & object;
Type Declaration
text
text: string;
type
type: "refusal";
RequestCreatedEvent
type RequestCreatedEvent = RequestEventBase & object;
Type Declaration
status
status: "in_progress";
type
type: "request.created";
RequestDebugEvent
type RequestDebugEvent = RequestEventBase & object;
Type Declaration
data
data: unknown;
name
name: string;
type
type: "debug";
RequestEventBase
type RequestEventBase = object;
Properties
requestId
requestId: string;
sequence_number
sequence_number: number;
stream
stream: "request";
ts
ts: number;
RequestPingEvent
type RequestPingEvent = RequestEventBase & object;
Type Declaration
type
type: "ping";
RequestResourceChangedEvent
type RequestResourceChangedEvent = RequestEventBase & object;
Type Declaration
changeType
changeType: "created" | "updated" | "deleted";
resourcePath
resourcePath: string;
scope
scope: "request";
type
type: "resource.changed";
RequestStatusEvent
type RequestStatusEvent = RequestEventBase & object;
Type Declaration
status
status: RequestStatus;
type
type: `request.${RequestStatus}`;
RequestStreamEvent
type RequestStreamEvent =
| RequestCreatedEvent
| RequestStatusEvent
| ItemAddedEvent
| ItemDoneEvent
| ItemUpdatedEvent
| ContentPartAddedEvent
| ContentPartDeltaEvent
| ContentPartDoneEvent
| ContentAudioDeltaEvent
| RequestResourceChangedEvent
| SessionMetadataChangedEvent
| RequestDebugEvent
| RequestPingEvent;
ResourceChangedEvent
type ResourceChangedEvent = RequestResourceChangedEvent;
ResourceChangeItem
type ResourceChangeItem = InvalidationItem & object;
Type Declaration
changeType
changeType: "created" | "updated" | "deleted";
resourcePath
resourcePath: string;
scope
scope: "request" | "session" | "user" | "org";
type
type: "resource_change";
ResourceLoadRecord
type ResourceLoadRecord = object;
One resource-load record attributable to a block dispatch (or, for
wave-1/wave-2 loads, to the request's entry block). Trace-only — never
enters the production items stream. Cache-hit runs of the same
(source, storageKey, accessor) are aggregated at record time via count.
Properties
accessor?
accessor?: "get" | "getOptional" | "list" | "count";
For reads through a collection accessor: which method triggered it. Absent for wave preloads (not a read).
cacheHit
cacheHit: boolean;
true = served from the in-memory cache; false = real store fetch.
count
count: number;
Number of identical records collapsed into this one (default 1).
durationMs
durationMs: number;
Wall time of the store round-trip in ms. ~0 for cache hits. Summed across an aggregated run.
scope
scope: "session" | "user" | "org";
source
source: "flow-eager" | "action-eager" | "block-eager" | "lazy";
Which load path produced this record.
storageKey
storageKey: string;
Canonical storage key for a single/instance load, or the prefix
(e.g. "files/") for a collection list/count load.
templateSource?
templateSource?: string;
Raw .md source when this resource's content is template-rendered.
RouterDecisionItem
type RouterDecisionItem = OutputItemBase & object;
Type Declaration
routerName
routerName: string;
selectedRoute
selectedRoute: string;
type
type: "router_decision";
RuntimeItem
type RuntimeItem =
| OutputItem
| BlockTraceItem
| RouterDecisionItem
| StateSnapshotItem
| GeneratorStepItem;
Runtime item union. Public OutputItem is the 10 client-visible types;
runtime buffers, the trace channel, and devtool consumers carry the
additional trace types (block_trace, router_decision, state_snapshot,
and the replay-only generator_step). Use this alias when narrowing items
that may be either kind.
SessionEventBase
type SessionEventBase = object;
Fields every session-stream event carries.
The session stream follows a whole session rather than one request, so its
events have no per-request sequence number. at is where a reconnect picks
up: a client that reconnects hands the last at it heard back as since,
and the server reads from a little before it. Items can arrive twice across
a reconnect; tell them apart by requestId and item.id.
Properties
at
at: number;
Server time (epoch ms) a reconnect can resume from without missing an item this connection had not sent yet: the start of the last read whose items were all sent. Before the first read finishes, the point that read reaches back to (less the server's margin).
sessionId
sessionId: string;
stream
stream: "session";
SessionItemEvent
type SessionItemEvent = SessionEventBase & object;
A finished item a request in the session kept, from any request, including
ones this client did not send. Filtered as the session snapshot filters its
items, so an item a snapshot hides never arrives. Items are told apart by
requestId and item.id together: two requests can keep items with the
same id.
Type Declaration
item
item: OutputItem;
requestId
requestId: string;
type
type: "session.item";
SessionMetadataChangedEvent
type SessionMetadataChangedEvent = RequestEventBase & object;
Type Declaration
description?
description?: string;
metadata?
metadata?: Record<string, unknown>;
sessionId
sessionId: string;
tags?
tags?: string[];
title?
title?: string;
type
type: "session.metadata.changed";
SessionPingEvent
type SessionPingEvent = SessionEventBase & object;
A keep-alive carrying the server's time, sent while nothing else is.
Type Declaration
type
type: "ping";
SessionRun
type SessionRun = object;
One unfinished run under the session, as a session-stream notice names it.
The same fields a background-work listing row carries, less status: every
run a notice names has not finished.
Properties
coordinate?
coordinate?: string;
The entry the run was dispatched for, as <type>:<target>, when recorded.
createdAt
createdAt: number;
flowId?
flowId?: string;
The flow instance the run belongs to, when the run records one.
id
id: string;
The run's own session id.
parentSessionId
parentSessionId: string;
The session the run hangs off: the one the stream follows.
topic?
topic?: string;
The key the run was derived from, when the dispatch recorded one.
updatedAt
updatedAt: number;
SessionRunsChangedEvent
type SessionRunsChangedEvent = SessionEventBase & object;
The session's unfinished runs changed: one started, or one finished. Names every run still unfinished, including ones older than a background-work listing's first page. Sent once when the stream opens, then on each change.
Type Declaration
runs
runs: SessionRun[];
type
type: "session.runs";
SessionStreamEvent
type SessionStreamEvent =
| SessionItemEvent
| SessionRunsChangedEvent
| SessionPingEvent;
Every event the session stream (GET /sessions/:sessionId/stream) sends.
SourceItem
type SourceItem = OutputItemBase & object;
Source reference emitted by provider-native tools (e.g., web search).
Type Declaration
model?
model?: ModelIdentity;
Resolved identity of the generator model that produced this source.
providerMetadata?
providerMetadata?: Record<string, Record<string, unknown>>;
sourceId
sourceId: string;
sourceType
sourceType: "url";
title?
title?: string;
type
type: "source";
url
url: string;
StateChangeItem
type StateChangeItem = InvalidationItem & object;
Type Declaration
blockInstanceId?
blockInstanceId?: string;
operation
operation: "patch" | "set" | "increment" | "push" | "delete_key" | "atomic";
path?
path?: string;
type
type: "state_change";
version
version: number;
StateSnapshotItem
type StateSnapshotItem = OutputItemBase & object;
Full state snapshot emitted at a step boundary for devtool inspection and durable checkpointing.
Sequencers emit one logical snapshot per instance, keyed by key
(the sequencer's blockInstanceId). Subsequent emissions for the same
key are in-place updates, not new entries — clients and the checkpoint
writer dedupe on key.
durable: true— also written tostores.checkpointsso the Phase 2 resume runtime can pick up after an interrupted request.durable: false— stream-only, observability for the devtool.terminal: true— final emission for this sequencer's run (success, error, or cancellation). The durability provider treats terminal frames as adelete(requestId, blockInstanceId)signal so the checkpoint store stays clean once the sequencer completes.
The owning block is identified by provenance.blockName /
provenance.blockInstanceId; no sequencer-specific identity fields are
duplicated here.
Type Declaration
durable
durable: boolean;
When true, also persist this snapshot to stores.checkpoints.
key
key: string;
Stable dedup key — set to the sequencer's blockInstanceId.
state
state: unknown;
stepIndex
stepIndex: number;
stepName
stepName: string;
suspensionId?
suspensionId?: string;
Set when written as a suspension passed through the sequencer: the id of the wait, whose state as it stood there this holds, with the waiting step's writes before it. Absent on step-boundary snapshots.
terminal?
terminal?: boolean;
When true, this is the final emission for the sequencer run; the
durability provider should delete rather than write.
type
type: "state_snapshot";
version
version: number;
Monotonic write counter for this sequencer instance.
StatusItem
type StatusItem = OutputItemBase & object;
Type Declaration
blocked?
blocked?: boolean;
When false, the client may send new actions even though the stream is still open.
detail?
detail?: unknown;
message
message: string;
sideChainTasks?
sideChainTasks?: number;
Number of background work tasks still running.
type
type: "status";
StreamEvent
type StreamEvent = RequestStreamEvent;
Every event a request stream sends.
StructureShape
type StructureShape =
| {
container: "array";
entries: BlockValueInternal<unknown>[];
}
| {
container: "object";
entries: Record<string, BlockValueInternal<unknown>>;
};
Shape of a structure BlockValue: a container of nested BlockValues.
Entries use the internal value type because structures may transitively
contain refs.
SuspensionItem
type SuspensionItem = OutputItemBase & object;
Emitted when a block calls ctx.suspend() in a durable action. Carries
the suspension metadata so clients can render a resume UI. Visibility:
client=true, history=false — a structural item that falls through to
STRUCTURAL_DEFAULT in resolveItemVisibility (client-visible, not in
LLM history). Persisted, so a GET returns it as part of the audit trail.
Type Declaration
allow?
allow?: ResumeAction[];
Resolution actions this suspension permits (e.g. ["submit", "skip"]).
Renderers read it to decide which controls to show — a Skip button appears
iff "skip" is present. Absent on suspensions persisted before this field
existed, which renderers treat as binary ["approve", "reject"].
blockInstanceId?
blockInstanceId?: string;
blockInstanceId of the block that suspended. The item itself is
emitted with runtime provenance, so this carries the suspending block's
identity into the log — the resume runtime recovers the logical path from
here (log-as-source-of-truth) to match the resolving ctx.suspend() call.
data?
data?: Record<string, unknown>;
expiresAt?
expiresAt?: number;
When the suspension stops waiting (ms epoch). Absent when it has no deadline.
kind?
kind?: SuspendForUserKind;
What a user's suspension asks for, when ctx.suspendForUser set it.
Absent on a raw ctx.suspend, and on items written before
it: read it with suspendForUserKindOf, which falls back to the reason.
message
message: string;
reason
reason: SuspensionReason;
render?
render?: object;
render.component
component: string;
render.props?
props?: Record<string, unknown>;
resumeData?
resumeData?: unknown;
resumeSchema?
resumeSchema?: Record<string, unknown>;
suspensionId
suspensionId: string;
suspensionStatus
suspensionStatus: SuspensionStatus;
title?
title?: string;
The suspension's short heading, when it gave one; message is then
its body, and may be markdown. Absent otherwise, and on items written
before it existed: a renderer heads the suspension with message instead.
type
type: "suspension";
SuspensionResumeItem
type SuspensionResumeItem = OutputItemBase & object;
Emitted into the resumed request's log when a suspension is resolved and the
same request continues. The durable audit counterpart to
SuspensionItem: where suspension records the pause, this records the
continuation. Positioned immediately after the suspension item it resolves.
Visibility: client=true, history=false — structural, falling through to
STRUCTURAL_DEFAULT. Non-transient, so a GET returns the full
pause→continue history for one request id.
resumeData is the typed payload the resolver injected (the value
ctx.suspend() returns on continuation). It is client-visible and persisted,
so consumers must not place secrets there.
Type Declaration
resolution
resolution: SuspensionStatus;
How the suspension was resolved. Reuses the suspension status vocabulary.
resolvedAt
resolvedAt: number;
When the suspension was resolved (ms epoch).
resolvedBy?
resolvedBy?: string;
Identity that resolved the suspension (the resume endpoint's resumedBy).
resumeData?
resumeData?: unknown;
The typed payload injected on resume — what ctx.suspend() returns.
suspensionId
suspensionId: string;
The suspension this continuation resolves.
type
type: "suspension_resume";
ToolOutputItem
type ToolOutputItem = OutputItemBase & object;
Tool result emitted when a block executes as a tool within a generator.
Type Declaration
blockName
blockName: string;
cacheAgeMs?
cacheAgeMs?: number;
Age (in milliseconds) of the cached entry at the moment the cache
hit served it. Set only when cached === true.
cached?
cached?: boolean;
True when this tool_output was served from the per-tool memoization
cache rather than executed against the upstream. The cached
value flows through the same envelope so transcripts, replay, and
downstream consumers see one shape regardless of source.
error?
error?: object;
Present when the tool execution failed (status will be "failed").
error.code?
code?: string;
Failure discriminator. Set to "SUSPENSION" when the failed
tool_output was produced by a tool that called ctx.suspend() (a
winning-but-arbitrated-away or losing concurrent suspension) rather than
by an ordinary thrown error. Resume reconstruction uses this to
tell a still-pending/losing suspension apart from a genuine tool failure:
a "SUSPENSION"-coded failure re-enters its gate on resume; any other
failure stays a model-visible error. Otherwise carries the thrown error's
own code when present.
error.details?
details?: Record<string, unknown>;
Open structured payload attached at failure time. Shape matches
BlockTraceItem.error.details so the two items render identically.
error.message
message: string;
model?
model?: ModelIdentity;
Resolved identity of the generator that invoked this tool.
modelOutput?
modelOutput?: unknown;
The model-facing tool result, computed ONCE when the tool settles during
the live run via the tool's mapModelOutput mapper. Present
ONLY when the tool declares a mapper — its presence means "a mapper
produced this value," which lets resume reproduce the live content-envelope
shape exactly (toolResultOutputForModel(output, modelOutput)) rather than
a bare text/json result. Resume reads it back verbatim, so the mapper is
never recomputed on resume (state/code could have drifted across the
suspend window, which would hand the resumed model a different result than
the original step saw). Absent when no mapper is declared, on the legacy
(non-owned-loop) tool path, and on items persisted before this field
existed; readers fall back to output.
output
output: unknown;
outputOmitted?
outputOmitted?: OmittedValue;
Set instead of output and modelOutput when either was over the record
limit or could not be serialized. bytes is the larger of the two. Absent
on every result recorded whole, and on items recorded before the limit
existed.
sourceTask?
sourceTask?: object;
Attribution back to the task whose original tool call populated this cache entry, when the cache hit crossed a task boundary inside a Task Board run. Absent for same-task cache hits and for non-board contexts.
sourceTask.collectionId
collectionId: string;
sourceTask.taskId
taskId: string;
toolCall
toolCall: object;
toolCall.alias?
alias?: string;
Model-facing sanitized alias the LLM saw and called (e.g.
tf_memory_recall). When present, history replay uses this directly
for the toolName field on serialised tool-call / tool-result content
parts — the value is already known to satisfy provider name patterns
(notably OpenAI's ^[a-zA-Z0-9_-]+$). Optional for backward
compatibility with items persisted before this field existed; the
replay path falls back to sanitizeToolName(name) when absent.
toolCall.arguments
arguments: string;
toolCall.callId
callId: string;
toolCall.generatorBlock
generatorBlock: string;
toolCall.name
name: string;
Framework block name (e.g. tf.memory/recall). Used for UI display
and observability. Matches the registered block, including framework
naming conventions like . and /.
toolCall.stepNumber?
stepNumber?: number;
Model step index this call belongs to within the generator's owned tool
loop. Resume replay and canonical collapse key by generator
path + stepNumber + callId, so a provider call id reused across two
steps of one generator run stays distinct. Absent on items persisted
before this field existed and on the legacy (non-owned-loop) .asTool()
path (a single call, no steps); readers treat absence as "unstepped" and
fall back to call-id-only keying.
type
type: "tool_output";
Variables
ITEM_UPDATE_INVARIANT_KEYS
const ITEM_UPDATE_INVARIANT_KEYS: readonly ["id", "type", "provenance", "itemVisibility", "transient"];
Identity-invariant keys that must not be replaced by an item.updated
patch. Producers should not include them; consumers must strip them
defensively before merging.
Functions
attributeItemsToTasks()
function attributeItemsToTasks(items, collectionId): Map<string, OutputItem[]>;
Group the items emitted under each task of collectionId, in stream order.
Every returned item belongs to exactly one task; concurrent siblings and
sequential turns are disjoint by construction. Items with no taskId
(emitted outside any task scope) and substrate records are excluded.
Parameters
items
readonly OutputItem[]
collectionId
string
Returns
Map<string, OutputItem[]>
buildItemLookup()
function buildItemLookup(items): ItemLookup;
Build a lookup closure from a flat items list. Indexes every item by
id (not just block_trace) so refs may resolve to message and
tool_output items as well. Callers with a Map already
indexed by id should wrap that directly.
Parameters
items
readonly OutputItem[] | readonly object[]
Returns
collectAttributedItemIds()
function collectAttributedItemIds(items): Set<string>;
The set of item.id for every item owned by some task, across all
collections. The chat-level <RequestGroupRenderer> uses this to skip items
that belong to a task so they render inside the task's <TaskPlan />
expansion only, not also inline in the thread. Substrate records are
excluded — they mount/group the board, or report on the board's own
bookkeeping, rather than belonging to a task.
Unlike the other two helpers, this does NOT gate on a collection's
task-change task ids: it is collection-agnostic by design (the chat thread
dedups across every board at once), and any item carrying a taskId was
stamped under a real worker scope — which always emits task-change events
for the task — so there is no orphaned-taskId case to guard against.
Parameters
items
readonly OutputItem[]
Returns
Set<string>
compareItemOrder()
function compareItemOrder(a, b): number;
Compare two items for display order: ts, then itemIndex, then
requestId, then id. Total, so no two distinct items compare equal and
the order never depends on arrival or on how a store lists requests.
Strings compare by code unit, not locale, so every runtime agrees.
Parameters
a
b
Returns
number
inlineBlockValue()
function inlineBlockValue<T>(value): BlockValue<T>;
Construct an inline BlockValue carrying novel content.
Type Parameters
T
T
Parameters
value
T
Returns
BlockValue<T>
isBlockValue()
function isBlockValue(candidate): candidate is BlockValue;
Runtime type guard. Useful for incremental migrations and defensive reads
at boundaries where an older raw value might sneak in — callers should
treat a non-BlockValue as an inline with that value.
Parameters
candidate
unknown
Returns
candidate is BlockValue
isEphemeralContent()
function isEphemeralContent(content): boolean;
Returns true if a content part should not be persisted to the store.
Parameters
content
Returns
boolean
isSuspensionItem()
function isSuspensionItem(item): item is SuspensionItem;
True when item is a suspension item (type === "suspension").
Use to narrow OutputItem to SuspensionItem without string-matching item.type.
Parameters
item
Returns
item is SuspensionItem
isSuspensionResumeItem()
function isSuspensionResumeItem(item): item is SuspensionResumeItem;
True when item is a suspension resume item (type === "suspension_resume").
Use to narrow OutputItem to SuspensionResumeItem without string-matching item.type.
Parameters
item
Returns
item is SuspensionResumeItem
isSuspensionWait()
function isSuspensionWait(item): boolean;
True when item is a tool call waiting on an approval or a question, not a
failed one. A tool that calls ctx.suspend() is recorded as a failed
tool_output whose error.code is "SUSPENSION", with the suspension's message as
its error; its real result replaces it once the answer resumes the run.
Renderers use this to draw the wait as waiting rather than as an error.
Parameters
item
error?
{
code?: string;
}
error.code?
string
status?
string
type
string
Returns
boolean
itemsForTask()
function itemsForTask(
items,
collectionId,
taskId
): readonly OutputItem[];
Items emitted under (collectionId, taskId), in stream order. Returns []
when the task has no task-change events in the log (never claimed).
Unions all attempts of a re-claimed task — the second claim emits items
stamped with the same taskId.
Parameters
items
readonly OutputItem[]
collectionId
string
taskId
string
Returns
readonly OutputItem[]
resolveBlockValue()
function resolveBlockValue<T>(value, lookup): T | undefined;
Resolve a BlockValue to its typed payload T.
inline→ returnsvaluedirectly.ref→ looks up the target item:block_trace→ recurse into its own BlockValue.message→ returns the joinedoutput_textcontent cast toT(streaming-text generators emit refs to their own message).tool_output→ returns itsoutput(a block run as a tool, or an.asTool()step, refs the tool result it recorded). Returnsundefinedif the target is missing (e.g., evicted).
structure→ deep-resolves each entry, reconstructing the container.omitted→undefined: the record left the value out.
Safe against cycles because the executor guarantees flatten-at-emit: a ref never points at another ref. We still bail on a second ref hop defensively.
Type Parameters
T
T = unknown
Parameters
value
BlockValue<unknown> | undefined
lookup
Returns
T | undefined
resolveItemVisibility()
function resolveItemVisibility(item): ItemVisibility;
Parameters
item
Returns
structureBlockValue()
function structureBlockValue<T>(shape): BlockValue<T>;
Construct a structure BlockValue describing a container of nested BlockValues.
Type Parameters
T
T
Parameters
shape
Returns
BlockValue<T>
References
collapseToCanonicalLog
Re-exports collapseToCanonicalLog
ItemVisibility
Re-exports ItemVisibility
ModelIdentity
Re-exports ModelIdentity
RequestStatus
Re-exports RequestStatus
whenAnyItem
Re-exports whenAnyItem
whenResourceChanged
Re-exports whenResourceChanged
whenResourceMatching
Re-exports whenResourceMatching