@flow-state-dev/client
Classes
ClientHttpError
The one error type a client throws. status is the server's HTTP status,
or 0 when the client refused before sending anything (a missing id, a
request with no session to continue, a wait that timed out). body is
the server's parsed answer, or { error } for a status-0 refusal.
Extends
Error
Constructors
Constructor
new ClientHttpError(message, options): ClientHttpError;
Parameters
message
string
options
body
unknown
status
number
Returns
Overrides
Error.constructor
Properties
body
readonly body: unknown;
cause?
cause?: unknown;
Inherited from
Error.cause
message
message: string;
Inherited from
Error.message
name
name: string;
Inherited from
Error.name
stack?
stack?: string;
Inherited from
Error.stack
status
readonly status: number;
CollectionReadStoppedError
Thrown when a read stops before the collection ran out of pages: the
ceiling was reached with a nextCursor still outstanding, or the server
handed back a cursor it had already sent. Either way the rows read so far
are not the whole collection, so none are returned.
Extends
Error
Constructors
Constructor
new CollectionReadStoppedError(
reason,
pagesRead,
rowsRead
): CollectionReadStoppedError;
Parameters
reason
pagesRead
number
rowsRead
number
Returns
Overrides
Error.constructor
Properties
cause?
cause?: unknown;
Inherited from
Error.cause
message
message: string;
Inherited from
Error.message
name
name: string;
Inherited from
Error.name
pagesRead
readonly pagesRead: number;
Pages fully read before the stop.
reason
readonly reason: CollectionReadStopReason;
Which guard stopped the read.
rowsRead
readonly rowsRead: number;
Rows those pages held.
stack?
stack?: string;
Inherited from
Error.stack
ResourceWriteError
Why a write was refused: code is the server's (stale_version, write_refused, not_writable, ...).
Extends
Error
Constructors
Constructor
new ResourceWriteError(code, message): ResourceWriteError;
Parameters
code
string
message
string
Returns
Overrides
Error.constructor
Properties
cause?
cause?: unknown;
Inherited from
Error.cause
code
readonly code: string;
message
message: string;
Inherited from
Error.message
name
name: string;
Inherited from
Error.name
stack?
stack?: string;
Inherited from
Error.stack
Interfaces
Client
The one client.
Properties
debug
debug: object;
Privileged host-wide reads for the DevTool. The server must opt in
(debugEndpointsEnabled / FSDEV_DEBUG_ENDPOINTS=1); otherwise 403.
storage()
storage(): Promise<DebugStorageResponse>;
How much space the host's store takes, or storage: null when it can't measure itself.
Returns
Promise<DebugStorageResponse>
requests
requests: object;
interrupted()
interrupted(options?): Promise<InterruptedRequest[]>;
The user's interrupted requests: a request a host lost in a crash or a
restart. Asks the server to sweep stale ones first, then reads every
interrupted record, so a request an earlier sweep marked is listed too,
on every call, until it is continued or removed.
staleThresholdMs can only widen the server's own threshold.
Parameters
options?
staleThresholdMs?
number
Returns
Promise<InterruptedRequest[]>
resources
resources: ResourcesApi;
sessions
sessions: SessionsApi;
userId
readonly userId: string;
The user every call acts as.
Methods
capabilities()
capabilities(): Promise<FlowCapabilities>;
What the server supports.
Returns
Promise<FlowCapabilities>
flow()
flow<TFlow>(address): FlowHandle<TFlow>;
One flow, by address: a singleton flow's kind, or a collection
instance's id. Pass typeof myFlow (a type import) to type-check
send's action name and input.
Type Parameters
TFlow
TFlow extends TypedFlow = UntypedFlow
Parameters
address
string
Returns
FlowHandle<TFlow>
flows()
flows(): Promise<FlowListEntry[]>;
The flows the server hosts.
Returns
Promise<FlowListEntry[]>
live()
Call Signature
live<T>(topics, options): LiveRead;
A live read: keep a screen current on what subscribe hears. Reads now,
and again on each notice under topics that hear and paths let
through, with one read in flight and at most one waiting; reports a value
only when it changed. A failed read tries again on its own (1 s doubling
to 30 s) and onStale says the screen is stale until one lands. Reads on
a timer (3 s by default) wherever push can miss a change. With
topicsFromResult, each read also returns the topics to hear next.
Type Parameters
T
T
Parameters
topics
readonly WireTopic[]
options
Returns
Call Signature
live<T>(topics, options): LiveRead;
Type Parameters
T
T
Parameters
topics
readonly WireTopic[]
options
Returns
resource()
resource<TDef>(def, options?): ScopeHandleOf<TDef>;
One user or org resource or collection, by its definition: read by scope
and key with no session, and written through the flow its runBy names. A
collection's handle reads and writes its entries one at a time. Its key is
the definition's ref (a collection's pattern), or options.key. Reads
nothing until a method is called.
Type Parameters
TDef
TDef extends ScopeResourceDef
Parameters
def
TDef
options?
key?
string
Returns
ScopeHandleOf<TDef>
subscribe()
subscribe(topics, options): Subscription;
Hear that something under topics changed, and read again in
onChange. A notice says when, never what: onChange gets the notice
(or null for a connect, a reconnect or a timer tick) and makes the read
the screen already makes. One socket per client, minted through this
client's fetcher, on a host with push; pollIntervalMs reads on a timer
wherever push can miss a change. Build topics with topic.session(id),
topic.user() and topic.org().
Parameters
topics
readonly WireTopic[]
options
Returns
transcribe()
transcribe(request): Promise<TranscribeResponse>;
Transcribe audio on the server.
Parameters
request
Returns
Promise<TranscribeResponse>
upload()
upload(request): Promise<FileContent>;
Upload one file to attach, once. Resolves to the file in reference form
(data is fsd-blob:<id>), held for this user until a message that
names it is sent. Send that, never the bytes.
Parameters
request
Returns
Promise<FileContent>
view()
view<TRef>(
ref,
input?,
options?
): Promise<ViewResult<ViewValueOf<TRef>>>;
Run a view once, as the client's user, and resolve to its value, the
change topics of what its run read, and a keyed view's row keys. A user
or org view needs no session; a session view takes sessionId. Nothing
is stored. To keep a screen current, watch it (useView in React).
Rejects with a ClientHttpError: 404 for an unknown view or a session
the user can't run in, 400 for input its schema refuses or a view called
at the wrong scope, 422 for a view that called a model or reached for a
session it doesn't have.
Type Parameters
TRef
TRef extends ViewRef
Parameters
ref
TRef
input?
ViewInputOf<TRef>
options?
Returns
Promise<ViewResult<ViewValueOf<TRef>>>
FlowHandle
One flow's actions and requests. Typed by flow<typeof myFlow>(…).
Type Parameters
TFlow
TFlow extends TypedFlow = UntypedFlow
Properties
address
readonly address: string;
The address every route of this handle takes.
Methods
createSession()
createSession(options?): Promise<SessionDetail>;
Start a session on this flow, as the client's user.
Parameters
options?
Returns
Promise<SessionDetail>
identity()
identity(): Promise<{
orgId: string;
userId: string;
}>;
The user and org the server acts as for this client under this flow's sign-in, with no session. On a host with no sign-in, the client's user and the default org.
Returns
Promise<{
orgId: string;
userId: string;
}>
request()
request(id): RequestHandle;
A request of this flow, by id. Reads nothing until a method is called.
Parameters
id
string
Returns
send()
Call Signature
send<TAction>(
action,
input,
options
): Promise<SentRequest>;
Run an action. Resolves to the request it started.
Type Parameters
TAction
TAction extends string
Parameters
action
TAction
input
ActionInputOf<TFlow, TAction>
options
Returns
Promise<SentRequest>
Call Signature
send<TAction>(
action,
input,
options
): Promise<Response>;
Type Parameters
TAction
TAction extends string
Parameters
action
TAction
input
ActionInputOf<TFlow, TAction>
options
Returns
Promise<Response>
upload()
upload(request): Promise<FileContent>;
Upload one file to attach to this flow's messages, checked by this flow's
own sign-in, so the file is held for the user its sends resolve. Use this
when the flow authenticates its own callers; otherwise client.upload is
the same.
Parameters
request
Returns
Promise<FileContent>
HarnessLines
One sender's lines, in the order they were typed. See harnessLines.
Type Parameters
TOutcome
TOutcome extends string = HarnessLineOutcome
Methods
send()
send(
prompt,
running,
sender
): Promise<TOutcome>;
Send one line after every line sent before it has its answer.
Parameters
prompt
string
running
boolean
Whether a turn is running now, as the page sees it.
sender
Returns
Promise<TOutcome>
turnChanged()
turnChanged(): void;
Call when the running turn changes or ends: lines may steer the new one.
Returns
void
HarnessLineSender
How a line is sent: the session flow's two actions.
Methods
steer()
steer(prompt): Promise<{
live: boolean;
taken: boolean;
}>;
Hands the line to the running turn. live: the turn offered to take one; taken: it did.
Parameters
prompt
string
Returns
Promise<{
live: boolean;
taken: boolean;
}>
turn()
turn(prompt): Promise<void>;
Sends the line as a turn, which waits for one already running.
Parameters
prompt
string
Returns
Promise<void>
InterruptedBySessionOptions
Options for interruptedBySession.
Properties
actions
readonly actions: readonly string[];
The actions that are the app's turns, e.g. ["respond"]. A request of any
other action (a worker's internal pass, a delivery) is left out, so it
badges nothing.
InterruptedRequest
An interrupted request, as Client.requests.interrupted() lists it.
Extends
Properties
actionName
readonly actionName: string;
flow
readonly flow: string;
The flow address its routes take: a singleton's kind, or an instance's id.
Inherited from
flowKind
readonly flowKind: string;
id
readonly id: string;
The request's id.
Inherited from
interruptedAt
readonly interruptedAt: number;
When it was marked interrupted, in ms since epoch.
sessionId?
readonly sessionId?: string;
Methods
abort()
abort(): Promise<void>;
Ask the server to stop it. A finished request answers 409.
Returns
Promise<void>
Inherited from
answer()
Call Signature
answer(body): Promise<RequestHandle>;
Answer a suspension of this request that waits for a user
(ctx.suspendForUser, or a raw user_approval / user_input stop),
whatever started its run, a task's included, which resume refuses.
The server checks the caller owns the request before it reads the stop,
resolves it once, and continues the same request; this resolves to its
handle. Rejects with a ClientHttpError: 404 for a stop that is not the
caller's or not a user's, 409 for one already resolved (an answer, a
cancel, a deadline or a stop got there first), 410 past its deadline,
400 for an answer that fails the stop's schema. With { stream: true }
it resolves to the route's SSE Response instead, so the continuation
streams from the POST itself, as resume and continue do.
Parameters
body
Returns
Promise<RequestHandle>
Inherited from
Call Signature
answer(body, options): Promise<Response>;
Parameters
body
options
Returns
Promise<Response>
Inherited from
continue()
Call Signature
continue(): Promise<RequestHandle>;
Carry on a crash-interrupted request under its own id: completed blocks replay from the durable log and the one in flight runs again. Resolves to this handle. Needs the request's session; a request with none rejects before any call.
Returns
Promise<RequestHandle>
Inherited from
Call Signature
continue(options): Promise<Response>;
Parameters
options
StreamOption & object
Returns
Promise<Response>
Inherited from
result()
result(options?): Promise<RequestResult>;
What the request answered: wait()'s polls of this request by its id,
each asking for its stored result, and the read that finds it settled is
the one returned. Resolves for every way a request settles
and says which, so branch on status: output is the action's return
value on completed or incomplete, error says why on failed, and a
run that stops for a person resolves suspended with neither. Rejects
only as wait() does: past timeoutMs, on a transport error, or when
signal aborts, which never stops the run.
Parameters
options?
Returns
Promise<RequestResult>
Inherited from
resume()
Call Signature
resume(body): Promise<RequestHandle>;
Answer a pending suspension of this request. The run carries on under the same request id; this resolves to its handle.
Parameters
body
Returns
Promise<RequestHandle>
Inherited from
Call Signature
resume(body, options): Promise<Response>;
Parameters
body
options
Returns
Promise<Response>
Inherited from
retry()
retry(options?): Promise<RequestHandle>;
Run the request again as a new request in the same session, with its
original input or input. Resolves to the new request.
Parameters
options?
input?
unknown
Returns
Promise<RequestHandle>
Inherited from
status()
status(): Promise<RequestStatusSnapshot>;
Its lifecycle state now.
Returns
Promise<RequestStatusSnapshot>
Inherited from
stream()
stream(options): RequestStreamHandle;
Follow the request's events. When the server ends the stream before the
request ends (it cuts off a reader that falls too far behind), the stream
resumes after the last event it delivered; after five connections in a
row that deliver nothing it gives up with onError.
Parameters
options
Returns
Inherited from
wait()
wait(options?): Promise<RequestStatusSnapshot>;
Resolves with the status once the request has settled: it is not
in_progress and the server holds no live run of it, so a request just
continued or resumed is waited for rather than read back as it was. A run
that stops for a person settles at suspended. Reads every pollMs
(default 250); past timeoutMs (default: never) it rejects with a
ClientHttpError of status 0. When signal aborts it rejects with the
signal's reason; the run carries on.
Parameters
options?
Returns
Promise<RequestStatusSnapshot>
Inherited from
RequestHandle
One request, found by a send, by id, or in the interrupted list. Its lifecycle lives on it, with the flow and session its routes need.
Extended by
Properties
flow
readonly flow: string;
The flow address its routes take: a singleton's kind, or an instance's id.
id
readonly id: string;
The request's id.
Methods
abort()
abort(): Promise<void>;
Ask the server to stop it. A finished request answers 409.
Returns
Promise<void>
answer()
Call Signature
answer(body): Promise<RequestHandle>;
Answer a suspension of this request that waits for a user
(ctx.suspendForUser, or a raw user_approval / user_input stop),
whatever started its run, a task's included, which resume refuses.
The server checks the caller owns the request before it reads the stop,
resolves it once, and continues the same request; this resolves to its
handle. Rejects with a ClientHttpError: 404 for a stop that is not the
caller's or not a user's, 409 for one already resolved (an answer, a
cancel, a deadline or a stop got there first), 410 past its deadline,
400 for an answer that fails the stop's schema. With { stream: true }
it resolves to the route's SSE Response instead, so the continuation
streams from the POST itself, as resume and continue do.
Parameters
body
Returns
Promise<RequestHandle>
Call Signature
answer(body, options): Promise<Response>;
Parameters
body
options
Returns
Promise<Response>
continue()
Call Signature
continue(): Promise<RequestHandle>;
Carry on a crash-interrupted request under its own id: completed blocks replay from the durable log and the one in flight runs again. Resolves to this handle. Needs the request's session; a request with none rejects before any call.
Returns
Promise<RequestHandle>
Call Signature
continue(options): Promise<Response>;
Parameters
options
StreamOption & object
Returns
Promise<Response>
result()
result(options?): Promise<RequestResult>;
What the request answered: wait()'s polls of this request by its id,
each asking for its stored result, and the read that finds it settled is
the one returned. Resolves for every way a request settles
and says which, so branch on status: output is the action's return
value on completed or incomplete, error says why on failed, and a
run that stops for a person resolves suspended with neither. Rejects
only as wait() does: past timeoutMs, on a transport error, or when
signal aborts, which never stops the run.
Parameters
options?
Returns
Promise<RequestResult>
resume()
Call Signature
resume(body): Promise<RequestHandle>;
Answer a pending suspension of this request. The run carries on under the same request id; this resolves to its handle.
Parameters
body
Returns
Promise<RequestHandle>
Call Signature
resume(body, options): Promise<Response>;
Parameters
body
options
Returns
Promise<Response>
retry()
retry(options?): Promise<RequestHandle>;
Run the request again as a new request in the same session, with its
original input or input. Resolves to the new request.
Parameters
options?
input?
unknown
Returns
Promise<RequestHandle>
status()
status(): Promise<RequestStatusSnapshot>;
Its lifecycle state now.
Returns
Promise<RequestStatusSnapshot>
stream()
stream(options): RequestStreamHandle;
Follow the request's events. When the server ends the stream before the
request ends (it cuts off a reader that falls too far behind), the stream
resumes after the last event it delivered; after five connections in a
row that deliver nothing it gives up with onError.
Parameters
options
Returns
wait()
wait(options?): Promise<RequestStatusSnapshot>;
Resolves with the status once the request has settled: it is not
in_progress and the server holds no live run of it, so a request just
continued or resumed is waited for rather than read back as it was. A run
that stops for a person settles at suspended. Reads every pollMs
(default 250); past timeoutMs (default: never) it rejects with a
ClientHttpError of status 0. When signal aborts it rejects with the
signal's reason; the run carries on.
Parameters
options?
Returns
Promise<RequestStatusSnapshot>
RequestStreamHandle
Handle returned by request-stream SSE connections.
Properties
lastEventId?
readonly lastEventId?: string;
Methods
close()
close(): void;
Returns
void
ResourcesApi
A session's resources.
Methods
createCollectionResource()
createCollectionResource(
sessionId,
ref,
options
): Promise<{
topic: string;
}>;
Parameters
sessionId
string
ref
string
options
CreateCollectionResourceOptions
Returns
Promise<{
topic: string;
}>
deleteCollectionResource()
deleteCollectionResource(
sessionId,
ref,
topic
): Promise<void>;
Parameters
sessionId
string
ref
string
topic
string
Returns
Promise<void>
getCollectionResourceContent()
getCollectionResourceContent(
sessionId,
ref,
topic
): Promise<ResourceContentResponse>;
Parameters
sessionId
string
ref
string
topic
string
Returns
Promise<ResourceContentResponse>
getCollectionResourceState()
getCollectionResourceState(
sessionId,
ref,
topic
): Promise<CollectionResourceState | null>;
One item's state, or null when the topic is absent.
Parameters
sessionId
string
ref
string
topic
string
Returns
Promise<CollectionResourceState | null>
getResourceContent()
getResourceContent(sessionId, ref): Promise<ResourceContentResponse>;
Parameters
sessionId
string
ref
string
Returns
Promise<ResourceContentResponse>
getResourceManifest()
getResourceManifest(sessionId): Promise<ResourceManifest>;
The public resources a session's flow declares. Deterministic per flow kind.
Parameters
sessionId
string
Returns
Promise<ResourceManifest>
listCollectionResources()
listCollectionResources(
sessionId,
ref,
options?
): Promise<CollectionListPage>;
One page of a collection; pass nextCursor back as cursor for the next.
Parameters
sessionId
string
ref
string
options?
ListCollectionResourcesOptions
Returns
Promise<CollectionListPage>
updateResourceContent()
updateResourceContent(
sessionId,
ref,
topic,
options
): Promise<void>;
Parameters
sessionId
string
ref
string
topic
string
options
Returns
Promise<void>
ScopeCollectionHandle
One user or org collection, by scope and pattern.
Extends
ResourceSends
Type Parameters
TValue
TValue = JsonValue
Properties
key
readonly key: string;
scope
readonly scope: "user" | "org";
Methods
entry()
entry(entry): ScopeEntryHandle<TValue>;
One entry, by its topic or storage key. Reads nothing until a method is called.
Parameters
entry
string
Returns
ScopeEntryHandle<TValue>
list()
Call Signature
list(options): Promise<CollectionManifestPage>;
One page of the caller's entries. In storage-key order, or (order: "newest")
newest first by each entry's at. manifest returns storage keys and
versions and no values, on the same route, in storage-key order.
Parameters
options
cursor?
string
limit?
number
manifest
true
topicPrefix?
string
Returns
Promise<CollectionManifestPage>
Call Signature
list(options?): Promise<ScopeEntryPage<TValue>>;
Parameters
options?
cursor?
string
limit?
number
order?
"newest"
topicPrefix?
string
Returns
Promise<ScopeEntryPage<TValue>>
listAll()
listAll(options?): Promise<ScopeEntry<TValue>[]>;
Every one of the caller's entries, page after page to the last. Rejects
with CollectionReadStoppedError, returning none, when the server hands
back a cursor it already sent or keeps paging past 1,000 pages.
Parameters
options?
limit?
number
topicPrefix?
string
Returns
Promise<ScopeEntry<TValue>[]>
send()
send<TOutput>(action, input): Promise<TOutput>;
Run action with input in the caller's write session; resolves to its output.
Type Parameters
TOutput
TOutput = unknown
Parameters
action
string
input
unknown
Returns
Promise<TOutput>
Inherited from
ResourceSends.send
ScopeEntryHandle
One entry of a collection, by its topic or storage key.
Extends
VersionedWrites<TValue,TValue|null>
Type Parameters
TValue
TValue = JsonValue
Properties
entry
readonly entry: string;
Methods
delete()
delete(options?): Promise<{
version: number;
}>;
Delete the entry at version when given, else at the version read just before. Rejects with stale_version when another write landed first.
Parameters
options?
version?
number
Returns
Promise<{
version: number;
}>
read()
read(): Promise<ScopeResourceRead<TValue | null>>;
The entry's value and version: null at version 0 when it is absent, or not the caller's to read.
Returns
Promise<ScopeResourceRead<TValue | null>>
set()
set(value, options?): Promise<{
version: number;
}>;
Store value (the fields the client can see), at version when given, else
at the version read just before. Rejects with stale_version when another
write landed first. Resolves to the new version.
Parameters
value
TValue
options?
version?
number
Returns
Promise<{
version: number;
}>
Inherited from
VersionedWrites.set
update()
update(updater): Promise<{
version: number;
}>;
Read, apply updater, write at the version read; on a stale version, read
again and re-apply, three times at most. Resolves to the new version.
Parameters
updater
(value) => TValue
Returns
Promise<{
version: number;
}>
Inherited from
VersionedWrites.update
ScopeResourceHandle
One user or org resource, by scope and key.
Extends
VersionedWrites<TValue,TValue>ResourceSends
Type Parameters
TValue
TValue = JsonValue
Properties
key
readonly key: string;
scope
readonly scope: "user" | "org";
Methods
read()
read(): Promise<ScopeResourceRead<TValue>>;
The value and its version. The value is the schema's default before any write.
Returns
Promise<ScopeResourceRead<TValue>>
send()
send<TOutput>(action, input): Promise<TOutput>;
Run action with input in the caller's write session; resolves to its output.
Type Parameters
TOutput
TOutput = unknown
Parameters
action
string
input
unknown
Returns
Promise<TOutput>
Inherited from
ResourceSends.send
set()
set(value, options?): Promise<{
version: number;
}>;
Store value (the fields the client can see), at version when given, else
at the version read just before. Rejects with stale_version when another
write landed first. Resolves to the new version.
Parameters
value
TValue
options?
version?
number
Returns
Promise<{
version: number;
}>
Inherited from
VersionedWrites.set
state()
state(): Promise<TValue>;
The value alone.
Returns
Promise<TValue>
update()
update(updater): Promise<{
version: number;
}>;
Read, apply updater, write at the version read; on a stale version, read
again and re-apply, three times at most. Resolves to the new version.
Parameters
updater
(value) => TValue
Returns
Promise<{
version: number;
}>
Inherited from
VersionedWrites.update
SentRequest
A request a send started, with the server's answer to the send.
Extends
Properties
flow
readonly flow: string;
The flow address its routes take: a singleton's kind, or an instance's id.
Inherited from
id
readonly id: string;
The request's id.
Inherited from
response
readonly response: ExecuteActionResponse;
The server's answer to the send: status, request and session.
Methods
abort()
abort(): Promise<void>;
Ask the server to stop it. A finished request answers 409.
Returns
Promise<void>
Inherited from
answer()
Call Signature
answer(body): Promise<RequestHandle>;
Answer a suspension of this request that waits for a user
(ctx.suspendForUser, or a raw user_approval / user_input stop),
whatever started its run, a task's included, which resume refuses.
The server checks the caller owns the request before it reads the stop,
resolves it once, and continues the same request; this resolves to its
handle. Rejects with a ClientHttpError: 404 for a stop that is not the
caller's or not a user's, 409 for one already resolved (an answer, a
cancel, a deadline or a stop got there first), 410 past its deadline,
400 for an answer that fails the stop's schema. With { stream: true }
it resolves to the route's SSE Response instead, so the continuation
streams from the POST itself, as resume and continue do.
Parameters
body
Returns
Promise<RequestHandle>
Inherited from
Call Signature
answer(body, options): Promise<Response>;
Parameters
body
options
Returns
Promise<Response>
Inherited from
continue()
Call Signature
continue(): Promise<RequestHandle>;
Carry on a crash-interrupted request under its own id: completed blocks replay from the durable log and the one in flight runs again. Resolves to this handle. Needs the request's session; a request with none rejects before any call.
Returns
Promise<RequestHandle>
Inherited from
Call Signature
continue(options): Promise<Response>;
Parameters
options
StreamOption & object
Returns
Promise<Response>
Inherited from
result()
result(options?): Promise<RequestResult>;
What the request answered: wait()'s polls of this request by its id,
each asking for its stored result, and the read that finds it settled is
the one returned. Resolves for every way a request settles
and says which, so branch on status: output is the action's return
value on completed or incomplete, error says why on failed, and a
run that stops for a person resolves suspended with neither. Rejects
only as wait() does: past timeoutMs, on a transport error, or when
signal aborts, which never stops the run.
Parameters
options?
Returns
Promise<RequestResult>
Inherited from
resume()
Call Signature
resume(body): Promise<RequestHandle>;
Answer a pending suspension of this request. The run carries on under the same request id; this resolves to its handle.
Parameters
body
Returns
Promise<RequestHandle>
Inherited from
Call Signature
resume(body, options): Promise<Response>;
Parameters
body
options
Returns
Promise<Response>
Inherited from
retry()
retry(options?): Promise<RequestHandle>;
Run the request again as a new request in the same session, with its
original input or input. Resolves to the new request.
Parameters
options?
input?
unknown
Returns
Promise<RequestHandle>
Inherited from
status()
status(): Promise<RequestStatusSnapshot>;
Its lifecycle state now.
Returns
Promise<RequestStatusSnapshot>
Inherited from
stream()
stream(options): RequestStreamHandle;
Follow the request's events. When the server ends the stream before the
request ends (it cuts off a reader that falls too far behind), the stream
resumes after the last event it delivered; after five connections in a
row that deliver nothing it gives up with onError.
Parameters
options
Returns
Inherited from
wait()
wait(options?): Promise<RequestStatusSnapshot>;
Resolves with the status once the request has settled: it is not
in_progress and the server holds no live run of it, so a request just
continued or resumed is waited for rather than read back as it was. A run
that stops for a person settles at suspended. Reads every pollMs
(default 250); past timeoutMs (default: never) it rejects with a
ClientHttpError of status 0. When signal aborts it rejects with the
signal's reason; the run carries on.
Parameters
options?
Returns
Promise<RequestStatusSnapshot>
Inherited from
SessionFeed
Methods
close()
close(): void;
Stop following: closes the stream and every followed response. The state becomes stopped.
Returns
void
followResponse()
followResponse(response): void;
Keep a send's streamed response (send(..., { stream: true })'s
Response): its items as they are written, until the request ends. The
session stream carries the finished copies from there.
Parameters
response
Response
Returns
void
getSnapshot()
getSnapshot(): SessionFeedSnapshot;
What the feed shows now. The same object until something changes.
Returns
loadEarlier()
loadEarlier(): Promise<void>;
Add the page of history before items[0] (up to 200 items), and say
whether there is more (hasEarlier). Live items keep arriving meanwhile.
Resolves at once when there is nothing earlier, before the history read
lands, or once the feed is closed; a call while one is reading shares it.
Rejects when the read fails, and leaves the feed as it was.
Returns
Promise<void>
subscribe()
subscribe(listener): () => void;
Called on every change. Returns what stops it.
Parameters
listener
(snapshot) => void
Returns
() => void
SessionsApi
The user's sessions.
Properties
debug
debug: object;
Privileged reads for the DevTool. The server must opt in
(debugEndpointsEnabled / FSDEV_DEBUG_ENDPOINTS=1); otherwise 403.
fetchCollectionResourceContent()
fetchCollectionResourceContent(
sessionId,
ref,
topic
): Promise<string>;
Parameters
sessionId
string
ref
string
topic
string
Returns
Promise<string>
fetchResourceContent()
fetchResourceContent(sessionId, ref): Promise<string>;
Parameters
sessionId
string
ref
string
Returns
Promise<string>
listCollectionResources()
listCollectionResources(
sessionId,
ref,
options?
): Promise<DebugCollectionResourcesResponse>;
Parameters
sessionId
string
ref
string
options?
ListDebugCollectionResourcesOptions
Returns
Promise<DebugCollectionResourcesResponse>
listResources()
listResources(sessionId): Promise<DebugResourcesResponse>;
Parameters
sessionId
string
Returns
Promise<DebugResourcesResponse>
listSuspensions()
listSuspensions(sessionId, options?): Promise<DebugSuspensionsResponse>;
Parameters
sessionId
string
options?
Returns
Promise<DebugSuspensionsResponse>
Methods
children()
children(parentSessionId, options?): Promise<ChildSessionSummary[]>;
The background work running under one conversation. Each row carries the
state its work reached; requests(row.id) shows what it has done. A
conversation with none returns an empty list.
Parameters
parentSessionId
string
options?
Returns
Promise<ChildSessionSummary[]>
delete()
delete(sessionId): Promise<void>;
Parameters
sessionId
string
Returns
Promise<void>
get()
get(sessionId): Promise<SessionDetail>;
Parameters
sessionId
string
Returns
Promise<SessionDetail>
list()
list(options?): Promise<SessionSummary[]>;
Sessions, newest first. Default: the client's own user's (ListSessionsOptions.userId).
Parameters
options?
Returns
Promise<SessionSummary[]>
requests()
requests(sessionId, options?): Promise<SessionRequestSummary[]>;
The requests run in one session.
Parameters
sessionId
string
options?
Returns
Promise<SessionRequestSummary[]>
state()
state(sessionId, options?): Promise<SessionStateSnapshotResponse>;
The session's state snapshot.
Parameters
sessionId
string
options?
Returns
Promise<SessionStateSnapshotResponse>
stream()
stream(sessionId, options?): SessionStreamHandle;
Follow a whole session: every finished item any request in it keeps, and
a notice whenever its unfinished runs change. Reconnects with backoff; a
401, 403, 404, 409 or 501 stops it for good (onStop).
Parameters
sessionId
string
options?
Returns
updateMetadata()
updateMetadata(sessionId, options): Promise<SessionDetail>;
Parameters
sessionId
string
options
Returns
Promise<SessionDetail>
SessionStreamHandle
Handle returned by a session-stream connection.
Properties
lastAt?
readonly lastAt?: number;
The server time of the last event heard, handed back as since on a reconnect.
stopped
readonly stopped: boolean;
True once the client stopped for good: closed, or refused by the server.
Methods
close()
close(): void;
Stop following the session: closes the connection and any pending reconnect.
Returns
void
SteerRunningTurnOptions
Options for steerRunningTurn.
Properties
action?
readonly action?: string;
The flow's steer action. Default "steer".
flowKind
readonly flowKind: string;
pollMs?
readonly pollMs?: number;
How often to poll the request while it runs. Default 150 ms.
prompt
readonly prompt: string;
sessionId
readonly sessionId: string;
SuspensionRecord
Properties
actionName
actionName: string;
allow?
allow?: ResumeAction[];
The resolution actions this suspension permits. The resume route rejects an
inbound action outside this set (409), and renderers read it to decide which
controls to show (e.g. a Skip button appears iff "skip" is present). When
absent — including on records persisted before this field existed — the
suspension is treated as binary ["approve", "reject"] for back-compat.
blockInstanceId
blockInstanceId: string;
createdAt
createdAt: number;
data?
data?: Record<string, unknown>;
expiresAt?
expiresAt?: number;
flowId?
flowId?: string;
The flow instance that owns the suspended run — the address a resume must
re-enter it through. Two copies of one kind suspend independently, so the
kind alone does not say which one is waiting. Absent on a record persisted
before owners were recorded; guard with == null, falling back to
flowKind, which is the correct address for a singleton and the only one
such a record ever had.
flowKind
flowKind: string;
kind?
kind?: SuspendForUserKind;
What a user's suspension asks for, when ctx.suspendForUser set it.
Absent on a raw ctx.suspend and on every other
suspension: read it with suspendForUserKindOf, which falls back to the
reason.
message
message: string;
reason
reason: SuspensionReason;
render?
render?: object;
component
component: string;
props?
props?: Record<string, unknown>;
requestId
requestId: string;
resolvedAt?
resolvedAt?: number;
resolvedBy?
resolvedBy?: string;
resumeData?
resumeData?: unknown;
resumeSchema?
resumeSchema?: Record<string, unknown>;
JSON Schema describing the expected resume payload shape. Generated from the Zod schema passed to ctx.suspend({ resumeSchema }). Stored as JSON Schema (not a Zod instance) so suspension records are serializable across processes.
sessionId?
sessionId?: string;
status
status: SuspensionStatus;
stepIndex
stepIndex: number;
stepInput?
stepInput?: unknown;
The input value that was about to be passed to the step that suspended.
suspensionId
suspensionId: string;
title?
title?: string;
The suspension's short heading; message is then its body. Absent when the
suspension gave none, including every record persisted before it existed:
a reader falls back to message.
userId
userId: string;
Type Aliases
ActionFieldSchema
type ActionFieldSchema = object;
Properties
default?
default?: unknown;
description?
description?: string;
enumValues?
enumValues?: string[];
fields?
fields?: Record<string, ActionFieldSchema>;
itemType?
itemType?: ActionFieldType;
max?
max?: number;
maxLength?
maxLength?: number;
min?
min?: number;
minLength?
minLength?: number;
required
required: boolean;
type
type: ActionFieldType;
ActionFieldType
type ActionFieldType = "string" | "number" | "boolean" | "enum" | "object" | "array" | "unknown";
ActionInputOf
type ActionInputOf<TFlow, TAction> = TFlow extends UntypedFlow ? unknown : TAction extends keyof TFlow["actions"] ? FlowActionInput<TFlow["actions"][TAction]> : never;
The input send takes for one action of a flow type.
Type Parameters
TFlow
TFlow extends TypedFlow
TAction
TAction extends string
ActionInputSchema
type ActionInputSchema =
| {
fields: Record<string, ActionFieldSchema>;
type: "object";
}
| {
type: "unsupported";
};
ActionNameOf
type ActionNameOf<TFlow> = TFlow extends UntypedFlow ? string : keyof TFlow["actions"] & string;
The action names send takes for a flow type.
Type Parameters
TFlow
TFlow extends TypedFlow
AnswerSuspensionBody
type AnswerSuspensionBody = object;
The answer to a suspension that waits for a user (RequestHandle.answer).
Who answered is the signed-in caller, set by the server: there is no resumedBy.
Properties
action
action: ResumeAction;
The answer: approve or reject for an approval, submit with data
for a review or an input. Must be in the suspension's allow set (409 otherwise).
data?
data?: unknown;
The answer's payload, validated against the suspension's resumeSchema.
suspensionId
suspensionId: string;
Id of the pending suspension to answer.
BindStoreToCallbacksOptions
type BindStoreToCallbacksOptions = object;
Options for bindStoreToCallbacks.
Properties
itemFilter?
itemFilter?: (item) => boolean;
Gate item upserts — items failing the predicate never reach the store.
Parameters
item
OutputItem
Returns
boolean
onChange?
onChange?: (kind) => void;
Invoked after a mutation that may have changed the snapshot.
Parameters
kind
Returns
void
ChangeKind
type ChangeKind =
| "items"
| "request"
| "run"
| "state"
| "resource"
| "board"
| "suspension"
| "resync";
What changed under a topic.
items— an item was kept under one of the session's requests.request— one of the session's requests was written: created, its status moved, or deleted.run— a session record was written: the topic's own session, or a run (a child session) under it.state— the scope's state was written: a session, user or org patch.resource— a resource under the scope was written, created or deleted. The topic names it inresource.board— a row on a task board changed, on the topic of the session that filed it, narrowed to the board's id. The session stream ignores it: a board is read through its own read.suspension— one of the user's suspensions was written or deleted, on their user topic. It names nothing: the topic spans their organizations.resync— the bus may have missed notices (it reconnected). Every subscriber reads once, whatever kinds it otherwise listens for.
ChildSessionStatus
type ChildSessionStatus = "active" | "completed" | "failed" | "incomplete" | "aborted";
How a ChildSession's runs ended, or that they have not ended. "active"
asserts only not finished. In a list read once, never gloss it as
"running" or "live": the read may be stale. A view that follows its session
(useSession(id, { live: true })) re-reads the list as runs start and
finish, so there "active" may read as "working", which clears when the run
ends. A paused or stopped run reads the same.
See docs/architecture/server-and-client.md § Background work (ChildSessions)
for the full semantics, including why this is not RequestStatus.
ChildSessionSummary
type ChildSessionSummary = object;
One body of background work running under a conversation.
A ChildSession is a child session that outlives the turn that started it, so
its history is read with sessions.requests — the
same call a conversation's own turns are read with.
The wire sends a named field set rather than a whole session record, so this
stands on its own instead of extending the client's SessionSummary: the listing
carries no flowKind, userId, title or metadata, and declaring them
here would type fields the server never sends.
Properties
coordinate?
coordinate?: string;
Display-only label for which worker within the work; same absence rule as topic.
createdAt
createdAt: number;
flowId?
flowId?: string;
The flow instance that owns the child — the address to read it through
when it was dispatched into another instance. Absent on a child written
before owners were recorded; guard with == null.
id
id: string;
Bare child session id — the address for reading this ChildSession's requests.
parentSessionId
parentSessionId: string;
Bare id of the conversation this work hangs off.
status?
status?: ChildSessionStatus;
Absent when nothing has run yet — not a status to render a placeholder for.
topic?
topic?: string;
Display-only label for what body of work this is; guard with == null.
updatedAt
updatedAt: number;
ClientFetch
type ClientFetch = (input, init?) => Promise<Response>;
Generic fetch signature used by all client transport modules.
Parameters
input
RequestInfo | URL
init?
RequestInit
Returns
Promise<Response>
CollectionListPage
type CollectionListPage = object;
One page of collection state returned by GET /sessions/:id/resources/:ref.
Cursor-paged: nextCursor is an opaque token present only when more rows
remain (its absence means the last page). Pass it back as cursor to fetch
the next page. Store-backed collections page by keyset; projected collections
return the app store's own cursor.
Properties
items
items: object[];
clientData?
clientData?: unknown;
topic
topic: string;
nextCursor?
nextCursor?: string;
CollectionManifestEntry
type CollectionManifestEntry = object;
One entry on a collection manifest: its storage key and version, and not its value.
Properties
storageKey
storageKey: string;
version
version: number;
CollectionManifestPage
type CollectionManifestPage = object;
One page of a collection manifest, and the cursor of the next (absent on the last).
Properties
items
items: CollectionManifestEntry[];
nextCursor?
nextCursor?: string;
CollectionReadStopReason
type CollectionReadStopReason = "page-limit" | "repeated-cursor";
Why a read stopped with pages still to read.
CollectionResourceHandle
type CollectionResourceHandle<TClient> = object;
React-layer wrapper around a collection resource. Augments the server's
{ topic, clientData? } payload with the lazy-content ergonomic
(fetchContent()) so consumers don't have to plumb the client themselves.
TClient is the projected client-data shape — supplied by the
React hook generic, typically via ClientDataOf<typeof collection>. Defaults
to unknown so untyped call sites are unaffected. The runtime payload is the
JsonValue produced by the server projection; the type is a hook-boundary
assertion backed by the projection contract.
Type Parameters
TClient
TClient = unknown
Properties
clientData?
clientData?: TClient;
topic
topic: string;
Methods
fetchContent()
fetchContent(): Promise<string | null>;
Returns
Promise<string | null>
CollectionResourceState
type CollectionResourceState = object;
One collection resource's state, returned by GET /sessions/:id/resources/:ref/:topic.
Properties
clientData?
clientData?: unknown;
topic
topic: string;
CollectionSnapshotEntry
type CollectionSnapshotEntry = object;
Client-visible metadata for a collection resource in the snapshot.
The per-item items map is not materialized by default.
count is always emitted for client-visible collections; prefetched is
populated only when the collection declares a non-zero prefetchWindow.
Properties
count?
count?: number;
Total number of items currently in the collection. Always emitted for
client-visible collections, regardless of client.state.read.
live?
live?: Record<string, {
clientData?: unknown;
deleted?: boolean;
}>;
Per-topic live overlay. Populated client-side by
mergeResourceChangeIntoSnapshot from live: true resource_change deltas
and read by useCollectionResource as an overlay on the fetched
baseline. A created/updated entry carries clientData; a deleted entry is
a tombstone (deleted: true) so the hook can show the item as gone without
waiting for a refetch. Never emitted by the server — purely a client-merge
target, reconciled away on the next authoritative snapshot.
prefetched?
prefetched?: CollectionSnapshotPrefetchedItem[];
First N items in lexicographic storage-key order. Populated only when the
collection declares prefetchWindow: N (N > 0). Per-item clientData is
included only when client.state.read: true.
CollectionSnapshotPrefetchedItem
type CollectionSnapshotPrefetchedItem = object;
One inlined item inside CollectionSnapshotEntry.prefetched.
clientData is present only when the collection sets client.state.read: true;
otherwise the entry carries just the topic. content is present only when
client.content.prefetch: true is also declared.
Properties
clientData?
clientData?: unknown;
content?
content?: string;
storageKey
storageKey: string;
Full storage key (e.g. "memos/abc"). Matches the standalone list endpoint shape.
topic
topic: string;
Bare topic — the identifying portion of the key after the pattern prefix.
CreateClientOptions
type CreateClientOptions = object;
Options for createClient.
Properties
apiPath?
apiPath?: string;
Where the server mounts the flow API, after baseUrl. Default
"/api/flows". Set it to the server's mount when that differs, such as
the Node host's basePath.
baseUrl?
baseUrl?: string;
Where the server answers, e.g. "http://localhost:3000"; "" for the
page's own origin. Required without a fetcher.
fetcher?
fetcher?: ClientFetch;
The fetch every call and stream goes through. Pass the engine's
createInProcessFetch(flowState) to reach an engine in this process with
no web server, or a wrapper that adds credentials. Default: the global
fetch.
sendTimeoutMs?
sendTimeoutMs?: number;
How long flow().send waits for the server to answer, in milliseconds.
The server answers a send as soon as it takes it, so a send with no
answer by then is lost on the way (a dropped connection, a proxy gone
down): it rejects with a ClientHttpError of status 0, and a message box
keeps its text for a Retry. Only the wait for the answer to start is
timed; a stream that has started runs as long as it runs. Default
30_000; 0 waits for ever.
userId
userId: string;
The user every call acts as. Sent as caller input, never trusted: with sign-in, the server authenticates the request's credentials instead.
CreateCollectionResourceOptions
type CreateCollectionResourceOptions = object;
A new resource in a collection.
Properties
content?
content?: string;
topic
topic: string;
CreateSessionOptions
type CreateSessionOptions = object;
What a new session starts with. The flow and user come from the handle and client.
Properties
description?
description?: string;
metadata?
metadata?: Record<string, unknown>;
sessionId?
sessionId?: string;
state?
state?: Record<string, unknown>;
tags?
tags?: string[];
title?
title?: string;
CreateSSEClientFromResponseOptions
type CreateSSEClientFromResponseOptions = RequestSSECallbacks & object;
Options for creating an SSE client from a pre-fetched Response (inline streaming). Used when the POST action response itself is the SSE stream.
Type Declaration
dedupWindowSize?
dedupWindowSize?: number;
response
response: Response;
DebugClientView
type DebugClientView =
| {
ok: true;
value: unknown;
}
| {
error?: string;
ok: false;
reason: "no_client_data" | "state_read_false" | "threw";
}
| null;
Per-entry projection result on the privileged debug surface — the same
shape client.data would have emitted (or a typed reason it didn't). See
@flow-state-dev/engine debug-snapshot.ts for the server-side producer.
DebugCollectionResource
type DebugCollectionResource = object;
One item in a paginated collection debug listing.
Properties
clientView
clientView: DebugClientView;
contentByteLength?
contentByteLength?: number;
contentType?
contentType?: string;
contentVisibleToClient
contentVisibleToClient: boolean;
hasContent
hasContent: boolean;
state
state: Record<string, unknown> | null;
storageKey
storageKey: string;
topic
topic: string;
DebugCollectionResourcesResponse
type DebugCollectionResourcesResponse = object;
Properties
items
items: DebugCollectionResource[];
nextCursor
nextCursor: string | null;
DebugResourceClientConfig
type DebugResourceClientConfig = object;
Snapshot of a resource's client.* config the panel renders next to each entry.
Properties
contentRead
contentRead: boolean;
data
data: boolean;
hasClient
hasClient: boolean;
prefetchWindow
prefetchWindow: number | null;
stateRead
stateRead: boolean;
DebugResourceEntry
type DebugResourceEntry = object;
One row in the debug resource tree.
Properties
aliases
aliases: string[];
clientConfig
clientConfig: DebugResourceClientConfig;
clientView?
clientView?: DebugClientView;
collectionPattern?
collectionPattern?: string;
contentByteLength?
contentByteLength?: number;
contentType?
contentType?: string;
contentVisibleToClient?
contentVisibleToClient?: boolean;
definitionId
definitionId: string;
hasContent?
hasContent?: boolean;
isCollection
isCollection: boolean;
itemCount?
itemCount?: number;
itemCountTruncated?
itemCountTruncated?: boolean;
llmWritable?
llmWritable?: boolean;
Whether a model is offered a write tool for the resource. A different
question from writable, and opt-in — most mutable resources leave it
unset — so it never stands in for it. Absent when undeclared.
primaryName
primaryName: string;
scope
scope: "session" | "user" | "org";
state?
state?: Record<string, unknown> | null;
storagePrefix?
storagePrefix?: string;
writable?
writable?: boolean;
Whether the store will accept a write to this resource's state or content.
Absent when nothing makes it unwritable, and absent means writable —
the framework's default. A server that predates this sends neither this
nor llmWritable, so treat absence as "not reported" rather than as
false.
false is narrower than "immutable". It refuses state and content
writes through this definition. A collection still permits create and
delete, and another flow holding its own definition of a shared org or
user resource can still write the same underlying cell.
DebugResourcesResponse
type DebugResourcesResponse = object;
Properties
flowKind
flowKind: string;
generatedAt
generatedAt: string;
resources
resources: DebugResourceEntry[];
sessionId
sessionId: string;
DebugStorageResponse
type DebugStorageResponse = object;
Response shape for the debug store-size endpoint. storage is null when
the host's store can't measure itself (an in-memory store, or an adapter
that doesn't report a size).
Properties
storage
storage:
| {
bytes: number;
kind: string;
location?: string;
}
| null;
Union Members
Type Literal
{
bytes: number;
kind: string;
location?: string;
}
bytes
bytes: number;
Bytes the store's files or tables take.
kind
kind: string;
The backend: "sqlite", "filesystem", "postgres", or an adapter's own name.
location?
location?: string;
What was measured: a file or folder path, or a database name.
null
DebugSuspensionsResponse
type DebugSuspensionsResponse = object;
Response shape for the debug suspensions listing endpoint.
Properties
suspensions
suspensions: SuspensionRecord[];
ExecuteActionResponse
type ExecuteActionResponse = object;
Canonical action execution response shape.
Properties
error?
error?: string;
request
request: object;
actionName
actionName: string;
flowId?
flowId?: string;
The flow instance that owns the request — the address to re-enter it through.
flowKind
flowKind: string;
id
id: string;
status
status: "in_progress" | "completed" | "failed" | "incomplete";
session?
session?: object;
id
id: string;
status
status: "in_progress" | "completed" | "failed" | "incomplete";
FlowCapabilities
type FlowCapabilities = object;
What the server supports, from GET /capabilities.
Properties
push?
push?: PushCapability | null;
The push client.subscribe hears change notices on, or null when the
server has none (a serverless host). Missing from an older server's
answer, which means none. It only advertises: the mint's answer decides.
userStream
userStream: boolean;
Always false: the server serves no user SSE stream.
FlowListEntry
type FlowListEntry = object;
List-flows API item shape.
Properties
actions
actions: string[];
actionSchemas?
actionSchemas?: Record<string, ActionInputSchema>;
cardinality
cardinality: "singleton" | "collection";
"singleton" (one instance, addressed by kind) or "collection" (addressed by id only).
description?
description?: string;
What the flow is for, in a sentence, when its definition says. Display only.
id
id: string;
The instance's address — its kind for a singleton, its explicit id for a collection member.
kind
kind: string;
requireUser
requireUser: boolean;
GetSessionStateOptions
type GetSessionStateOptions = object;
Query options for reading a session's state snapshot.
Properties
clientData?
clientData?: string[];
includeItems?
includeItems?: boolean;
itemTypes?
itemTypes?: string[];
limit?
limit?: number;
offset?
offset?: number;
HarnessLineOutcome
type HarnessLineOutcome = "taken" | "after-this-turn" | "turn";
What became of a line: taken into the running turn, sent to run after it, or sent as a turn because none was running.
ListChildSessionsOptions
type ListChildSessionsOptions = object;
Paging for the background work under one conversation. There is no filter: which work a caller may see is the server's call, from the stored parent.
Properties
limit?
limit?: number;
1–100. The server returns 25 rows when this is absent.
offset?
offset?: number;
0–10000.
ListCollectionResourcesOptions
type ListCollectionResourcesOptions = object;
Paging for one collection's resources.
Properties
cursor?
cursor?: string;
limit?
limit?: number;
topicPrefix?
topicPrefix?: string;
ListDebugCollectionResourcesOptions
type ListDebugCollectionResourcesOptions = object;
Query options for the debug items endpoint.
Properties
cursor?
cursor?: string | null;
limit?
limit?: number;
topic?
topic?: string;
Case-sensitive substring filter on the bare topic.
ListDebugSuspensionsOptions
type ListDebugSuspensionsOptions = object;
Query options for the debug suspensions endpoint.
Properties
flowKind?
flowKind?: string;
limit?
limit?: number;
status?
status?: SuspensionStatus;
userId?
userId?: string;
ListSessionRequestsOptions
type ListSessionRequestsOptions = object;
Query options for listing the requests in one session.
Properties
includeItems?
includeItems?: boolean;
Return each summary's full item log (include_items=true). Off by default.
includeResultOutput?
includeResultOutput?: boolean;
Return each finished request's result.output. Off by default.
limit?
limit?: number;
offset?
offset?: number;
status?
status?: SessionRequestSummary["status"];
ListSessionsOptions
type ListSessionsOptions = object;
Query options for Client.sessions.list.
Properties
flowId?
flowId?: string;
Exact owning instance. Narrower than flowKind for a collection flow.
flowKind?
flowKind?: string;
include?
include?:
| SessionListInclude
| readonly SessionListInclude[];
What the listing adds, one value or several:
"dispatch-runs": also return the sessions a dispatcher ran work in. Off by default: a listing without it returns the sessions the user started. It widens parentage only; a run of another principal, organization or tenant stays absent. A row that came in this way carries SessionSummary.parentSessionId."status": each row's SessionSummary.requestStatus, the state of its latest request, read on the server.
limit?
limit?: number;
offset?
offset?: number;
state?
state?: Readonly<Record<string, string>>;
Only the sessions whose readonly state fields hold these values: a field
the flow's session stateSchema declares .readonly(), set when the
session was created. Needs flowKind or flowId; the server refuses a
field that isn't readonly on that flow.
userId?
userId?: string;
Whose sessions to list. Default: the client's own user. With sign-in on, the server narrows any listing to the signed-in user.
LivePaths
type LivePaths = readonly string[] | ((scope) => readonly string[] | undefined);
Which resource paths a live read hears: roots (a notice at a root or below
it reads), or roots per scope. undefined from the function rules nothing
out, for roots not known yet.
LiveRead
type LiveRead = object;
A running live read.
Methods
close()
close(): void;
Stop: the subscription closes, a read still out is for nobody, and nothing more is reported.
Returns
void
refresh()
refresh(): void;
Read again now, through the same queue.
Returns
void
LiveReadOptions
type LiveReadOptions<T> = LiveReadBase<T> & object;
Options for client.live. read gets the notice that woke it, or null for several, a connect or a tick.
Type Parameters
T
T
Type Declaration
read
read: (notice, signal) => T | PromiseLike<T>;
Parameters
notice
WireNotice | null
signal
AbortSignal
Returns
T | PromiseLike<T>
topicsFromResult?
topicsFromResult?: false;
LiveReadWithTopicsOptions
type LiveReadWithTopicsOptions<T> = LiveReadBase<T> & object;
Options for client.live when each read also names the topics to hear next.
Type Parameters
T
T
Type Declaration
read
read: (notice, signal) =>
| LiveResult<T>
| PromiseLike<LiveResult<T>>;
Parameters
notice
WireNotice | null
signal
AbortSignal
Returns
| LiveResult<T>
| PromiseLike<LiveResult<T>>
topicsFromResult
topicsFromResult: true;
LiveResult
type LiveResult<T> = object;
What a read hands back when it also names the topics to hear next, and,
for a view's answer, which notices under them may change it (hears;
absent: every one).
Type Parameters
T
T
Properties
hears?
hears?: readonly ViewHearing[];
topics
topics: readonly WireTopic[];
value
value: T;
PushCapability
type PushCapability =
| {
transport: "websocket";
}
| {
transport: "ably";
};
The push a server has, as GET /capabilities reports it in push, or
null when it has none (a serverless host, createServerApp alone). It
only advertises: once a client mints, the answer's transport decides.
ReadEveryCollectionPageOptions
type ReadEveryCollectionPageOptions = object;
Options for readEveryCollectionPage.
Properties
keepReading?
readonly keepReading?: () => boolean;
Checked after each page. Returning false ends the read early with the
rows read so far, for a caller whose result is already stale and will be
discarded.
Returns
boolean
limit?
readonly limit?: number;
Page size requested each time. Not a cap on rows: the read follows the cursor to the end.
ReadSessionEarlierOptions
type ReadSessionEarlierOptions = object;
Options for readSessionEarlier.
Properties
limit?
readonly limit?: number;
How many earlier items to add. Default SESSION_WINDOW_PAGE.
ReadSessionTailOptions
type ReadSessionTailOptions = object;
Options for readSessionTail.
Properties
itemTypes?
readonly itemTypes?: readonly string[];
Only these item types, as sessions.state's itemTypes.
limit?
readonly limit?: number;
How many of the newest items to read. Default SESSION_WINDOW_PAGE.
RequestResult
type RequestResult = object;
A settled request, as RequestHandle.result reads it: its status, plus what the record stored for it.
status | also |
|---|---|
completed / incomplete | output, absent when the action returned nothing |
failed | error, plus output when the action answered before a completion hook failed the request |
| any of those, output not storable as JSON | outputNotRecorded: true in place of output |
suspended / aborted / interrupted | nothing |
Properties
error?
error?: object;
Why the request failed.
code
code: string;
message
message: string;
output?
output?: unknown;
The action's return value, as stored (JSON).
outputNotRecorded?
outputNotRecorded?: true;
The action returned a value that could not be stored as JSON; distinct from returning nothing.
status
status: RequestStatusSnapshot["status"];
How the request settled.
RequestSSECallbacks
type RequestSSECallbacks = object;
Callback set for request-stream SSE events.
Properties
onClose?
onClose?: () => void;
Fired once the underlying stream body ends cleanly — i.e. onError
did NOT fire and the connection was not close()d locally. A stream can
legally end without ever emitting a terminal onRequestStatus (e.g. the
server closes after a pre-transition failure), so a caller that only
clears its "in flight" state from onRequestStatus/onError would
otherwise get stuck. Only implemented by createSSEClientFromResponse:
a request's own stream() does not fire this. It resumes after its last
event instead, and reports with onError if it gives up. A caller of
createSSEClientFromResponse resumes the same way: request(id).stream()
with startingAfter set to the last sequence_number it applied.
Returns
void
onContentAdded?
onContentAdded?: (event) => void;
Parameters
event
ContentPartAddedEvent
Returns
void
onContentAudioDelta?
onContentAudioDelta?: (event) => void;
Fires for each chunk of streaming TTS audio. Live-only —
these events are NOT delivered via Last-Event-ID resume; on
reconnect, the durable representation arrives as an
OutputAudioContent snapshot via onContentAdded / onContentDone.
The chunk's mediaType is on the parent OutputAudioContent, not
on the delta itself.
Parameters
event
ContentAudioDeltaEvent
Returns
void
onContentDelta?
onContentDelta?: (event) => void;
Parameters
event
ContentPartDeltaEvent
Returns
void
onContentDone?
onContentDone?: (event) => void;
Parameters
event
ContentPartDoneEvent
Returns
void
onDebug?
onDebug?: (event) => void;
Parameters
event
RequestDebugEvent
Returns
void
onError?
onError?: (error) => void;
Parameters
error
Error
Returns
void
onEvent?
onEvent?: (event) => void;
Parameters
event
RequestStreamEvent
Returns
void
onHeartbeat?
onHeartbeat?: () => void;
Fired when the parser sees an SSE comment frame (: ping\n\n). The
server emits these on a fixed cadence so clients can run an inactivity
watchdog without producing false positives during long pauses (e.g.
an LLM thinking between tokens).
Returns
void
onItemAdded?
onItemAdded?: (event) => void;
Parameters
event
ItemAddedEvent
Returns
void
onItemDone?
onItemDone?: (event) => void;
Parameters
event
ItemDoneEvent
Returns
void
onItemUpdated?
onItemUpdated?: (event) => void;
Fired when an item.updated event arrives. The patch is a shallow
top-level merge into the previously-added item; identity-invariant
keys (id, type, provenance, itemVisibility, transient) are
stripped server-side and should also be ignored defensively here.
Parameters
event
ItemUpdatedEvent
Returns
void
onRequestCreated?
onRequestCreated?: (event) => void;
Parameters
event
RequestCreatedEvent
Returns
void
onRequestStatus?
onRequestStatus?: (event) => void;
Parameters
event
RequestStatusEvent
Returns
void
onResourceChanged?
onResourceChanged?: (event) => void;
Parameters
event
RequestResourceChangedEvent
Returns
void
onSessionMetadataChanged?
onSessionMetadataChanged?: (event) => void;
Parameters
event
SessionMetadataChangedEvent
Returns
void
RequestStreamChangeKind
type RequestStreamChangeKind = "item" | "content" | "status";
What changed on the store, so a consumer can pick a flush policy per kind.
RequestStreamOptions
type RequestStreamOptions = RequestSSECallbacks & StreamResumeOptions & object;
Options for RequestHandle.stream.
Type Declaration
includeTrace?
includeTrace?: boolean;
Also deliver trace items (block_trace, router_decision, state_snapshot).
reconnect?
reconnect?: boolean;
Keep following until the request ends: a failed connection opens again
after the client's backoff (1 s, doubling, at most 30 s), resuming after
the last event, and is not reported. Five empty answers in a row (a
request that already ended) or a 401, 403 or 404 still end the stream
with onError; close() ends it, a pending reconnect included.
RequestStreamStore
type RequestStreamStore<T> = object;
Imperative request-stream store. Maintains a Map<id, T> in sync
with a binary-insert-maintained sorted id list, an ownership index, and a
content-delta queue, plus the request's status, sequence cursor, and
status-event log. All methods are synchronous; no React state is touched.
An "id" a method takes is the item's key: its id, unless the store was
created with keyOf.
T is the row type the store holds, and every read returns exactly the rows
written, so reads are typed T. It defaults to OutputItem. A store seeded
with trace rows (block_trace and the rest) is created as
createRequestStreamStore<RuntimeItem>().
Type Parameters
T
T extends RuntimeItem = OutputItem
Properties
lastSequenceNumber
readonly lastSequenceNumber: number;
The highest sequence number recorded from the stream (the resume cursor).
status
readonly status: RequestStatus;
The request's current status (default "in_progress").
statusEvents
readonly statusEvents: readonly RequestStatusEvent[];
Every request.* status event seen, in arrival order.
Methods
accumulateDelta()
accumulateDelta(
itemId,
contentIndex,
delta
): void;
Buffer a text delta for later flush.
Parameters
itemId
string
contentIndex
number
delta
string
Returns
void
applyContentAdded()
applyContentAdded(
itemId,
contentIndex,
content
): boolean;
Place a content part at an index on a message (content) or reasoning (summary) item — overwrites an existing index, otherwise appends. Returns true if the item was updated.
Parameters
itemId
string
contentIndex
number
content
Content
Returns
boolean
applyContentDone()
applyContentDone(
itemId,
contentIndex,
content
): boolean;
Replace a content part with its authoritative final value at an index (inserting if no prior part exists). Returns true if the item was updated.
Parameters
itemId
string
contentIndex
number
content
Content
Returns
boolean
applyItemPatch()
applyItemPatch(itemId, patch): boolean;
Apply a shallow item.updated patch (invariant keys stripped) to an existing item. Returns false (no-op) if the id is unknown.
Parameters
itemId
string
patch
Record<string, unknown>
Returns
boolean
clear()
clear(): void;
Drop all items, sorted ids, ownership, pending deltas, and reset the status/sequence/status-event layer to a fresh stream.
Returns
void
deleteById()
deleteById(id): boolean;
Remove an item from the map, sorted ids, and ownership index. Returns true if found.
Parameters
id
string
Returns
boolean
discardDeltas()
discardDeltas(itemId): void;
Discard all buffered deltas for an item — the binder's filter seam calls this when itemFilter rejects an item, so a permanently-absent item's deltas don't sit in the queue. No-op if none are buffered.
Parameters
itemId
string
Returns
void
flushDeltas()
flushDeltas(): boolean;
Apply every buffered delta whose target item and content part are ready; deltas that aren't ready yet stay queued for a later flush (streamed text is never dropped). Returns true if any item changed.
Returns
boolean
getById()
getById(id): T | undefined;
Look up a single item by id.
Parameters
id
string
Returns
T | undefined
getOwnedBy()
getOwnedBy(ownedBy): T[];
Return items whose ownedBy matches the given value, sorted chronologically.
Parameters
ownedBy
string
Returns
T[]
getRaw()
getRaw(): T[];
Return all items in chronological order WITHOUT the canonical collapse —
every superseded partial/in-progress row getSorted() strips (Rule 3,
crash-recovery re-run) is still present here. Consumers that need to
render the pre-/post-recovery boundary itself (rather than just the
merged live view) read this instead of getSorted(). New array each call.
Returns
T[]
getSorted()
getSorted(): T[];
Return all items in canonical (collapsed) chronological order. New array each call.
Returns
T[]
loadSnapshot()
loadSnapshot(items): void;
Replace all items with a pre-sorted snapshot. Rebuilds the ownership index. Leaves status/sequence/status-events untouched.
Parameters
items
readonly T[]
Returns
void
recordSequence()
recordSequence(sequenceNumber): void;
Record a stream event's sequence number, advancing the resume cursor.
Parameters
sequenceNumber
number
Returns
void
recordStatusEvent()
recordStatusEvent(event): void;
Append a request.* status event to the log.
Parameters
event
RequestStatusEvent
Returns
void
setStatus()
setStatus(status): boolean;
Set the request status (from a request.created / request.* event). Returns true if the value changed.
Parameters
status
RequestStatus
Returns
boolean
size()
size(): number;
Current item count.
Returns
number
upsert()
upsert(item): boolean;
Insert or update an item. Returns true if sorted order changed (insert or reorder), false if value-only update.
Parameters
item
T
Returns
boolean
RequestStreamStoreOptions
type RequestStreamStoreOptions<T> = object;
Options for createRequestStreamStore.
Type Parameters
T
T extends RuntimeItem = OutputItem
Properties
keyOf?
keyOf?: (item) => string;
The key an item is held under. Defaults to item.id, which is unique
within one request. A store that holds a whole session's items keys by
request and item id together, because two requests can keep the same id
(a keyed item's id comes from its key). Every method that takes an item id
then takes this key instead. It must not change over an item's life.
Parameters
item
T
Returns
string
ResourceContentResponse
type ResourceContentResponse = object;
A resource's rendered content, alone or in a collection.
Properties
content
content: string;
ref
ref: string;
topic?
topic?: string;
ResourceManifest
type ResourceManifest = object;
Resource manifest returned by GET /sessions/:id/manifest. Describes every
public resource the session's flow exposes — static per flowKind.
Properties
flowKind
flowKind: string;
resources
resources: ResourceManifestEntry[];
ResourceManifestEntry
type ResourceManifestEntry = object;
Per-resource manifest entry. Static metadata describing a public resource exposed by a flow.
Properties
client
client: object;
content?
content?: object;
content.create?
create?: boolean;
content.delete?
delete?: boolean;
content.prefetch?
prefetch?: boolean;
content.read?
read?: boolean;
content.update?
update?: boolean;
state?
state?: object;
state.read?
read?: boolean;
hasClientData
hasClientData: boolean;
Whether the resource declares a clientData projection function.
kind
kind: "single" | "collection";
pattern?
pattern?: string;
Pattern (collections only).
prefetchWindow?
prefetchWindow?: number;
Configured prefetch window (collections only). 0 if unset.
ref
ref: string;
scope
scope: "session" | "user" | "org";
ResourceSnapshotEntry
type ResourceSnapshotEntry = object;
Client-visible metadata for a single resource in the snapshot.
Properties
clientData?
clientData?: unknown;
content?
content?: string;
Only present when client.content.prefetch: true is declared on the resource.
ResumeSuspensionBody
type ResumeSuspensionBody = object;
The answer that resolves a pending suspension. Who resolved it is the signed-in caller (the request's owner when the app does not authenticate), set by the server.
Properties
action
action: ResumeAction;
How the suspension resolves: approve/reject, submit with data
validated against the suspension's resumeSchema, or skip for an
optional step. It must be in the suspension's allow set, or the server
answers 409.
data?
data?: unknown;
Resume payload validated against the suspension's resumeSchema.
suspensionId
suspensionId: string;
Id of the pending suspension to resolve.
ScopeEntry
type ScopeEntry<TValue> = object;
One listed entry: its topic, storage key, value and version.
Type Parameters
TValue
TValue
Properties
storageKey
storageKey: string;
topic
topic: string;
value
value: TValue;
version
version: number;
ScopeEntryPage
type ScopeEntryPage<TValue> = object;
One page of a collection's entries, and the cursor of the next (absent on the last).
Type Parameters
TValue
TValue
Properties
items
items: ScopeEntry<TValue>[];
nextCursor?
nextCursor?: string;
ScopeHandleOf
type ScopeHandleOf<TDef> = TDef extends object ? ScopeCollectionHandle<ClientValue<TDef>> : ScopeResourceHandle<ClientValue<TDef>>;
The handle client.resource builds for def: a collection's when it has a pattern.
Type Parameters
TDef
TDef
ScopeResourceDef
type ScopeResourceDef<TValue> = object;
What client.resource takes: a defined user or org resource (its ref is its key) or collection (its pattern).
Type Parameters
TValue
TValue = JsonValue
Properties
ClientType?
ClientType?: TValue;
The client projection's type, branded by defineResource and defineResourceCollection.
pattern?
pattern?: string;
A collection's pattern: its entries are read and written one at a time.
ref?
ref?: string;
scope
scope: "session" | "user" | "org";
ScopeResourceRead
type ScopeResourceRead<TValue> = object;
One read: the value as the client sees it, and the version it is at (0: nothing stored yet).
Type Parameters
TValue
TValue
Properties
value
value: TValue;
version
version: number;
SendOptions
type SendOptions = object;
How a send is addressed and labelled.
Properties
attachments?
attachments?: FileContent[];
The message's files, each as upload returned it (data is its
fsd-blob: reference, never the bytes), in the order attached. They ride
beside the input: the model gets them on the person's turn, and the
conversation shows them on that line. The action must write a user
message (userMessage) and the session must be named. Over the limits
(10 images, 5 documents) the server refuses the send by name.
metadata?
metadata?: Record<string, unknown>;
requestId?
requestId?: string;
sessionId
sessionId: string;
The session the action runs in. Required: every send names its
session. One from createSession(), or, for a one-shot send that belongs
to no conversation, oneOffSessionId() from @flow-state-dev/core/helpers.
SessionConnectionStatus
type SessionConnectionStatus = "connecting" | "live" | "reconnecting" | "lapsed" | "stopped";
How far a session follow can be trusted.
connecting: nothing is vouched for yet; no connection has named the runs.live: the current connection named the runs, so what it says is current.reconnecting: the connection closed and the first retry is coming, as after the server's own close every 15 minutes.lapsed: a retry has failed; what it last said may be out of date. It becomesliveagain when a connection names the runs.stopped: it will not come back: refused, the session gone, or closed.
SessionDetail
type SessionDetail = SessionSummary & object;
Session detail shape returned from session read/create endpoints.
Type Declaration
latestRequestId?
latestRequestId?: string;
orgId
orgId: string;
The organization this session is bound to. Always present on a session the server admitted — the server decides it from the verified principal, and a client never sends one.
state?
state?: Record<string, unknown>;
The session state fields the flow exposes (session.client.expose) or
declares readonly, and no others: empty when there are none. Derived values are on
getSessionState's clientData.
stateSummary?
stateSummary?: object;
stateSummary.org?
org?: Record<string, unknown>;
stateSummary.session?
session?: Record<string, unknown>;
stateSummary.user?
user?: Record<string, unknown>;
version?
version?: number;
SessionFeedOptions
type SessionFeedOptions = object;
Properties
includeTransient?
readonly includeTransient?: boolean;
Keep transient items too. Default false, as useSession.
itemTypes?
readonly itemTypes?: string[];
Keep only these item types. Default: every type.
retryMs?
readonly retryMs?: number;
How long the first retry of a failed history read waits, in ms; each later one waits twice as long, and after four the feed stops. Default 2000.
SessionFeedSnapshot
type SessionFeedSnapshot = object;
What a feed shows at one moment. A new, frozen object on every change.
Properties
error
readonly error: Error | null;
The last history read's failure: while it is read again, and after the
feed gave up (stopped). null once a read lands.
hasEarlier
readonly hasEarlier: boolean;
The session holds items older than items[0]: show Load earlier.
false until the history read lands.
historyLoaded
readonly historyLoaded: boolean;
The history read has landed: items is what the session holds, so an
empty list is an empty session, not one still being read. false again
while the feed starts over on a new session under the id.
items
readonly items: readonly OutputItem[];
The newest history items (readSessionTail's window), the earlier pages
SessionFeed.loadEarlier added, and every item kept since, in
display order (compareItemOrder).
runs
readonly runs: readonly SessionRun[] | null;
The session's unfinished runs as the stream last named them; null until it has.
state
readonly state: SessionConnectionStatus;
How far items and runs can be trusted. See SessionConnectionStatus.
SessionItemsSource
type SessionItemsSource = Pick<SessionsApi, "state">;
What a window reads through: client.sessions, or anything with its state.
SessionItemsWindow
type SessionItemsWindow = object;
A run of one session's items, from start to the session's end as it
stood when read. Hand it back to readSessionEarlier or
refreshSessionWindow; it carries what they need to read on.
Properties
at?
readonly at?: number;
The server time the last read began, to follow the session from with
the session stream's since. An older server omits it.
hasEarlier
readonly hasEarlier: boolean;
Whether the session holds items before this window: show Load earlier.
items
readonly items: readonly OutputItem[];
Oldest first: the session's items from start to total.
itemTypes?
readonly itemTypes?: readonly string[];
The item types the window was read with. Positions count only these.
sessionCreatedAt?
readonly sessionCreatedAt?: number;
When the session read was created, for the session stream's
sessionCreatedAt. A later read that finds another session under the id
starts the window over. An older server omits it.
sessionId
readonly sessionId: string;
start
readonly start: number;
Where items[0] sat in the session's whole item list.
total
readonly total: number;
How many items the session held when read.
SessionListInclude
type SessionListInclude = "dispatch-runs" | "status";
What a session listing can add to its rows (ListSessionsOptions.include).
SessionRequestResult
type SessionRequestResult = object;
A request's action result, as GET /sessions/:id/requests lists it.
| Request ended | result |
|---|---|
completed / incomplete | { output }, the value the action returned; no output when it returned nothing |
failed | { error }, plus output when the action answered before a completion hook failed the request |
output is listed only when the caller passes includeResultOutput: true;
hasOutput says whether there is one either way.
Properties
error?
error?: object;
Why the request failed.
code
code: string;
message
message: string;
hasOutput?
hasOutput?: boolean;
Whether the action's return value is stored, listed or not.
output?
output?: unknown;
The action's return value. Listed only with includeResultOutput.
outputNotRecorded?
outputNotRecorded?: true;
The action returned a value that could not be stored as JSON. The request still finished; its return value is unknown.
SessionRequestSummary
type SessionRequestSummary = object;
Request record fields consumed by client/session views.
Properties
actionName
actionName: string;
completedAtMs?
completedAtMs?: number;
createdAt
createdAt: number;
failedAtMs?
failedAtMs?: number;
flowId?
flowId?: string;
The flow instance that owns the request — the address a retry or continuation re-enters it through. Absent on a legacy record.
flowKind
flowKind: string;
historyStart?
historyStart?: object;
Where the turns this request read begin: the first past turn its history
window held, when earlier turns had fallen out of it. Draw a divider
before that request; the turns above it are out of the model's view (or,
on a flow with a history summary, in the summary). Absent when every
earlier turn was in the window, and on servers that predate the field.
Guard with == null.
requestId
requestId: string;
id
id: string;
items?
items?: OutputItem[];
Item log. Omitted by the GET /sessions/:id/requests list endpoint by
default — it returns summaries only. Pass includeItems: true
(include_items=true) to populate it, or read a single request's items
via the state endpoint. Present on responses that carry full records.
metadata?
metadata?: Record<string, unknown>;
orgId?
orgId?: string;
The organization the request ran in. Absent only on a legacy record.
result?
result?: SessionRequestResult;
What the action came to, once the request has ended. See SessionRequestResult.
Absent while the request runs or is suspended, and on aborted or
interrupted requests. Absent on a completed, incomplete or failed
request means no result was recorded (a server, or history, from before
results were stored). Guard with == null.
retryable?
retryable?: boolean;
Whether the server runs this request again when the caller retries it:
the retry route's own rule, the same answer a session's turns carry.
Offer Retry on a failed turn only when it is true. Absent on servers
that predate the field; read absent as not retryable.
sessionId?
sessionId?: string;
source?
source?: string;
Inbound transport provenance — see server RequestRecord.source.
Records summarized from an older server may omit the
field; clients should default missing values to "http".
startedAtMs?
startedAtMs?: number;
state?
state?: Record<string, unknown>;
status
status: RequestStatus;
updatedAt
updatedAt: number;
userId
userId: string;
SessionSSECallbacks
type SessionSSECallbacks = object;
Callback set for session-stream events.
The stream starts a few seconds before since, so onItem can fire for an
item it already delivered, or one the snapshot that gave since already
held, and an item a request emits more than once under one id (a keyed
component) fires once per emission. Tell items apart by requestId and
item.id together and keep the copy that sorts later by
compareItemOrder.
Properties
onError?
onError?: (error) => void;
An event the client could not parse. Connection drops are retried, not reported.
Parameters
error
Error
Returns
void
onEvent?
onEvent?: (event) => void;
Every event, pings included.
Parameters
event
SessionStreamEvent
Returns
void
onItem?
onItem?: (event) => void;
A finished item a request in the session kept, from any request.
Parameters
event
SessionItemEvent
Returns
void
onReconnecting?
onReconnecting?: (event) => void;
The connection dropped and the client will try again after its backoff.
attempt counts the tries since the stream last delivered an event: 1 is
the reconnect after an ordinary close, such as the server's own after 15
minutes; 2 or more means a try has failed since. Until a connection
delivers again, what the stream last said may no longer be current.
Parameters
event
attempt
number
Returns
void
onRuns?
onRuns?: (event) => void;
The session's unfinished runs, on open and whenever the set changes.
Parameters
event
SessionRunsChangedEvent
Returns
void
onStop?
onStop?: (reason) => void;
The server refused the stream (401 or 403), does not have it (404, 501), cannot say who owns the session until it is migrated (409), or the session is gone. The client does not retry; the view carries on as it would without the stream.
Parameters
reason
status
number
Returns
void
SessionStateSnapshotResponse
type SessionStateSnapshotResponse = object;
Canonical session state snapshot response shape.
Properties
at?
at?: number;
The server time this read began. Everything kept before it is in the
snapshot, so a client that then follows the session passes it to the
session stream as since. An older server omits it.
clientData
clientData: object;
org?
org?: Record<string, unknown>;
session?
session?: Record<string, unknown>;
user?
user?: Record<string, unknown>;
flowKind
flowKind: string;
items?
items?: OutputItem[];
pagination?
pagination?: object;
hasMore
hasMore: boolean;
limit
limit: number;
nextOffset
nextOffset: number;
offset
offset: number;
total
total: number;
resources?
resources?: object;
org?
org?: Record<string,
| ResourceSnapshotEntry
| CollectionSnapshotEntry>;
session?
session?: Record<string,
| ResourceSnapshotEntry
| CollectionSnapshotEntry>;
user?
user?: Record<string,
| ResourceSnapshotEntry
| CollectionSnapshotEntry>;
sessionCreatedAt?
sessionCreatedAt?: number;
When the session this snapshot read was created. A session id can be
deleted and used again, so a client that then follows the session passes
this to the session stream as sessionCreatedAt, and the stream follows
this session and none that takes its id later. An older server omits it.
sessionId
sessionId: string;
SessionStreamOptions
type SessionStreamOptions = SessionSSECallbacks & object;
Configuration for following a whole session over
GET /api/flows/sessions/:sessionId/stream.
Type Declaration
itemTypes?
itemTypes?: string[];
The session snapshot's type filter, so the stream sends what the snapshot shows.
retry?
retry?: object;
Reconnect backoff: initialDelayMs (default 1000) doubling to maxDelayMs (default 30000).
retry.initialDelayMs?
initialDelayMs?: number;
retry.maxDelayMs?
maxDelayMs?: number;
sessionCreatedAt?
sessionCreatedAt?: number;
The session snapshot's sessionCreatedAt, when the stream follows a
snapshot. Every connection then follows that session only: once its id
holds another session, the server answers 404 and the client stops.
since?
since?: number;
A server time to start from: one an earlier connection heard
(handle.lastAt), or the session snapshot's at when the stream follows a
snapshot. The server's first read reaches a few seconds before it.
Omitted, it reaches back about a minute.
SessionSummary
type SessionSummary = object;
Session summary shape used in list endpoints.
Properties
coordinate?
coordinate?: string;
The entry the run was dispatched for, as <type>:<target>. Display only.
createdAt
createdAt: number;
description?
description?: string;
flowId?
flowId?: string;
The flow instance that owns the session. Absent on a session written before instance ownership existed.
flowKind
flowKind: string;
id
id: string;
label?
label?: string;
What the session's flow calls it (its session.label), computed from the
state the session shows when the session is read. Absent when the flow
declares none or names nothing. Display only: a title, when the session
has one, reads first.
metadata?
metadata?: Record<string, unknown>;
parentSessionId?
parentSessionId?: string;
The session a dispatcher was running in when it started this one — the provenance edge, and the only thing that makes this row a dispatch run rather than a conversation someone opened.
Only ever populated when the listing was asked for dispatch runs
(include: "dispatch-runs"); without that the listing returns top-level
sessions only, and every row's is absent. A store that nulls absent keys
hands back null, so guard with == null rather than a truthiness check.
requestStatus?
requestStatus?: RequestStatus;
The state of the session's latest request: one still going
(in_progress, or suspended while it is stopped) wins over a later
one that ended, else the most recent request's status. Only when the
listing was asked for it (include: "status"), and absent on a session
with no request; guard with == null.
requestWaitsForUser?
requestWaitsForUser?: boolean;
With requestStatus: "suspended": true when the stop waits for the
user (a question, an approval), false when it waits on other work and
resumes by itself. Absent otherwise, and from a server that predates it.
tags?
tags?: string[];
title?
title?: string;
topic?
topic?: string;
The key the dispatcher derived this run's session id from. Display only: it names the body of work, never who may read it.
updatedAt
updatedAt: number;
userId
userId: string;
StreamOption
type StreamOption = object;
Ask for an SSE response instead of JSON: the call resolves to the raw Response.
Properties
stream
stream: true;
true returns the server's SSE Response from the POST itself, so a
serverless host with no shared pub/sub still streams the run live. A
server that can't stream inline answers 202 JSON instead; read the
response's content-type.
StreamResumeOptions
type StreamResumeOptions = object;
Resume options a request or user stream takes.
Properties
dedupWindowSize?
dedupWindowSize?: number;
How many recent event keys are remembered to drop a duplicate. Default 1000.
lastEventId?
lastEventId?: string;
Resume after this event id (sent as Last-Event-ID). Ignored when startingAfter is set.
startingAfter?
startingAfter?: number;
Resume after this sequence number.
SubscribeOptions
type SubscribeOptions = object;
Options for client.subscribe.
Properties
onChange
onChange: (notice) => void;
Called when something under a subscribed topic may have changed: with
the notice that woke it, or null for a connect, a reconnect, a change
of whether push crosses processes, or a timer tick. Read again here.
Parameters
notice
WireNotice | null
Returns
void
pollIntervalMs?
pollIntervalMs?: number;
Read on a timer at this pace wherever push can miss a change: the host has no push, the socket is down, or its bus doesn't cross processes. Omitted: no timer; reads happen on a notice, a connect and a reconnect.
Subscription
type Subscription = object;
A live subscription.
Methods
close()
close(): void;
Stop hearing these topics. The last handle on a client closes its socket.
Returns
void
SuspensionStatus
type SuspensionStatus =
| "pending"
| "approved"
| "rejected"
| "submitted"
| "skipped"
| "timed_out"
| "expired"
| "stopped"
| "cancelled";
Lifecycle status of a suspension. pending is the sole non-terminal state.
TopicOptions
type TopicOptions = object;
Narrow a topic to one resource under its scope.
Properties
resource?
resource?: string;
TranscribeRequest
type TranscribeRequest = object;
Audio to transcribe.
Properties
audio
audio: Uint8Array | Blob;
language?
language?: string;
mediaType?
mediaType?: string;
TranscribeResponse
type TranscribeResponse = object;
A transcription.
Properties
language?
language?: string;
text
text: string;
TypedFlow
type TypedFlow = object;
A flow whose actions type-check send, as typeof myFlow gives it. Types only.
Properties
actions
actions: Record<string, ActionConfig>;
UntypedFlow
type UntypedFlow = object;
The flow type flow() uses when none is given: any action name, any input.
Properties
actions
actions: Record<string, never>;
UpdateResourceContentOptions
type UpdateResourceContentOptions = object;
New content for a resource, alone or in a collection.
Properties
content
content: string;
UpdateSessionMetadataOptions
type UpdateSessionMetadataOptions = object;
Fields of a session's metadata to replace.
Properties
description?
description?: string;
metadata?
metadata?: Record<string, unknown>;
tags?
tags?: string[];
title?
title?: string;
UploadRequest
type UploadRequest = object;
One file to attach: its bytes, its type (a Blob's own type when omitted), and the name a person sees.
Properties
data
data: Uint8Array | Blob;
filename?
filename?: string;
mediaType?
mediaType?: string;
ViewCallOptions
type ViewCallOptions = object;
Options for running a view: the session, for a session view, and the change
notice it may answer for (ctx.view.changed). A notice with no ids is not
sent: the view answers whole.
Properties
changed?
changed?: WireNotice | null;
sessionId?
sessionId?: string;
ViewInputOf
type ViewInputOf<TRef> = TRef extends ViewRef<infer TView> ? ViewInput<TView> : unknown;
The input type of the view a handle names.
Type Parameters
TRef
TRef
ViewRef
type ViewRef<TView> = object;
A view by flow address and name, typed by the view. Holds no block: safe in a browser bundle.
Type Parameters
TView
TView extends ViewDefinition = ViewDefinition
Properties
__view?
readonly __view?: TView;
Types only: the view this handle names. Never set.
flow
readonly flow: string;
view
readonly view: string;
ViewResult
type ViewResult<TValue> = object;
One run of a view: its value, the topics of what it read, and a keyed view's row keys, in order.
Type Parameters
TValue
TValue = unknown
Properties
hears?
hears?: ViewHearing[];
Which notices under topics may change what the run read. Absent (a server from before it): every one.
keys?
keys?: string[];
partial?
partial?: object;
Set when the view answered for just the rows a change touched: value
is those rows, to place by key over the rows held, and removed the
keys to drop. Absent: value is the whole answer.
removed
removed: string[];
topics
topics: WireTopic[];
value
value: TValue;
ViewValueOf
type ViewValueOf<TRef> = TRef extends ViewRef<infer TView> ? ViewOutput<TView> : unknown;
The answer type of the view a handle names.
Type Parameters
TRef
TRef
WaitOptions
type WaitOptions = object;
How RequestHandle.wait and RequestHandle.result wait.
Properties
pollMs?
pollMs?: number;
How often the status is read, in ms. Default 250.
signal?
signal?: AbortSignal;
Stop waiting when this aborts. Stops the wait only, never the run.
timeoutMs?
timeoutMs?: number;
Reject with a ClientHttpError of status 0 past this many ms. Default: never.
WireNotice
type WireNotice = object;
A change notice as the socket delivers it: the topic it happened under (the resource included when the change was narrowed to one), its kind, the request that made it, when a request did, and the ids of what changed, when the publisher knew them. Never the rows that changed.
Properties
ids?
ids?: string[];
Which rows changed: opaque ids the publisher already holds (a task on a
board notice, an entry's storage key on a collection entry's resource
notice, a session on a run notice, a request on a request notice), at
most NOTICE_MAX_IDS. Absent: read everything. A hint, never data:
a reader that can't use them reads everything.
kind
kind: ChangeKind;
origin?
origin?: object;
requestId
requestId: string;
partition?
partition?: string;
On a board notice, the partition of a partitioned ledger the change is
in, as an opaque key: a keyed digest the server makes, which names no
session and can't be matched by guessing one. A reader compares it with
the keys an answer read (ViewHearing.partitions) and nothing else.
Absent: any partition, and every board under the topic reads.
topic
topic: WireTopic;
WireTopic
type WireTopic =
| {
id: string;
resource?: string;
scope: "session";
}
| {
resource?: string;
scope: "user" | "org";
};
A topic as a client names it: a scope, the session's id for a session, and optionally one resource under the scope. No user, org or tenant id.
Variables
COLLECTION_READ_MAX_PAGES
const COLLECTION_READ_MAX_PAGES: 1000 = 1000;
The most pages one collection read follows.
A guard against a transport that hands back a nextCursor forever, not a
size anyone is expected to reach: at the route's largest page (200 rows) it
covers 200,000 rows, when the collection honours the requested page size.
SESSION_WINDOW_PAGE
const SESSION_WINDOW_PAGE: 200 = 200;
Items a window reads from the newest end, and adds per readSessionEarlier.
topic
const topic: object;
The wire topic constructors. topic.session(id) watches one session,
topic.user() the caller's own user scope and topic.org() the caller's
organization. Each takes an optional { resource } to watch one resource
under the scope.
Type Declaration
org
readonly org: (options?) => WireTopic;
Parameters
options?
Returns
session
readonly session: (id, options?) => WireTopic;
Parameters
id
string
options?
Returns
user
readonly user: (options?) => WireTopic;
Parameters
options?
Returns
Functions
bindStoreToCallbacks()
function bindStoreToCallbacks(store, options?): RequestSSECallbacks;
Build the deduplicated RequestSSECallbacks reducer for a store. Each
callback mutates the store, then signals onChange only when a mutation
actually occurred (so filtered-out items and dropped out-of-order updates do
not schedule spurious flushes).
Parameters
store
options?
Returns
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
OutputItem
b
OutputItem
Returns
number
createClient()
function createClient(options): Client;
Build the one client. Another user or another server is another client.
Parameters
options
Returns
createRequestStreamStore()
function createRequestStreamStore<T>(options?): RequestStreamStore<T>;
Create a new imperative request-stream store. Pass RuntimeItem as T for
a store that holds trace rows; see RequestStreamStore.
Type Parameters
T
T extends RuntimeItem = OutputItem
Parameters
options?
Returns
createSSEClientFromResponse()
function createSSEClientFromResponse(options): RequestStreamHandle;
Creates a request-stream SSE client from an existing Response object. Used for inline streaming where the POST action response returns SSE directly instead of a 202 JSON response. This eliminates the need for a separate GET stream connection — essential on serverless platforms where POST and GET may hit different instances.
Parameters
options
CreateSSEClientFromResponseOptions
Returns
harnessLines()
function harnessLines<TOutcome>(sendOne?): HarnessLines<TOutcome>;
Keep one sender's lines in the order they were typed.
Each line waits for the one before it to have its answer. And once a line has gone to run after the running turn, the lines after it go the same way until the turn changes: steered into the running turn, a later line would reach the agent before the earlier one.
Type Parameters
TOutcome
TOutcome extends string = HarnessLineOutcome
Parameters
sendOne?
(prompt, running, sender) => Promise<TOutcome>
How one line is sent. Default sendHarnessLine.
Returns
HarnessLines<TOutcome>
interruptedBySession()
function interruptedBySession(requests, options): Map<string, InterruptedRequest[]>;
The interrupted requests of the named actions, by the session they ran in, oldest first in each. A request with no session is left out: there is no conversation to show it in.
Parameters
requests
readonly InterruptedRequest[]
What client.requests.interrupted() returned.
options
The app's turn actions.
Returns
Map<string, InterruptedRequest[]>
readEveryCollectionPage()
function readEveryCollectionPage(
source,
sessionId,
ref,
options?
): Promise<object[]>;
Every row of one collection, following nextCursor until the server stops
returning one.
Throws CollectionReadStoppedError when the server keeps returning cursors past COLLECTION_READ_MAX_PAGES pages, or returns a cursor it already sent. A page that fails rejects with that page's own error.
Parameters
source
Pick<ResourcesApi, "listCollectionResources">
sessionId
string
ref
string
options?
ReadEveryCollectionPageOptions
Returns
Promise<object[]>
readSessionEarlier()
function readSessionEarlier(
source,
window,
options?
): Promise<SessionItemsWindow>;
The window grown backward by up to limit earlier items, read again to
the session's end. A window that already starts at the beginning comes
back as it is, with no call.
Parameters
source
window
options?
Returns
Promise<SessionItemsWindow>
readSessionTail()
function readSessionTail(
source,
sessionId,
options?
): Promise<SessionItemsWindow>;
The session's newest limit items. A session that holds no more than that
is read in one call; a longer one takes a second, from its end.
Parameters
source
sessionId
string
options?
Returns
Promise<SessionItemsWindow>
refreshSessionWindow()
function refreshSessionWindow(source, window): Promise<SessionItemsWindow>;
The window read again from its start to the session's end: new items, and any item stored since among the ones it already held. For a view with no live feed; one that follows the session takes new items from the stream.
Parameters
source
window
Returns
Promise<SessionItemsWindow>
sendHarnessLine()
function sendHarnessLine(
prompt,
running,
sender
): Promise<HarnessLineOutcome>;
Send one line.
Parameters
prompt
string
The line, trimmed.
running
boolean
Whether a turn is running now, as the page last saw it. A turn that ended meanwhile offers nothing, so the line falls back to a turn.
sender
The flow's actions.
Returns
Promise<HarnessLineOutcome>
sessionFeed()
function sessionFeed(
client,
sessionId,
options?
): SessionFeed;
Follow one session. The feed starts at once and runs until SessionFeed.close; one feed holds one connection, so views that show the same session share the feed.
Parameters
client
sessions
Pick<SessionsApi, "state" | "stream">
sessionId
string
options?
Returns
sessionQueryFor()
function sessionQueryFor(address, flows):
| Pick<ListSessionsOptions, "flowId">
| Pick<ListSessionsOptions, "flowKind">;
The listing filter for one flow address.
A collection member's sessions are filed under its exact id: its rows record the definition's kind, not the address, so a kind filter would sweep in every sibling copy's sessions. A singleton lists by kind — its id is its kind, and the kind filter additionally finds sessions saved before owners were recorded, which the exact-owner filter never matches.
Exactly one of the two keys is returned, never both. The server intersects
them, so a helper that sent a flowKind alongside a flowId would silently
narrow the listing to rows that agree on both — which for a collection member
is none of them.
An address the flow list does not carry reads as a singleton. That is not a
fallback for an error case: useFlow builds its first listing before its own
listFlows has resolved, and a kind filter is what every flow was before
collection cardinality existed.
Parameters
address
string
flows
readonly Pick<FlowListEntry, "id" | "cardinality">[]
The flow list, or as much of it as the caller holds. Only id and
cardinality are read, and the parameter says so: a caller that has one
entry rather than the whole listing should not have to fabricate the
fields this function never looks at.
Returns
| Pick<ListSessionsOptions, "flowId">
| Pick<ListSessionsOptions, "flowKind">
steerRunningTurn()
function steerRunningTurn(client, options): Promise<{
live: boolean;
taken: boolean;
}>;
Send the flow's steer action and read its answer. It goes through client
on its own, not a session hook, so the stream following the running turn
stays on that turn. A steer that failed, or whose answer can't be read,
reads as not taken, so the line falls back to a turn.
Parameters
client
options
Returns
Promise<{
live: boolean;
taken: boolean;
}>
viewRef()
function viewRef<TView>(flow, view): ViewRef<TView>;
Name a view for the client. Pass the view's type for a typed answer:
viewRef<typeof roster>("workforce-roster", "roster").
Type Parameters
TView
TView extends ViewDefinition = ViewDefinition
Parameters
flow
string
view
string
Returns
ViewRef<TView>