@flow-state-dev/engine/host
Classes
ConcurrencyLeaseLostError
The reason a run is stopped when the place it held on a shared lease backend is lost: a renewal found the place gone, or no renewal landed for half the backend's lease. Past that point another process may take the key, so the run is stopped rather than left to overlap the next holder.
Extends
Error
Constructors
Constructor
new ConcurrencyLeaseLostError(key): ConcurrencyLeaseLostError;
Parameters
key
string
Returns
Overrides
Error.constructor
Properties
cause?
cause?: unknown;
Inherited from
Error.cause
key
readonly key: string;
message
message: string;
Inherited from
Error.message
name
name: string;
Inherited from
Error.name
stack?
stack?: string;
Inherited from
Error.stack
ConcurrencyQueueTimeoutError
Thrown when a queue request waits past its budget for the key to free up,
instead of hanging indefinitely. Carries an HTTP-shaped status (503) and
the contended key. Retryable with backoff.
Extends
Error
Constructors
Constructor
new ConcurrencyQueueTimeoutError(key, timeoutMs): ConcurrencyQueueTimeoutError;
Parameters
key
string
timeoutMs
number
Returns
Overrides
Error.constructor
Properties
cause?
cause?: unknown;
Inherited from
Error.cause
key
readonly key: string;
message
message: string;
Inherited from
Error.message
name
name: string;
Inherited from
Error.name
stack?
stack?: string;
Inherited from
Error.stack
status
readonly status: 503 = 503;
timeoutMs
readonly timeoutMs: number;
ConcurrencyRejectedError
Rejects the accepted and finished of the handle host.dispatch returns
(before any request record exists, and only once the caller's ownership of
the session has been checked) when an action's concurrency policy is
reject and another request already
holds the key (default: the session). Carries an HTTP-shaped status (409)
like PrincipalResolutionError, the contended key, and the in-flight
requestId so a caller may choose to tail the surviving request instead of
retrying. Fire-and-forget adapters (scheduled/webhook) map it to a benign
skipped response so the provider stops redelivering.
Extends
Error
Constructors
Constructor
new ConcurrencyRejectedError(key, inFlightRequestId?): ConcurrencyRejectedError;
Parameters
key
string
inFlightRequestId?
string
Returns
Overrides
Error.constructor
Properties
cause?
cause?: unknown;
Inherited from
Error.cause
inFlightRequestId?
readonly inFlightRequestId?: string;
key
readonly key: string;
message
message: string;
Inherited from
Error.message
name
name: string;
Inherited from
Error.name
stack?
stack?: string;
Inherited from
Error.stack
status
readonly status: 409 = 409;
LegacySessionlessRequestError
Raised when a stored request with no session would run again. Its own error so a log tells "this is a pre-upgrade row" apart from a failed run; the record is preserved unchanged.
Extends
Error
Constructors
Constructor
new LegacySessionlessRequestError(seam): LegacySessionlessRequestError;
Parameters
seam
string
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
reason
readonly reason: "legacy-sessionless-request";
seam
readonly seam: string;
stack?
stack?: string;
Inherited from
Error.stack
OrgBindingMismatchError
Thrown when a request supplies an orgId that doesn't match the org the
session was bound to at creation. Org binding is immutable for the lifetime
of a session — apps that need to "move" a session create a new one.
Extends
Error
Constructors
Constructor
new OrgBindingMismatchError(
sessionId,
sessionOrgId,
requestedOrgId
): OrgBindingMismatchError;
Parameters
sessionId
string
sessionOrgId
string
requestedOrgId
string
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
requestedOrgId
readonly requestedOrgId: string;
sessionId
readonly sessionId: string;
sessionOrgId
readonly sessionOrgId: string;
stack?
stack?: string;
Inherited from
Error.stack
OrgRequiredError
Thrown when TRUSTED code submits an identity with no usable organization
— a direct runAction, a pre-resolved adapter envelope, a CLI
seed, a queued job replayed from a durable substrate.
Distinct from PrincipalResolutionError, which answers an inbound caller and carries an HTTP status. This one answers the framework's own embedder, so it is layer-agnostic and carries no status: an adapter that chooses to expose a trusted-input failure over HTTP maps it to 400 itself. Reaching it means a call site skipped the resolver rather than that a caller failed to authenticate — which is why it names the seam, not the flow alone.
Extends
Error
Constructors
Constructor
new OrgRequiredError(flowKind, seam?): OrgRequiredError;
Parameters
flowKind
string
seam?
string
Returns
Overrides
Error.constructor
Properties
cause?
cause?: unknown;
Inherited from
Error.cause
flowKind
readonly flowKind: string;
message
message: string;
Inherited from
Error.message
name
name: string;
Inherited from
Error.name
stack?
stack?: string;
Inherited from
Error.stack
ReadonlySessionStateError
Thrown when a write would change a session's readonly state field: a
top-level .readonly() field of the flow's session stateSchema, set when
the session was created. Nothing is written.
Extends
Error
Constructors
Constructor
new ReadonlySessionStateError(
flowKind,
sessionId,
field
): ReadonlySessionStateError;
Parameters
flowKind
string
sessionId
string
field
string
Returns
Overrides
Error.constructor
Properties
cause?
cause?: unknown;
Inherited from
Error.cause
code
readonly code: "readonly-session-state" = "readonly-session-state";
field
readonly field: string;
flowKind
readonly flowKind: string;
message
message: string;
Inherited from
Error.message
name
name: string;
Inherited from
Error.name
sessionId
readonly sessionId: string;
stack?
stack?: string;
Inherited from
Error.stack
RequestOwnerMismatchError
Thrown when a dispatch reaches a request record, or an in-flight entry,
that another principal owns: a different user, tenant or organization
(context/request-principal.ts). Raised at every point a dispatch writes or
adopts a request record, before it does, so a request id can never move a
record from one user to another. The HTTP action route hands such a caller
its own id first; this is the refusal for the race it cannot see, and for
any other entry point. The message names the id only, never the owner.
Extends
Error
Constructors
Constructor
new RequestOwnerMismatchError(requestId): RequestOwnerMismatchError;
Parameters
requestId
string
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
requestId
readonly requestId: string;
stack?
stack?: string;
Inherited from
Error.stack
ResponseEmitter
Stateful request event emitter used by runtime execution and SSE transport.
Implements
ResponseEmitterHandle
Constructors
Constructor
new ResponseEmitter(options): ResponseEmitter;
Creates a request-scoped emitter instance.
Parameters
options
CreateInternalResponseEmitterOptions
Returns
Methods
addEventObserver()
addEventObserver(fn): void;
Registers an event observer that is called after each event is emitted. Used by the TTS pipeline to intercept content deltas for synthesis.
Parameters
fn
(event) => void
Returns
void
emit()
emit(event): Promise<void>;
Emits a draft request event if shape is valid; otherwise emits an internal debug event.
Item events (item.added, item.done) are routed through the tracking helpers
so that items are captured in getItems() and available for persistence/replay.
Parameters
event
unknown
Returns
Promise<void>
Implementation of
ResponseEmitterHandle.emit
emitContentAdded()
emitContentAdded(
itemId,
contentIndex,
content
): Promise<RequestStreamEventWithId>;
Emits a content-part added event for an item.
Parameters
itemId
string
contentIndex
number
content
Content
Returns
Promise<RequestStreamEventWithId>
emitContentAudioDelta()
emitContentAudioDelta(
itemId,
contentIndex,
chunk
): Promise<RequestStreamEventWithId>;
Emits a chunk of streaming TTS audio for an in-flight
OutputAudioContent part. Live-only — the chunk is delivered to wire
consumers and the in-memory buffer but excluded from getReplayableEvents
and the events-log persistence hook, mirroring the policy for text
content.delta. The durable representation is the eventual
OutputAudioContent snapshot delivered via emitContentAdded /
emitContentDone; chunks live only on the wire.
The emitter encodes raw bytes to base64 (the wire format is JSON SSE);
callers pass the Uint8Array from VoiceProvider.speakStream() directly.
Parameters
itemId
string
contentIndex
number
chunk
bytes
Uint8Array
isLast?
boolean
Returns
Promise<RequestStreamEventWithId>
emitContentDelta()
emitContentDelta(
itemId,
contentIndex,
delta
): Promise<RequestStreamEventWithId>;
Emits a content-part delta event for an item.
Parameters
itemId
string
contentIndex
number
delta
string
Returns
Promise<RequestStreamEventWithId>
emitContentDone()
emitContentDone(
itemId,
contentIndex,
content
): Promise<RequestStreamEventWithId>;
Emits a content-part done event for an item.
Parameters
itemId
string
contentIndex
number
content
Content
Returns
Promise<RequestStreamEventWithId>
emitDebug()
emitDebug(name, data): Promise<RequestStreamEventWithId>;
Emits a debug event.
Parameters
name
string
data
unknown
Returns
Promise<RequestStreamEventWithId>
emitItemAdded()
emitItemAdded(item): Promise<RequestStreamEventWithId>;
Emits an item-added event and tracks the item for later item views.
Parameters
item
RuntimeItem
Returns
Promise<RequestStreamEventWithId>
emitItemDone()
emitItemDone(item): Promise<RequestStreamEventWithId>;
Emits an item-done event and updates tracked item state.
Parameters
item
RuntimeItem
Returns
Promise<RequestStreamEventWithId>
emitItemOneShot()
emitItemOneShot(item): Promise<{
addedEvent: RequestStreamEventWithId;
doneEvent: RequestStreamEventWithId;
}>;
Emits item.added + item.done events for a single transient item without
tracking it in itemsById. The events reach connected clients via the
SSE stream and are persisted to the events log (the durable source for
replay). The item is NOT returned from getItems() and therefore never
enters the request-record items array — useful for large observability
payloads (e.g. full LLM prompts in block_debug) that would otherwise
balloon in-memory request state.
Tradeoff: one-shot items cannot be replayed from the in-memory response buffer after a reconnect — only from the events log store. For block_debug this is acceptable because a reconnecting client sees the next emission when the block re-resolves, and devtool replay reads from the events log anyway.
Parameters
item
RuntimeItem
Returns
Promise<{
addedEvent: RequestStreamEventWithId;
doneEvent: RequestStreamEventWithId;
}>
emitItemUpdated()
emitItemUpdated(itemId, patch): Promise<RequestStreamEventWithId | undefined>;
Emits an item.updated event applying a shallow top-level merge of
patch to the previously-emitted item. Identity-invariant keys
(id, type, provenance, itemVisibility, transient) are stripped
from the patch before it reaches the wire and before the server-side
mirror is updated.
Out-of-order resilience: if itemId is unknown (no prior item.added
for it on this emitter), nothing is emitted and a debug event is
recorded for diagnosis. Updates after item.done are applied normally,
except to a done transient item already dropped from the map (see
retainDoneItem), which counts as unknown.
Parameters
itemId
string
patch
Record<string, unknown>
Returns
Promise<RequestStreamEventWithId | undefined>
emitPing()
emitPing(): Promise<RequestStreamEventWithId>;
Emits a keepalive ping event.
Returns
Promise<RequestStreamEventWithId>
emitRequestCreated()
emitRequestCreated(): Promise<RequestStreamEventWithId>;
Emits the canonical request-created event.
Returns
Promise<RequestStreamEventWithId>
emitRequestStatus()
emitRequestStatus(status): Promise<RequestStreamEventWithId>;
Emits a request status transition event.
Parameters
status
RequestStatus
Returns
Promise<RequestStreamEventWithId>
emitResourceChange()
emitResourceChange(options): Promise<{
addedEvent: RequestStreamEventWithId;
changedEvent?: RequestStreamEventWithId;
doneEvent: RequestStreamEventWithId;
item: ResourceChangeItem;
}>;
Emits the standard resource change item lifecycle and optional request resource.changed event.
Parameters
options
changeType
"updated" | "created" | "deleted"
delta?
unknown
itemId?
string
itemIndex?
number
provenance?
ItemProvenance
resourcePath
string
scope
"request" | "session" | "user" | "org"
transient?
boolean
ts?
number
version?
number
Returns
Promise<{
addedEvent: RequestStreamEventWithId;
changedEvent?: RequestStreamEventWithId;
doneEvent: RequestStreamEventWithId;
item: ResourceChangeItem;
}>
getEvents()
getEvents(): RequestStreamEventWithId[];
Returns all emitted request events in emission order.
Returns
getItemCount()
getItemCount(): number;
O(1) next-itemIndex cursor. Used on the per-emit hot path to assign the
next item's index without materializing or ordering the items snapshot.
Includes baseItemIndex so a same-request continuation's re-entry items
continue after the prior persisted log; baseItemIndex is 0 on
a fresh run. Also counts items dropped from the map, so the
cursor never moves back and no index is reissued; a dropped keyed item
that is emitted again takes a new slot.
Returns
number
Implementation of
ResponseEmitterHandle.getItemCount
getItems()
getItems(): RuntimeItem[];
Returns current tracked items in stream (insertion) order.
The backing Map preserves first-insert order and re-sets (item.done /
item.updated) keep an item's original slot, so iteration order already
matches the emission sequence that itemIndex encodes. No read-time sort
— the previous Array.from(...).sort() ran on every emit via
getItemCount's former getItems().length, compounding to O(N² log N).
Done transient items beyond the newest maxBufferSize are not retained;
their events still reached the wire and the events log.
Returns
RuntimeItem[]
Implementation of
ResponseEmitterHandle.getItems
getLastEventId()
getLastEventId(): string | undefined;
Returns the most recently emitted event id.
Returns
string | undefined
getReplayableEvents()
getReplayableEvents(): RequestStreamEventWithId[];
Returns all replayable events (excludes ping, debug, content.delta, and content.audio.delta).
content.delta is reclassified as non-replayable: the running
text is checkpointed via MessageItem.content / ReasoningItem.summary
snapshots through the onItemUpdate hook instead.
content.audio.delta follows the same policy: the durable
representation is the eventual OutputAudioContent snapshot delivered
via content.added / content.done. Replaying per-chunk audio would
10–100x the event-log size for sub-second TTS without enabling any
client behavior that the snapshot doesn't already cover.
Returns
getSequenceNumber()
getSequenceNumber(): number;
Returns the latest request sequence number.
Returns
number
setEventHooks()
setEventHooks(hooks): void;
Registers hooks for incremental event persistence. Called after each replayable event with only the newly emitted event(s).
Parameters
hooks
ResponseEmitterEventHooks
Returns
void
setItemHooks()
setItemHooks(hooks): void;
Registers hooks that fire when items reach terminal status. Used by the execution layer for incremental item persistence.
Parameters
hooks
ResponseEmitterItemHooks
Returns
void
subscribeToItems()
subscribeToItems(listener, options?): () => void;
Subscribes to subsequent item lifecycle transitions on this emitter.
kind is "added" for fresh items, "updated" for in-place
mutations (item.updated and streaming content.delta), and "done" for
terminal status. Returns an idempotent unsubscribe — calling it more
than once is a no-op. Listener errors are isolated: a throw routes to
a debug event and other listeners still fire.
Fan-out uses snapshot semantics: the listener set is copied before iteration, so a listener that unsubscribes itself (or registers a new listener) mid-fan-out does not corrupt the in-flight loop. A listener registered during fan-out only sees subsequent events.
When options.filter is provided, the listener is skipped for events
the filter returns false for. Filter throws are caught and
the listener STILL fires (fail-open) — a filter that throws is a
caller bug; failing closed would silently produce 5-second
.waitForCondition timeouts with nothing in the trace explaining why.
Parameters
listener
(item, kind) => void
options?
filter?
(item, kind) => boolean
Returns
() => void
Implementation of
ResponseEmitterHandle.subscribeToItems
SessionCreateRefusedError
Thrown when a create is refused: the flow's create check said no, the
initial state failed the flow's stateSchema, or a caller seeded a
server-owned state field. Nothing was written. status is the HTTP status
the create route answers with; field names the state field when one was
the reason.
Extends
Error
Constructors
Constructor
new SessionCreateRefusedError(
sessionId,
status,
message,
field?
): SessionCreateRefusedError;
Parameters
sessionId
string
status
400 | 403 | 404
message
string
field?
string
Returns
Overrides
Error.constructor
Properties
cause?
cause?: unknown;
Inherited from
Error.cause
code
readonly code: "session-create-refused" = "session-create-refused";
field?
readonly field?: string;
message
message: string;
Inherited from
Error.message
name
name: string;
Inherited from
Error.name
sessionId
readonly sessionId: string;
stack?
stack?: string;
Inherited from
Error.stack
status
readonly status: 400 | 403 | 404;
SessionRequiredError
Thrown when a run is started with no session id: by runAction, the
inbound host's dispatch, or any other seam a run passes through. Every
run names its session, and an entry point that starts a run belonging to no
conversation makes a one-off id with oneOffSessionId() before it
dispatches. Thrown before anything is registered or written.
Like OrgRequiredError, it answers the framework's embedder and
carries no status; the HTTP action route answers a send with no session
400 { error: "session-required" } itself, before principal resolution.
Extends
Error
Constructors
Constructor
new SessionRequiredError(flowKind, seam?): SessionRequiredError;
Parameters
flowKind
string
seam?
string
Returns
Overrides
Error.constructor
Properties
cause?
cause?: unknown;
Inherited from
Error.cause
flowKind
readonly flowKind: string;
message
message: string;
Inherited from
Error.message
name
name: string;
Inherited from
Error.name
stack?
stack?: string;
Inherited from
Error.stack
StoreSubscriptionError
Subscription-time failures from a RequestStore.subscribeToEvents
iterator. liveness_timeout is internal — the iterator surfaces it as
a synthetic request.interrupted event rather than as an error.
Extends
FlowError
Constructors
Constructor
new StoreSubscriptionError(subCode, message?): StoreSubscriptionError;
Parameters
subCode
"backpressure_overflow" | "listen_unrecoverable"
message?
string
Returns
Overrides
FlowError.constructor
Properties
blockInstanceId?
readonly blockInstanceId?: string;
Inherited from
FlowError.blockInstanceId
blockName?
readonly blockName?: string;
Inherited from
FlowError.blockName
cause?
readonly cause?: unknown;
Inherited from
FlowError.cause
code?
readonly code?: string;
Inherited from
FlowError.code
details?
readonly details?: Record<string, unknown>;
Inherited from
FlowError.details
message
message: string;
Inherited from
FlowError.message
name
name: string;
Inherited from
FlowError.name
retryable
readonly retryable: boolean;
Inherited from
FlowError.retryable
scope?
readonly scope?: FlowErrorScope;
Inherited from
FlowError.scope
stack?
stack?: string;
Inherited from
FlowError.stack
subCode
readonly subCode: "backpressure_overflow" | "listen_unrecoverable";
Methods
isInstance()
static isInstance(err): err is FlowError;
Matches FlowError and its subclasses by instanceof, plus direct
FlowError instances (not subclasses) by name-tag. The name-tag
fallback exists for the dual-realm case where a bundler boundary
produced a duplicate FlowError identity; subclass realm-safety
additionally requires the caller to test the subclass's own name
(e.g. err.name === "OutputValidationError").
Parameters
err
unknown
Returns
err is FlowError
Inherited from
FlowError.isInstance
UnattributedOrgError
Raised when a stored record cannot be admitted because nobody ever recorded which organization it belongs to.
Deliberately its own error rather than a generic failure: an operator reading a log needs to tell "this data needs attributing" apart from "this caller was refused", because only one of them is fixed by a migration. The record is preserved untouched in every case.
Extends
Error
Constructors
Constructor
new UnattributedOrgError(seam): UnattributedOrgError;
Parameters
seam
string
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
reason
readonly reason: "migration-required";
Stable discriminator shared with the route layer's 409 body.
seam
readonly seam: string;
stack?
stack?: string;
Inherited from
Error.stack
UserBindingMismatchError
Thrown when a request supplies a userId that doesn't match the user the
session was created against. Closes a long-standing gap where the loaded
session record's userId was preserved without cross-checking the incoming
options.userId.
Raised at admission, before a run is registered or acknowledged
(runAction, and the transport host for a queued run), and again at
context creation for a session created in between. The HTTP action route
answers it as an unknown session. The message names the session only, never
its owner: it reaches the caller as the run's error item, and the caller is
the one user who must not learn whose the session is. sessionUserId still
carries the owner for server-side code.
Extends
Error
Constructors
Constructor
new UserBindingMismatchError(
sessionId,
sessionUserId,
requestedUserId
): UserBindingMismatchError;
Parameters
sessionId
string
sessionUserId
string
requestedUserId
string
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
requestedUserId
readonly requestedUserId: string;
sessionId
readonly sessionId: string;
sessionUserId
readonly sessionUserId: string;
stack?
stack?: string;
Inherited from
Error.stack
Interfaces
ActiveRequestRegistry
Properties
sharedAcrossProcesses?
readonly sharedAcrossProcesses?: boolean;
Whether entries written by one process are visible to every other process in the deployment.
Read it with isRegistrySharedAcrossProcesses, never directly: absent means NOT shared. An adapter compiled against the older contract declares nothing, and treating that silence as "shared" is precisely the wrong direction — a per-process registry makes another process's healthy request look absent, and absence reads as "not running".
Only the liveness enablement gate consumes this. An adapter that cannot tell
from its own construction — a filesystem or SQLite registry that might sit on
a shared volume or in a per-process temp dir — declares false. The answer
is a property of the CONSTRUCTED store, not of the adapter's package name.
Methods
deregister()
deregister(requestId): Promise<void>;
Remove a request from the registry. Called on terminal (success/failure).
Parameters
requestId
string
Returns
Promise<void>
get()
get(requestId): Promise<ActiveRequestEntry | undefined>;
Return a single entry by requestId, or undefined.
Parameters
requestId
string
Returns
Promise<ActiveRequestEntry | undefined>
heartbeat()
heartbeat(requestId): Promise<void>;
Update the heartbeat timestamp. Called on a periodic interval.
Parameters
requestId
string
Returns
Promise<void>
listAll()
listAll(): Promise<ActiveRequestEntry[]>;
Return all currently registered entries.
Returns
Promise<ActiveRequestEntry[]>
listStale()
listStale(thresholdMs): Promise<ActiveRequestEntry[]>;
Return all entries whose lastHeartbeatAt is older than Date.now() - thresholdMs.
Parameters
thresholdMs
number
Returns
Promise<ActiveRequestEntry[]>
register()
register(entry): Promise<void>;
Register a new in-flight request. Called at the start of runAction.
Parameters
entry
Returns
Promise<void>
BlobStore
Where a profile's attachment bytes live. Filled from the profile's blobs slot.
Properties
local
readonly local: boolean;
true when the bytes stay on this host (its disk or its memory), so
another instance of the app can't reach them. A host whose disk does not
last refuses uploads to such a store.
persists
readonly persists: boolean;
false when the bytes go when the process ends.
Methods
claim()
claim(id, claim): Promise<BlobClaimResult>;
Claim a held file into owner, for the uploader who holds it, on behalf
of send (an id the caller makes per message). A file owner already
holds is already-owned, and send is recorded as relying on it too.
Parameters
id
string
claim
owner
string
send
string
uploader
Returns
Promise<BlobClaimResult>
confirm()
confirm(
id,
owner,
send
): Promise<void>;
send was admitted: the file stays with owner whatever later sends do. Does nothing unless owner holds it.
Parameters
id
string
owner
string
send
string
Returns
Promise<void>
delete()
delete(id): Promise<boolean>;
Delete one file by id. Returns whether it existed.
Parameters
id
string
Returns
Promise<boolean>
deleteOwner()
deleteOwner(owner, options?): Promise<number>;
Delete every file owner holds. Returns how many went. keepUploader
spares the files that uploader claimed: a reborn session's purge keeps
the files its own first message just claimed.
Parameters
owner
string
options?
keepUploader?
Returns
Promise<number>
dispose()?
dispose?(): void | Promise<void>;
Release anything the store holds open.
Returns
void | Promise<void>
head()
head(id): Promise<BlobRecord | undefined>;
The record for id, or undefined.
Parameters
id
string
Returns
Promise<BlobRecord | undefined>
put()
put(input): Promise<BlobRecord>;
Store a new file, held for its uploader. A store also sweeps here:
uploads no message claimed within ATTACHMENT_LIMITS.unclaimedTtlMs go.
Parameters
input
Returns
Promise<BlobRecord>
read()
read(id): Promise<
| {
bytes: Uint8Array;
record: BlobRecord;
}
| undefined>;
The record and bytes for id, or undefined.
Parameters
id
string
Returns
Promise<
| {
bytes: Uint8Array;
record: BlobRecord;
}
| undefined>
release()
release(
id,
owner,
send
): Promise<void>;
send was refused before it ran: it no longer relies on the file. The
file goes back to its uploader only when no other send relies on it and
none was admitted with it. Does nothing unless owner holds it.
Parameters
id
string
owner
string
send
string
Returns
Promise<void>
ChangeBus
The bus an adapter backs.
Who hears a notice. A subscriber to a scope's topic with no resource
hears every notice under that scope, narrowed or not, and receives the
notice's own topic. A subscriber narrowed to a resource hears only notices
narrowed to that resource. Scope, id and tenant always match exactly.
Reconnects. A bus that lost its connection and got it back sends each
subscriber one notice of kind resync on its subscribed topic: it may have
missed some, so every subscriber reads once.
Properties
crossesProcesses
readonly crossesProcesses: boolean;
Whether a change made in any process that serves this app reaches this process's subscribers right now. The in-memory bus meets that because the app it serves runs as one process. May change at runtime; each change is delivered through ChangeBus.onCrossingChange.
Methods
onCrossingChange()
onCrossingChange(listener): () => void;
Hear each change of ChangeBus.crossesProcesses. Returns the unsubscribe. A bus whose answer never changes never calls it.
Parameters
listener
(crosses) => void
Returns
() => void
publish()
publish(notice): Promise<void>;
Send a notice. Called only after the change it names can be read. A failure is the bus's to report; it never fails the write that caused it.
Parameters
notice
Returns
Promise<void>
subscribe()
subscribe(topic, listener): () => void;
Hear the notices under topic (see "Who hears a notice"). Returns the
unsubscribe.
Parameters
topic
listener
Returns
() => void
CheckpointStore
Durable sequencer checkpoint store.
Latest-only persistence: identity is (requestId, blockInstanceId). Each
write overwrites any prior record. The Phase 2 resume runtime
reads the latest checkpoint to find the resume point — no enumeration
needed since identity is fully scoped.
GC is per-instance: each sequencer's terminal state_snapshot triggers a
delete for its own instance. No listForRequest / pruneBefore /
stepHistory — those are explicitly out of scope.
Properties
persists?
readonly persists?: boolean;
false when this store keeps nothing past the process. Absent means it persists.
Methods
delete()
delete(requestId, blockInstanceId): Promise<void>;
Remove the checkpoint when its sequencer reaches terminal state.
Parameters
requestId
string
blockInstanceId
string
Returns
Promise<void>
deleteForRequest()
deleteForRequest(requestId): Promise<void>;
Remove every checkpoint for requestId across all blockInstanceIds.
Idempotent — a request with no checkpoints is a no-op, never an error.
Parameters
requestId
string
Returns
Promise<void>
latest()
latest(requestId, blockInstanceId): Promise<SequencerCheckpoint | null>;
Read the latest checkpoint, or null if none exists.
Parameters
requestId
string
blockInstanceId
string
Returns
Promise<SequencerCheckpoint | null>
write()
write(checkpoint): Promise<void>;
Overwrite the latest checkpoint for this sequencer instance.
Parameters
checkpoint
SequencerCheckpoint
Returns
Promise<void>
ConcurrencyLeaseBackend
Ordered leases on a key, shared by every process of a deployment.
Holds no policy. Every call may throw when the backend cannot be reached; the arbiter then refuses the dispatch rather than running it unarbitrated.
Properties
leaseMs?
readonly leaseMs?: number;
How long a place lives past its last renewal, for a backend whose places
expire. With it, a running holder that cannot renew is stopped at half
the lease, so it has ended before another process can take the key.
Without it, only a renewal that answers false stops a holder.
Methods
giveBack()
giveBack(place): Promise<void>;
Remove the place. Idempotent. Wakes the next waiter on the key.
Parameters
place
Returns
Promise<void>
isMyTurn()
isMyTurn(place): Promise<boolean | "missing">;
True when this place is the first live place on its key. "missing" when
the key's line no longer has the place at all: a backend whose places
expire dropped it. The request behind it did not go away, so the engine
takes a new place for it, at the back of the line. A backend that answers
only true / false never re-admits a waiter.
Parameters
place
Returns
Promise<boolean | "missing">
renew()
renew(place): Promise<boolean | void>;
Extend the place's lease, for a backend whose places expire. The engine's
arbiter calls it every 2 seconds (more often under a short leaseMs) for
as long as its process holds the place: from take, through the
dispatch's writes, its wait for a turn and its run, until it gives the
place back or hands it to a job (whose worker then renews it). A lease a
few times longer than 2 seconds survives one missed renewal.
Answers false when the place is gone, so it can no longer be kept; a
running holder is then stopped. Any other answer, undefined included,
means the place was kept.
Parameters
place
Returns
Promise<boolean | void>
take()
take(input): Promise<LeaseTakeResult>;
Append a place to the key's line, or with ifEmpty claim only a free key.
Returns the current holder's request id instead when ifEmpty finds the
key held.
Not idempotent: each call appends a new place, even for a request id already on the line. The engine takes once per dispatch.
Parameters
input
Returns
Promise<LeaseTakeResult>
ContentStore
Separates resource content persistence from scope record persistence.
Content is addressed by (scopeType, scopeId, resourceKey). This allows adapters to store content independently of metadata — e.g., SQL metadata with blob storage for content, or individual files on the filesystem.
Methods
delete()
delete(
scopeType,
scopeId,
resourceKey
): Promise<void>;
Delete a single resource's content.
Parameters
scopeType
scopeId
string
resourceKey
string
Returns
Promise<void>
deleteAll()
deleteAll(scopeType, scopeId): Promise<void>;
Delete all content for a scope instance. Used during scope record deletion.
Parameters
scopeType
scopeId
string
Returns
Promise<void>
get()
get(
scopeType,
scopeId,
resourceKey
): Promise<string | undefined>;
Read a single resource's content.
Parameters
scopeType
scopeId
string
resourceKey
string
Returns
Promise<string | undefined>
getAll()
getAll(scopeType, scopeId): Promise<Record<string, string>>;
Read all content for a scope instance. Used during state route reads (full-scope view).
Parameters
scopeType
scopeId
string
Returns
Promise<Record<string, string>>
getByPrefix()
getByPrefix(
scopeType,
scopeId,
keyPrefix
): Promise<Record<string, string>>;
Read every content entry in a scope whose resourceKey starts with
keyPrefix. The match is on the start of the key string: whole path
segments (notes/shared/) or part of a name (notes/sh); / is not
special. An empty keyPrefix returns all keys in the scope
(equivalent to getAll). Used during context initialization to load
only the content a flow declares — fixed resources by exact key, and
collections by their pattern prefix.
Parameters
scopeType
scopeId
string
keyPrefix
string
Returns
Promise<Record<string, string>>
set()
set(
scopeType,
scopeId,
resourceKey,
content
): Promise<void>;
Write a single resource's content. Creates or overwrites.
Parameters
scopeType
scopeId
string
resourceKey
string
content
string
Returns
Promise<void>
ContinueRequestOptions
Properties
flowRegistry
flowRegistry: FlowRegistry;
includeTrace?
includeTrace?: boolean;
Forward trace-channel items (block_trace/router_decision/
state_snapshot) on the created live stream instead of filtering them
out. Only takes effect when responseEmitter is not supplied (a BYO
emitter's owner controls forwarding). Default false.
requestId
requestId: string;
The suspended/interrupted request to continue, re-entered under this id.
responseEmitter?
responseEmitter?: ResponseEmitter;
Bring-your-own emitter. When provided, no LiveRequestStream is created and
liveStream is null on the result (the caller owns streaming).
resumeContext?
resumeContext?: ResumeContext;
The resolution to inject — which gate, approve/reject, payload, resolver.
runtimeConfig
runtimeConfig: RuntimeConfig;
signal?
signal?: AbortSignal;
startRun?
startRun?: (run, start) => Promise<ExecutionResult>;
Gates start once the live stream and the active-request entry exist.
start's signal also stops the run. Absent, the run starts at once.
Parameters
run
flow
FlowInstance
orgId
string
record
sessionId
string
start
(signal?) => Promise<ExecutionResult>
Returns
Promise<ExecutionResult>
stores
stores: StoreRegistry;
ContinueRequestResult
Properties
finished
finished: Promise<ExecutionResult>;
Resolves when the continued run reaches a terminal (or re-suspended) state.
liveStream
liveStream: LiveRequestStream | null;
Live SSE stream for the re-entry, or null when a responseEmitter was supplied.
requestId
requestId: string;
The continued request's id — the SAME id that was passed in.
CreateBearerSecretPrincipalResolverOptions
Properties
headerName?
headerName?: string;
HTTP header name to read. Default: "authorization". Header lookup
is case-insensitive (the underlying Headers API normalizes names).
principal
principal: ResolvedPrincipal;
Principal returned on a successful match. Typically a system user
({ userId: "system" }) when the resolver fronts a scheduled or
webhook transport.
secret
secret: string;
Shared bearer secret. Compared in constant time against the token extracted from the request header.
CreateFlowStateOptions
Type Parameters
TSettings
TSettings extends object = FlowStateSettings
Properties
adapters?
adapters?: InboundTransportAdapter[];
Forwarded to createFlowApiRouter for power users (custom transports).
chat?
chat?: object;
Interactive-harness defaults. chat.default is the target fsdev chat
binds when started with no positional flow — "<flowKind>" (its sole
action) or "<flowKind>.<action>". A host-level default target for the
CLI, not a flow-level option.
default?
default?: string;
debugAllowAnonymousLocal?
debugAllowAnonymousLocal?: boolean;
Forwarded to createFlowApiRouter. Admit Origin-less requests to the
debug endpoints. Default false (falls back to
FSDEV_DEBUG_ALLOW_ANONYMOUS_LOCAL=1); only for a loopback-bound server.
debugEndpointsEnabled?
debugEndpointsEnabled?: boolean;
defaultProfile?
defaultProfile?: string;
Which profile is active at runtime. Resolution chain (first match wins):
process.env.FSD_ENV → this value → first declared profile. NODE_ENV
is intentionally not consulted.
defaultSseHeartbeatMs?
defaultSseHeartbeatMs?: number;
detectInterruptedOnStartup?
detectInterruptedOnStartup?: boolean;
Whether to detect interrupted requests from previous runs on startup. Disable on serverless (background queries on cold start can exhaust the pool before real requests are served). Default: true.
devtool?
devtool?: DevToolConnectionConfig;
How fsdev dev should connect DevTool to this app. fsdev dev reads this
and injects it into the DevTool page (served over loopback), so a secured
flow is debuggable without hand-editing DevTool settings: userId becomes
DevTool's session identity and bearerToken is sent as
Authorization: Bearer on every flow request. It is a DEV convenience —
only fsdev dev reads it; the production serve/deploy paths ignore it.
dispatchDrainTimeoutMs?
dispatchDrainTimeoutMs?: number;
How long dispose() waits for detached work running IN THIS PROCESS before
shutting down anyway. Default: 30000 (30s). Queue-backed work is never
waited for and this does not apply to it.
A ceiling, not a target: work that finishes sooner is never delayed. When it expires, shutdown proceeds and reports the request and session ids it did not wait out, so abandoned work is named rather than silently dropped.
Configurable because the two callers have genuinely different tolerances and
no single number serves both well. A server disposing under a termination
signal lives inside a platform grace period (commonly 30s) and cannot
usefully exceed it — the process is killed regardless. A fsdev run
verifying a slow flow has no such ceiling and may reasonably wait longer for
an agent turn to finish, since watching that finish is the point of the run.
The default is set for the first, because exceeding it there is futile;
raise it for the second.
0 disables waiting entirely — a legitimate choice for a host that wants
immediate shutdown, and it still reports what it left behind.
durabilityRetention?
durabilityRetention?: DurabilityRetentionConfig;
Retention policy for the durability sweeper. Takes effect
wherever durable execution is on: by default over persisting stores, or
with durable: true. Enforces
suspension expiry and prunes aged-out suspensions, leases, and orphaned
checkpoints on a cadence.
durable?
durable?: boolean;
Durable execution for this host. On by default when the
resolved stores persist (filesystem, SQLite, Postgres): createFlowState
builds the default createCheckpointDurabilityProvider from its own
resolved stores, so sequencers checkpoint, a crashed request resumes, and
ctx.suspend() holds a request until it is answered. Off by default over
in-memory stores, where a suspension would be lost with the process.
false opts out; true forces it on over in-memory stores too (tests).
The rule is resolveDurabilityProvider.
Power users needing a custom DurabilityProvider should use the
lower-level createFlowApiRouter (which accepts one via runtimeConfig).
errorCapture?
errorCapture?: ErrorCaptureHandler;
Opt-in error-capture sink. Routes runtime block failures (tool
errors, generator failures, handler exceptions) to an external
observability service. Distinct from onError, which is an HTTP-level sink:
errorCapture is block-aware and receives the failing block's identity plus
the flow / request / session / user IDs. Provider-neutral — the operator
writes the adapter; the framework ships no provider SDK. Off by default.
fill?
fill?: Readonly<Record<string, unknown>>;
The app's own entries for the kits' slots, by slot key:
fill: { [harnesses.slots.harnesses]: [codexHarness(), cursorHarness()] }.
A keyed slot takes a record, or a list of entries each keyed by its id;
a list slot gets the app's entries last.
flows?
flows?: readonly FlowInstance<any, any>[];
Flows to register, as a list. Each is served under its own flow.id
(its kind unless the instance was given another); two with one id are
refused.
jobQueue?
jobQueue?: JobQueueAdapter;
Job queue adapter (e.g. bullmqJobQueue(...) from
@flow-state-dev/bullmq). Wires the enqueue side and/or the processing
side per the adapter's mode, both against the same resolved runtime.
Processing starts on first ready() / getRouter() /
getRuntime() — call ready() eagerly in processes that must consume
the queue from boot. Mutually exclusive with runner.
kits?
kits?: readonly KitInstance[];
Kits to install, each a kit's factory called with its config, in any
order: kits: [harnesses({}), workforce({ model })]. They install in
requires order, each slot filled once from the kits that require its
owner; their flows are served beside flows.
An order nobody can satisfy, a slot filled twice under one key, a fill by
a kit that doesn't require the slot's owner and an entry its slot's schema
refuses throw here. Each kit's folder is read at start-up, and any file in
it no reader used rejects ready() and every request, naming each file.
maxChildSessionListLimit?
maxChildSessionListLimit?: number;
Largest limit the child-session listing route accepts. Default 100.
Raise it for deployments whose conversations start more child sessions than that: the list a client reads is all-time history, so any fixed ceiling eventually hides the oldest finished work. Raise it deliberately — each row resolves its status from the request store and clients re-read the list on every interaction, so a larger ceiling costs more per turn.
maxDebtAgeMs?
maxDebtAgeMs?: number;
How long past its due time a debt may stay outstanding before a pass ends it, settled undeliverable and logged. Only takes effect with durable execution and a store that keeps wakes. Default 24 hours.
modelResolver?
modelResolver?: ModelResolver;
Escape hatch: a pre-built model resolver. When provided, it is used
instead of building one from models — for test mocks
(createMockModelResolver) or fully custom resolvers.
models?
models?: FlowStateModelsConfig;
Model resolver config. Auto-wires AI Gateway via AI_GATEWAY_API_KEY.
noticeIds?
noticeIds?: NoticeIdScopes;
Which topic scopes' change notices may name what changed (a task, an
entry, a session). On by default; { org: false } sends no org notice to
a browser with ids or a collection entry's key, where even an org's change
timing is sensitive. Read by every push edge of the app.
onBackgroundWork?
onBackgroundWork?: (promise) => void;
Background-work keep-alive hook. On serverless platforms that freeze the
function after the response (Vercel), pass the platform's post-response
primitive — e.g. (p) => after(() => p) from next/server — so
fire-and-forget work (scheduled dispatches, post-202 action execution)
isn't killed mid-flight. Platform-agnostic, so it's a createFlowState
option rather than baked into an adapter: the router is built here, and a
downstream handler can't inject it after construction.
Parameters
promise
Promise<unknown>
Returns
void
onError?
onError?: (error, context) => void;
HTTP-level error sink. Receives { method, path } context.
Parameters
error
Error
context
method
string
path
string
Returns
void
publicReentrySources?
publicReentrySources?: readonly string[];
Transport sources this deployment adds to the public re-entry allow-list
for retry, continue and resume.
Name the sources your own out-of-tree InboundTransportAdapters stamp —
without this they are refused with a not-found, because a source the
framework cannot enumerate is refused by default. webhook and the
detached-dispatch source are refused: neither is caller-addressed, so
re-entering one from a public route would run it with caller-supplied
input. Default: only the built-in sources.
queuedGraceMs?
queuedGraceMs?: number;
How long an externally-queued request may sit unclaimed before a sweep
treats it as lost (ms). A queued request has no heartbeat, so
staleSweepThresholdMs cannot answer for it. Raise this when a legitimate
backlog can outlast the default. Must be finite and non-negative — it is the
only bound on a queued entry, so a value nothing can exceed would leave a
lost job reported live indefinitely. Default 600000 (10 minutes).
resolvePrincipal?
resolvePrincipal?: ResolvePrincipalFn;
Host-level fallback principal resolver, used when an inbound flow has no
authentication.resolvePrincipal of its own. Per-flow auth always wins.
root?
root?: string | URL;
The app's folder, which a kit's default folder is read against: a path,
or a URL such as import.meta.url (its directory). Defaults to the
working directory. A directory given in a kit's config reads against
the working directory instead.
runner?
runner?: FlowRunner;
Low-level escape hatch: a pre-built FlowRunner controlling where
flow actions execute. Default: in-process (runAction called directly).
Most deployments should use jobQueue instead — it wires the runner
AND the processing side from one adapter. Mutually exclusive with
jobQueue.
scheduler?
scheduler?: false | SchedulerAdapter;
When the app's schedules fire. Omitted: the built-in local cron, which
ticks each minute in a process that builds the router (ready(),
getRouter(), a server) or starts a job queue's processing, when a
registered flow declares static schedules or a schedule index. A lease in
stores.leases elects one process to tick across a deployment that
shares its store. false: nothing fires the tick. An adapter (a host's
cron route) fires it itself.
sealingSecret?
sealingSecret?: string;
The host's secret for sealing what it hands a client to send back unread
(RuntimeConfig.sealingSecret): today a read across sessions' cursor.
Default: process.env.FSD_SEALING_SECRET. Set the same secret on every
process behind one address.
settings?
settings?: TSettings;
Instance-level configuration read inside blocks via ctx.settings.
Typed via the TSettings generic (declaration-merged in user code into
the FlowStateSettings interface).
staleSweepIntervalMs?
staleSweepIntervalMs?: number;
Stale-request sweeper cadence (ms). 0 disables. Default 30000.
staleSweepThresholdMs?
staleSweepThresholdMs?: number;
Heartbeat-age threshold (ms) for the stale-request sweeper. Default 60000.
stores?
stores?:
| StoreAdapter
| StoresConfig;
Where the app keeps its data. Three shapes:
- omitted: in memory, as the
defaultprofile. Nothing persists across a restart; startup says so, and production warns. - one adapter (
sqliteStores({ filename })): thedefaultprofile'sprimary, exactly{ default: { primary: adapter } }. - named profiles, each a map of capability slots, for an app that picks a
store per environment (
defaultProfile,FSD_ENV). At least one.
userDeadlineMs?
userDeadlineMs?: number;
The deadline a stop that waits for a user gets when it names none:
every ctx.suspendForUser without a deadline, and every held
question. Unset by default, so such a stop waits until it is answered,
stopped or cancelled. One second to 365 days.
voice?
voice?: FlowStateVoiceConfig;
Voice providers (speech / transcription).
waitDeadlines?
waitDeadlines?: object;
A wait's deadline bounds: the deadline a wait that names none gets (default five minutes), and the shortest and longest one may name (default one second and 24 hours). Only takes effect with durable execution and a store that keeps wakes.
defaultMs?
defaultMs?: number;
maxMs?
maxMs?: number;
minMs?
minMs?: number;
CreateHmacVerifierOptions
Properties
algorithm?
algorithm?: HmacAlgorithm;
Hash algorithm. Default: sha256.
encoding?
encoding?: HmacEncoding;
Signature encoding. Default: hex.
format?
format?: "raw" | "stripe" | "custom";
Header format. raw matches [prefix=]<sig>; stripe matches
t=<ts>,v1=<sig>[,vN=<sig>...]. For other formats, pass custom and
supply parseSignature.
now?
now?: () => number;
Clock used for timestamp tolerance checks. Test seam.
Returns
number
parseSignature?
parseSignature?: HmacSignatureParser;
Custom parser when format: "custom". Required in that mode. Receives
the raw header value, returns the parsed signature(s) or null if the
header is malformed. Returning null causes verification to fail.
prefix?
prefix?: string;
Signature prefix for raw format (e.g. sha256= for GitHub). Stripped
before comparison. Ignored when format is not raw. Default: empty.
secret
secret: string;
Shared secret used to compute the HMAC.
toleranceSeconds?
toleranceSeconds?: number;
For stripe format: maximum allowed age (seconds) of the signed
timestamp. Older timestamps are rejected even if the signature
matches, defending against replay. Default: 300 (5 minutes). Set to
Infinity to disable.
CreateHs256JwtVerifierOptions
Properties
audience?
audience?: string | string[];
Allowed aud value(s). When set, tokens whose aud doesn't intersect
the list are rejected. Tokens with no aud claim are rejected when
this option is present.
clockSkewSeconds?
clockSkewSeconds?: number;
Maximum allowed clock skew (seconds) when checking exp and nbf.
Default: 0. Increase for distributed-system tolerance.
issuer?
issuer?: string | string[];
Allowed iss value(s). When set, tokens whose iss is missing or not
in the list are rejected.
now?
now?: () => number;
Clock used for expiration checks. Test seam.
Returns
number
secret
secret: string;
Shared secret used to compute the HS256 signature.
CreateWebhookTransportAdapterOptions
Properties
basePath?
basePath?: string;
Base path for webhook routes. Default "/api/flows".
providers
providers: Record<string, WebhookProviderDefinition>;
Provider mechanics, keyed by provider name (the :provider URL segment).
CreateWebhookVerifierOptions
Extends
Omit<CreateHmacVerifierOptions,"secret">
Properties
algorithm?
algorithm?: HmacAlgorithm;
Hash algorithm. Default: sha256.
Inherited from
CreateHmacVerifierOptions.algorithm
encoding?
encoding?: HmacEncoding;
Signature encoding. Default: hex.
Inherited from
CreateHmacVerifierOptions.encoding
format?
format?: "raw" | "stripe" | "custom";
Header format. raw matches [prefix=]<sig>; stripe matches
t=<ts>,v1=<sig>[,vN=<sig>...]. For other formats, pass custom and
supply parseSignature.
Inherited from
CreateHmacVerifierOptions.format
header
header: string;
Request header carrying the signature, e.g. "stripe-signature".
now?
now?: () => number;
Clock used for timestamp tolerance checks. Test seam.
Returns
number
Inherited from
parseSignature?
parseSignature?: HmacSignatureParser;
Custom parser when format: "custom". Required in that mode. Receives
the raw header value, returns the parsed signature(s) or null if the
header is malformed. Returning null causes verification to fail.
Inherited from
CreateHmacVerifierOptions.parseSignature
prefix?
prefix?: string;
Signature prefix for raw format (e.g. sha256= for GitHub). Stripped
before comparison. Ignored when format is not raw. Default: empty.
Inherited from
CreateHmacVerifierOptions.prefix
secret
secret: string | (() => string);
Shared secret, or a getter resolved lazily on first use.
toleranceSeconds?
toleranceSeconds?: number;
For stripe format: maximum allowed age (seconds) of the signed
timestamp. Older timestamps are rejected even if the signature
matches, defending against replay. Default: 300 (5 minutes). Set to
Infinity to disable.
Inherited from
CreateHmacVerifierOptions.toleranceSeconds
DevToolConnectionConfig
DevTool connection config declared in fsdev.config.ts (see
CreateFlowStateOptions.devtool). Both fields are optional so an app
can set just the identity, just the token, or both.
Properties
bearerToken?
bearerToken?: string;
Bearer token DevTool sends as Authorization: Bearer <token> on flow
requests — the credential a bearer-gated flow's resolver validates. Read a
secret from the environment here (e.g. process.env.KH_MCP_SECRET); it is
exposed only to the loopback DevTool page fsdev dev serves.
userId?
userId?: string;
Identity DevTool creates sessions and dispatches actions as.
DispatchEnvelope
Serializable subset of InboundRequestEnvelope — everything a remote worker needs to call runAction.
Properties
actionName
actionName: string;
attachments?
attachments?: FileContent[];
The person's files, in reference form: plain data, so they ride a queue.
See InboundRequestEnvelope.attachments. == null → none, as on a job
enqueued before this field existed.
flowKind
flowKind: string;
The address of the flow instance this request is for — its exact id
(a singleton's kind, or a collection member's explicit id). The field
keeps its historical name; the value is what the receiving process hands
to FlowRegistry.get. A collection's bare kind is not an address and
resolves nothing on either side of a queue.
input
input: unknown;
leasePlace?
leasePlace?: LeasePlace | null;
The run's place on its concurrency key, taken by the dispatching host before the job was enqueued. Present only when the host arbitrates external dispatch over a backend the worker shares: the worker waits for the place's turn before running and gives it back when the job is done for good.
== null → no place: a job from a host that does not arbitrate, or one
enqueued before this field existed. It runs as it always did.
The place can be gone from the line by the time the worker reads it: the
host gives it back when the enqueue fails, and a failure can be ambiguous
(the queue accepted the job but the acknowledgement was lost), or its lease
can lapse. A worker must not run under a place that is no longer on the
line. The four-call contract cannot yet tell such a place from one still
waiting (isMyTurn answers false for both), so how a worker recovers an
orphaned job is not settled here; it is designed with the first shared
backend.
leaseTurn?
leaseTurn?: LeaseTurn | null;
How the job reaches its turn, when not by waiting in line for
leasePlace. Set by the host from the entry's policy:
{ kind: "now" }—hold:leasePlacehas its turn already. The worker runs the job at once, renews the place while it runs, and gives it back when the job is done for good.{ kind: "when-free", key }—defer: no place yet. The worker claimskeyonly once nothing holds or waits on it, yielding to newer runs for at most the patienceplanDeferWaitsets, then lining up behind the places on the key.
== null → leasePlace, if any, waits its turn in line (queue,
reject), as a job from a release before this field does.
metadata?
metadata?: Record<string, unknown>;
orgId
orgId: string;
The organization the run belongs to. Required: a runner
hands work to a worker that runs BELOW principal resolution, so the
envelope is the only place that worker can learn the organization from.
A durable job written before this field existed is refused on the way
back in rather than run without one — see context/org-attribution.ts.
principalKind?
principalKind?: PrincipalKind;
The kind of the principal the run runs as, as its door set it
(context/principal.ts). == null on a job enqueued before the field, or
from a caller that assembled its envelope without a door: the run then
reads its request record's, then its session's, and is a machine's
without either.
requestId
requestId: string;
resolvedActionCore?
resolvedActionCore?: ActionCore;
Pre-resolved action core for an event dispatch with no static coordinate
(the dynamic schedule). NOT serializable — a block cannot cross a queue
boundary — so the host runs a dispatch carrying it on the in-process
runner even when an external runner (BullMQ) is installed; an external
runner is never handed one. Consistent with dynamic schedules being
non-recoverable. See InboundRequestEnvelope.resolvedActionCore.
resolvedBy?
resolvedBy?: string;
The resolver identity that produced the principal (Principal.resolvedBy). == null → none, which matches nothing.
sessionId
sessionId: string;
The session the run lands in: always set by the host, which refuses an envelope with none.
source?
source?: string;
tenantId?
tenantId?: string;
userId
userId: string;
DurabilityProvider
Methods
acquireLease()
acquireLease(requestId, options): Promise<Lease | null>;
Attempt to acquire an exclusive lease for resuming a request. Returns the lease on success, null if already held by another holder.
Parameters
requestId
string
options
Returns
Promise<Lease | null>
cleanup()
cleanup(requestId): Promise<void>;
Clean up durability artifacts for a completed request: suspension records and leases. Called when a durable request reaches a final terminal status (completed/failed). Checkpoint cleanup is controlled separately via request.cleanupCheckpointsOnTerminal.
Parameters
requestId
string
Returns
Promise<void>
cleanupCheckpoints()
cleanupCheckpoints(requestId): Promise<void>;
Delete all checkpoints for a request (delegates to CheckpointStore.deleteForRequest).
Parameters
requestId
string
Returns
Promise<void>
listSuspended()
listSuspended(filter?): Promise<SuspensionRecord[]>;
List suspended requests matching a filter.
Parameters
filter?
SuspensionFilter
Returns
Promise<SuspensionRecord[]>
loadCheckpoint()
loadCheckpoint(requestId, blockInstanceId): Promise<SequencerCheckpoint | null>;
Load the latest checkpoint for a sequencer instance.
Parameters
requestId
string
blockInstanceId
string
Returns
Promise<SequencerCheckpoint | null>
loadSuspension()
loadSuspension(requestId, suspensionId): Promise<SuspensionRecord | null>;
Load a specific suspension by ID.
Parameters
requestId
string
suspensionId
string
Returns
Promise<SuspensionRecord | null>
pruneSuspensions()
pruneSuspensions(cutoffMs, limit): Promise<number>;
Prune terminal suspensions resolved before cutoffMs, up to limit.
Returns the count deleted (delegates to SuspensionStore.pruneTerminalBefore).
Parameters
cutoffMs
number
limit
number
Returns
Promise<number>
releaseLease()
releaseLease(requestId, leaseId): Promise<void>;
Release a previously acquired lease.
Parameters
requestId
string
leaseId
string
Returns
Promise<void>
saveCheckpoint()
saveCheckpoint(checkpoint): Promise<void>;
Persist a checkpoint at a sequencer step boundary.
Parameters
checkpoint
SequencerCheckpoint
Returns
Promise<void>
suspend()
suspend(record): Promise<void>;
Create a suspension record when ctx.suspend() is called.
Parameters
record
SuspensionRecord
Returns
Promise<void>
DurabilityRetentionConfig
Retention policy for the durability sweeper. Every field is optional; the sweeper resolves the documented defaults when a value is absent.
Properties
batchLimit?
batchLimit?: number;
Max records deleted per store per tick (batch budget). Default 1000.
checkpointMaxAgeMs?
checkpointMaxAgeMs?: number;
Backstop max-age (ms) for checkpoints of TERMINAL requests (completed/failed/aborted) whose cleanup never fired. Default 86_400_000 (24h). Checkpoints of in_progress/suspended requests are NEVER pruned by age.
orphanCheckpointThresholdMs?
orphanCheckpointThresholdMs?: number;
Max-age (ms) past a non-terminal (interrupted) request's last activity before its checkpoints are considered orphaned and eligible for pruning. Default 86_400_000 (24h).
suspensionTerminalMaxAgeMs?
suspensionTerminalMaxAgeMs?: number;
Retention window (ms) for resolved suspensions, measured from resolvedAt. Default 604_800_000 (7d).
sweepIntervalMs?
sweepIntervalMs?: number;
Sweep cadence (ms). 0 or negative disables the sweeper. Default 600_000 (10min).
FlowRegistry
Methods
describeSharedSchemas()
describeSharedSchemas(): SharedSchemasDescription;
Merged cross-flow schema view — what each scope's shared storage looks like once isolated declarations are excluded. Diagnostics and devtool surfaces consume this.
Returns
get()
get(address): FlowInstance | undefined;
Resolve an instance by its exact global id, or undefined. A singleton
answers to its kind (that is its id); a collection member answers to its
explicit id only. Nothing is guessed from an incomplete address.
Parameters
address
string
Returns
FlowInstance | undefined
indexedCollections()
indexedCollections(): readonly IndexedCollection[];
Every collection that declares indexes, across every flow this registry
has admitted, unregistered ones included. The runtime's index writer
computes each write's entries from it.
Returns
readonly IndexedCollection[]
list()
list(): FlowInstance[];
Every admitted instance, ordered by kind then id. Built-in instances are not listed.
Returns
FlowInstance[]
pinOf()
pinOf(id): InstanceOwnerPin | undefined;
The owner pin on the instance at this address, or undefined when the
instance is shared or the address is not held. Reads FlowInstance.ownerPin.
Parameters
id
string
Returns
InstanceOwnerPin | undefined
register()
register(flow, options?): void;
Admit one instance. Throws FlowIdentityConflictError for a
duplicate id, a singleton under a custom id, or a mixed-cardinality kind,
CrossFlowSchemaConflictError for a schema conflict, and an Error
when the owner-private fence refuses a collection or a single resource
keyed with a segment beginning ~ (see the file header) — in every case
before any registry state is touched.
options.pin pins the instance to an owner, { orgId, userId? }.
Omitted, a pin already on the instance is kept; otherwise the instance is
shared. A second pin that disagrees with the one on the instance is
refused.
Parameters
flow
FlowInstance
options?
pin?
InstanceOwnerPin
Returns
void
registerBuiltIn()?
registerBuiltIn?(flow): void;
Hold one of the framework's own instances at its address: get answers
it, list never shows it, so no catalog, listing or tool surface offers
it. Idempotent per address; a held user instance at that address wins.
Optional so a hand-built registry needs none.
Parameters
flow
FlowInstance
Returns
void
registerMany()
registerMany(flows): void;
register, in order. An element that fails leaves the earlier ones admitted.
Parameters
flows
FlowInstance[]
Returns
void
unregister()
unregister(id): boolean;
Release one address. true when an instance was holding it, false when
nothing was — an unknown id is an ordinary answer, not an error, because
the caller's question is "is this address free now" and both answers are
yes.
The kind keeps its worker in the cross-flow schema view, even when this removes its last instance — see InMemoryFlowRegistry.unregister.
Parameters
id
string
Returns
boolean
FlowRunner
Controls where flow actions execute. Implementations:
- InProcessRunner (default) — calls runAction in the current process
- WorkerRunner (BullMQ) — enqueues to a BullMQ queue, subscribes via bridge
- Future: TriggerDevRunner, PgBossRunner
Methods
close()
close(): Promise<void>;
Returns
Promise<void>
dispatch()
dispatch(envelope, bridge?): Promise<RunnerHandle>;
Parameters
envelope
bridge?
Returns
Promise<RunnerHandle>
FlowStateModelsConfig
Model-resolver config, re-shaped for the FlowState surface.
Properties
default?
default?: string;
Concrete fallback model when an intent/<name> string can't resolve.
gateways?
gateways?: Record<string, unknown>;
intents?
intents?: Record<string, string[]>;
Named intent ladders — each is an ordered list of candidate model ids.
keys?
keys?: Partial<Record<string, string>>;
providerPreference?
providerPreference?: ProviderPreference;
providers?
providers?: Record<string, unknown>;
retryPolicy?
retryPolicy?: ModelRetryPolicy;
FlowStateRuntime
The runtime internals of a FlowState, resolved alongside the router.
Off-transport consumers — background workers, queue processors, scripts —
need these directly rather than reaching through the HTTP router. The shape
is exactly what a job queue runtime's createJobProcessor(deps) consumes.
Properties
chat?
chat?: object;
Interactive-harness defaults forwarded from createFlowState options.
default?
default?: string;
registry
registry: FlowRegistry;
The flow registry built from the configured flows.
resolvePrincipal
resolvePrincipal: ResolvePrincipalFn;
The host-level resolver the router's host is given (createFlowState's
resolvePrincipal, else the development resolver). A worker hands it to
the built-in flows it holds, so the default write flow decides whether
two declarations agree exactly as the host does.
runtimeConfig
runtimeConfig: RuntimeConfig;
The forwarded instance-level runtime configuration bundle.
stores
stores: StoreRegistry;
The resolved store registry for the active profile; stores are open.
FlowStateVoiceConfig
Voice configuration for the runtime. The user instantiates a provider class
(e.g. new OpenAIVoiceProvider({ apiKey })) and passes the instance; the
router and TTS pipeline dispatch through it.
Properties
provider?
provider?: VoiceProvider;
Voice provider for TTS and STT.
InboundDispatchHandle
Returned synchronously from host.dispatch. Adapters use this to wire up
their response (HTTP SSE Response, webhook 202 ack, schedule completion
log) without awaiting the full action pipeline.
Properties
accepted?
readonly accepted?: Promise<void>;
Resolves once the request has been accepted — discoverable, with nothing left that could make it silently not exist. It does not wait for execution to finish, and it rejects when acceptance fails, so a caller that acks on it never acks a request that never runs.
What "discoverable" costs differs by path, and each promises what its own path can honour:
- External dispatch: the enqueue-time store writes
(
activeRequestsentry + thein_progressrecord) have committed AND the runner has taken the job. Adapters that ack before the client opensGET …/stream(the202path) await this; a store-write or enqueue failure rejects it and surfaces as a failed POST / reverted resume. - In-process,
queuepolicy: the same enqueue-time writes. The run itself is still waiting behind its concurrency key. - In-process, ordinary: the run's own
activeRequestsregistration has committed.dispatchLocalreturns whilerunActionis still at its first await, so without this a caller would ack a request while the write that makes it exist could still fail. Thein_progressrecord follows during execution on this path, so an immediate…/streamread can still miss it; the entry that recovery and the sweeper key off is what has landed.
Acceptance is discoverability, not safety, and it is not trying to be. Setup continues after it and can still fail without recording anything. What protects a caller that handed over durable work is that work's own lease: if the run dies at any point — during setup, mid-execution, or by the process going away — the lease lapses and the owner recovers the row. That is the designed recovery path for every way a child can die, and no dispatch milestone improves on it.
What acceptance buys is therefore visibility, not safety: a
fire-and-forget caller holds no finished, so without this a registration
failure is silent and the row waits out its lease with nothing anywhere
saying why. With it, the failure surfaces where it happened.
Optional on the type because a custom runner may not distinguish acceptance from completion. Every runner this package ships does.
finished
readonly finished: Promise<ExecutionResult>;
Resolves when the action completes (success, failure, or abort).
liveStream
readonly liveStream: LiveRequestStream | null;
SSE-shaped readable stream for HTTP transports; null otherwise.
requestId
readonly requestId: string;
responseEmitter
readonly responseEmitter: ResponseEmitter;
ResponseEmitter the runtime writes items to. Always present.
InboundRequestEnvelope
Single shape every adapter constructs before invoking the runtime. The
runtime below this layer is identical regardless of source.
Properties
action
action: string;
attachments?
attachments?: FileContent[];
The files the person's message carries, in reference form, already
checked against the limits and claimed into the session by the action
route's parse step (routes/attachment-claim.ts). Set by that step, never
read from a body here. The run writes them on the user line and shows
them to blocks as ctx.request.attachments.
flowKind
flowKind: string;
input
input: unknown;
Raw input; validated by action.inputSchema downstream.
metadata?
metadata?: Record<string, unknown>;
Adapter-specific provenance (webhook headers, MCP session ids, etc.).
orgId?
orgId?: string;
Organization override for this dispatch, when the adapter resolved one
that differs from principal.orgId — a trusted continuation or child
carrying its parent's binding, say. Absent means "use the principal's",
which is the normal case; it is never a way to arrive with no
organization at all.
principal
principal: ResolvedPrincipal & Partial<Pick<Principal, "kind" | "resolvedBy">>;
Resolved principal — normally populated by host.resolvePrincipal
before dispatch, and carried unchanged. The runtime treats this as
authoritative.
kind and resolvedBy are the door's (Principal). A principal
assembled without them (a direct host.dispatch from server code) runs
as its session's kind when the session exists, and as a machine's when
the run creates it.
rawBody?
rawBody?: Uint8Array<ArrayBufferLike>;
Raw HTTP body bytes preserved for adapters that need pre-parse access (webhook signature verification). Only set by HTTP-shaped adapters.
requestId?
requestId?: string;
Adapter-generated or framework-generated when absent.
resolvedActionCore?
resolvedActionCore?: ActionCore;
Pre-resolved action core, set ONLY by adapters for an event dispatch that
has no static coordinate to recover from — today, the dynamic schedule
whose handler block is produced at dispatch time by a resolver. When
present, the runtime runs this core directly instead of resolving from
flow via resolveActionCore. Like source, it is set internally and
never read from a request body, so it adds no attack surface on the
caller-addressed path. Not serializable and not persisted: on recovery the
field is absent, which is why durable dynamic schedules do not recover
(a documented non-goal). Statically-declared bindings (HTTP actions,
webhooks, schedules.static) leave this unset and resolve by
coordinate.
Scope: only runAction.resolveAction consumes the carried core. The two
coordinate-resolution sites in createExecutionContext (eager-resource
prefetch and the live token-budget remaining accessor) are not given it,
so for a dynamic schedule they resolve nothing: eager block-declared
resources are not prefetched (collections still lazy-load on access; eager
singles are absent) and the in-flow tokenUsage.remaining reads
+Infinity. Terminal token-budget enforcement is unaffected — it reads the
budget off the carried core that runAction runs. This within-run
degradation is the accepted cost of the dynamic schedule's ad-hoc path,
alongside its non-recoverability; static bindings have neither limitation.
Not serializable, so a dispatch carrying it runs in the dispatching process whatever runner is installed: a job queue never sees it.
responseEmitter?
responseEmitter?: ResponseEmitter | null;
Stream emitter the runtime writes to. HTTP adapter constructs a
LiveRequestStream; other adapters may pass null for fire-and-forget.
runtimeConfig?
runtimeConfig?: RuntimeConfig;
Runtime config to run this dispatch under, instead of the host's own.
Server-set and internal, like source and resolvedActionCore — never read
from a request body, so it adds no caller-facing surface. Today's one writer
is the detached start operation: a child continues the launching request's
work, and that request may be running under a config the caller derived
(fsdev run builds one so --model applies), which the host was never
constructed with.
The rule this field exists for: a detached child inherits the LAUNCHING
REQUEST's effective config, not the host's construction-time one. A host
is built once; a caller may run any given request under a config it derived
(fsdev run builds { ...appConfig, modelResolver, logger } so --model
takes effect), and the child is that request's own work continued in the
background.
And the limit, which is part of the rule rather than an exception to it:
it cannot cross a serialization boundary. A RuntimeConfig holds live
resolvers and providers, so the external-runner branch ignores this — a
queued job runs under its own worker's config, which is the only thing that
process can honour. Carrying just a model id across would not fix it: the
worker has its own gateways and keys, so a forced id may not resolve there
at all. The host therefore WARNS at the dispatch that drops an override
rather than pretending it applied.
Three separate rounds of fixes rediscovered this limit one instance at a time. It is written here so the fourth does not have to.
sessionId
sessionId: string;
The session the run lands in. Required: every run names its session,
and its request record names it from the first write. An existing
session, a new id (born on the run's first write), or, for a run that
belongs to no conversation, oneOffSessionId() from
@flow-state-dev/core/helpers. Missing at run time, dispatch throws
SessionRequiredError before anything is written.
signal?
signal?: AbortSignal;
Cancellation signal forwarded from the inbound transport.
source
source: string;
Provenance — propagated to RequestRecord.source.
tenantId?
tenantId?: string;
Optional tenant the request runs under. Extracted by HTTP
adapters from a configurable header (default x-tenant-id) and threaded
onto the request/session context identities.
InboundTransportAdapter
Inbound transport adapter — translates external input into action invocations.
Adapters are immutable factory objects: a source identifier plus a
single pure createBindings(host) function that produces routes and
dispatchers. Adapters do not retain references to the host. They are
not mounted as plugins — they are values consumed at host construction.
Properties
source
readonly source: string;
Stable identifier stamped onto every request as
RequestRecord.source. See InboundSource for the documented
known-set.
Methods
createBindings()
createBindings(host): TransportBindings;
Pure factory: produce the routes and dispatchers this adapter exposes
given the host runtime. Called once per host construction. Must be
synchronous and side-effect-free up to the optional async start hook
surfaced via the returned bindings.
Parameters
host
Returns
InboundTransportHost
Runtime surface available to a transport adapter. The framework owns this
type; adapters never construct one. They consume it via createBindings.
Properties
arbitratesExternalDispatch?
readonly arbitratesExternalDispatch?: boolean;
Whether work this host hands to an external queue is arbitrated against
the recipient's concurrency policy — true when the host's arbiter keeps its
keys in a backend the worker processes share (a worker adapter's
leaseBackend). A delivery into an existing session past an external
queue is refused unless this is true.
Absent reads as false: a host built before this field existed keeps the refusal.
logger?
readonly logger?: RuntimeLogger;
registry
readonly registry: FlowRegistry;
resolvers?
readonly resolvers?: object;
model?
model?: ModelResolver;
voice?
voice?: VoiceProvider;
Router-level voice provider, set once at host construction. Per-action
dispatch uses flow?.voice?.provider ?? voice; this bag is for adapter
introspection only and is not consulted during the per-action merge.
stores
readonly stores: StoreRegistry;
usesExternalRunner
readonly usesExternalRunner: boolean;
Whether this host's effective runner hands work to an external queue rather than running it here.
Exposed because a delivery into an existing session past that boundary
must refuse rather than under-deliver when the host cannot arbitrate it
against the session's concurrency policy — that is, unless
arbitratesExternalDispatch is true. The host already computes this
to pick its own dispatch branch; publishing it is what stops a caller
re-deriving it from the runner and reaching a different answer than the
host did.
Methods
continueRequest()
continueRequest(options): Promise<ContinueRequestResult>;
Continue a suspended request under its OWN id. Unlike dispatch,
which starts a fresh run, this re-enters the existing request: completed
blocks replay from the durable log, the resolving ctx.suspend() returns
the resume payload, and the record transitions suspended → in_progress → terminal in place — no second request is created. Wraps continueRequest
with the host's registry/stores/runtimeConfig. Rejects for a missing record
or unregistered flow.
Parameters
options
HostContinueRequestOptions
Returns
Promise<ContinueRequestResult>
dispatch()
dispatch(envelope): InboundDispatchHandle;
Dispatch an action-execution envelope. Fire-and-forget: returns a
synchronous InboundDispatchHandle whose liveStream and requestId are
available immediately, while finished resolves when the action
completes.
Adapters that need a streamed response (HTTP+SSE) consume
handle.liveStream.readable; adapters that only want a final result
(webhook, schedule) await handle.finished.
Throws synchronously for unknown flow kinds or malformed envelopes.
Scope: action-execution only. Session/state/resource routes are
adapter-owned and use host.stores / host.registry directly.
Parameters
envelope
Returns
resolvePrincipal()
resolvePrincipal(context): Promise<Principal>;
Resolve the principal for a request. Phase 1 delegates to the body-
userId stub. A configurable hook on
createFlowApiRouter replaces the stub later. Adapter code does not change between phases —
adapters always call this method.
Parameters
context
PrincipalResolutionContext
Returns
Promise<Principal>
validateDispatch()
validateDispatch(envelope): Promise<void>;
Validate async flow-level pre-conditions before dispatch. Must be
awaited between resolvePrincipal and dispatch.
Throws OrgRequiredError when the envelope reaches dispatch with no
usable organization on either the envelope or its principal — which means
a call site assembled an envelope without going through principal
resolution, since resolution cannot produce one. Also throws a
plain Error for an unregistered flowKind (same shape as dispatch).
Parameters
envelope
Returns
Promise<void>
InProcessFetchOptions
Options for createInProcessFetch.
Properties
basePath?
basePath?: string;
The mount prefix the router is addressed under. Default "/api/flows",
the default of createFlowApiRouter and of every host. A path outside
it answers 404.
InProcessPrincipal
Who an in-process caller is, and where that answer came from.
Extends
Properties
from
from: "resolver" | "development-default";
resolver when a configured resolver named the organization;
development-default when the flow authenticates nobody and the framework
supplied DEFAULT_ORG_ID.
kind
readonly kind: PrincipalKind;
Inherited from
orgId
orgId: string;
Inherited from
resolvedBy?
readonly resolvedBy?: string;
Inherited from
tenantId?
readonly tenantId?: string;
Inherited from
userId
userId: string;
Inherited from
InProcessPrincipalQuestion
What an in-process caller asks: the question an HTTP action request asks, minus the request.
Properties
action
action: string;
The action the caller is about to run.
flowKind
flowKind: string;
The flow instance address (a singleton's kind, or a collection member's id).
input
input: unknown;
The action input, as the resolver would see it on an HTTP request.
userId
userId: string;
The user the local caller names, the way an unauthenticated HTTP caller names one in its body. A resolver that authenticates ignores it; the framework default returns it.
InstancePinCaller
Who is asking to see or run the instance. Both fields come from a resolved principal or a bound session.
Properties
orgId
orgId: string;
userId
userId: string;
JobQueueAdapter
A job queue adapter for the jobQueue option of createFlowState.
Adapter packages (e.g. @flow-state-dev/bullmq) return an object whose
shape satisfies this interface. createFlowState resolves the runtime
once and hands the SAME { registry, stores, runtimeConfig } to both
sides, so the enqueue path and the processing side can never disagree on
stores — the invariant that makes streaming, refresh, and the devtool read
what processed jobs write.
Properties
leaseBackend?
readonly leaseBackend?: ConcurrencyLeaseBackend;
An ordered-lease backend shared by every process of the deployment, for the engine's concurrency arbiter to keep its lines in.
Supplied by an adapter whose runs land in several processes, so a
session's queue / reject / hold / defer policy holds across all of them. The
arbiter keeps the policy; the backend only orders places on a key. With
one, a delivery into an existing session is accepted and carries its
place on the job (DispatchEnvelope.leasePlace), which the adapter's
processing side waits on and gives back.
Absent → each process arbitrates only its own in-process runs, work handed
to the queue is not arbitrated, and a delivery into an existing session is
refused external-flow-runner.
mode?
readonly mode?: JobQueueMode;
Which sides this process runs. Default "colocated".
Methods
close()?
close?(): Promise<void>;
Release backend resources (queues, connections). Called by dispose().
Returns
Promise<void>
createRunner()
createRunner(runtime): FlowRunner;
Build the enqueue side (enqueue + live-event bridge). Installed as the
router's FlowRunner unless mode is "process-only".
Parameters
runtime
Returns
startProcessing()
startProcessing(runtime): ProcessingHandle;
Start the processing side against the resolved runtime. Called during
runtime init unless mode is "enqueue-only". The returned handle is
closed by FlowState.dispose() before store adapters are disposed, so
in-flight jobs drain against open stores.
Parameters
runtime
Returns
JwtPayload
Standard JWT registered claims this verifier inspects. Hosts read custom
claims off the returned payload directly; nothing here is opinionated
about identity-shape (no enforced userId / sub mapping).
Indexable
[claim: string]: unknown
Properties
aud?
aud?: string | string[];
exp?
exp?: number;
iat?
iat?: number;
iss?
iss?: string;
jti?
jti?: string;
nbf?
nbf?: number;
sub?
sub?: string;
Lease
Properties
acquiredAt
acquiredAt: number;
expiresAt
expiresAt: number;
holder
holder: string;
leaseId
leaseId: string;
requestId
requestId: string;
LeaseOptions
Properties
durationMs
durationMs: number;
How long the lease is valid, in ms.
holder
holder: string;
Identifier of the holder (worker id, process id).
LeasePlace
A run's place in one key's line, as the backend issued it. Opaque to callers.
Properties
key
readonly key: string;
The tenant-namespaced concurrency key the engine resolved.
ticket
readonly ticket: string;
The backend's id for this place on the key.
LeasePlaceHold
A place this process keeps renewed until it stops holding it.
Methods
stop()
stop(): void;
Stop renewing. Idempotent. Does not give the place back.
Returns
void
LeaseStore
Lease persistence for preventing concurrent resume. Each lease is keyed by requestId; only one active (non-expired) lease per request at a time.
Methods
acquire()
acquire(requestId, options): Promise<Lease | null>;
Attempt to acquire a lease. Returns the lease on success, null if the request already has an active (non-expired) lease held by another holder.
Parameters
requestId
string
options
Returns
Promise<Lease | null>
get()
get(requestId): Promise<Lease | null>;
Get the current lease for a request, if any.
Parameters
requestId
string
Returns
Promise<Lease | null>
pruneExpired()
pruneExpired(): Promise<void>;
Remove expired leases. Called periodically or on acquire.
Returns
Promise<void>
release()
release(requestId, leaseId): Promise<void>;
Release a lease by (requestId, leaseId).
Parameters
requestId
string
leaseId
string
Returns
Promise<void>
LeaseTakeInput
What take is asked for.
Properties
ifEmpty?
ifEmpty?: boolean;
Claim the key only if nobody holds or waits on it (the reject policy).
When the key is taken, take answers { heldBy } instead of a place.
key
key: string;
The tenant-namespaced concurrency key.
requestId
requestId: string;
The request that will hold the place, named to a refused reject caller.
OrgStore
Extends
DeltaStoreOps<OrgRecord>
Methods
delete()
delete(id): Promise<void>;
Parameters
id
string
Returns
Promise<void>
deleteField()?
deleteField?(
id,
path,
expectedVersion,
updatedAt
): Promise<SetResult<OrgRecord<JsonObject>>>;
Remove the value at path inside the record's state slice. For a
depth-2 path ["field", "key"] this deletes state.field.key, leaving
sibling keys intact. A missing key is a no-op (version still bumps).
Parameters
id
string
path
string[]
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<OrgRecord<JsonObject>>>
Inherited from
DeltaStoreOps.deleteField
get()
get(id): Promise<OrgRecord<JsonObject> | undefined>;
Parameters
id
string
Returns
Promise<OrgRecord<JsonObject> | undefined>
incField()?
incField?(
id,
path,
delta,
expectedVersion,
updatedAt
): Promise<SetResult<OrgRecord<JsonObject>>>;
Atomically add delta to the numeric value at path inside state.
Treats a missing key or null as 0; throws via the adapter's normal
error surface, writing nothing, if a value is already present and is not
a number. Other record fields are preserved unchanged.
Parameters
id
string
path
string[]
delta
number
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<OrgRecord<JsonObject>>>
Inherited from
DeltaStoreOps.incField
list()
list(options?): Promise<OrgRecord<JsonObject>[]>;
Parameters
options?
Returns
Promise<OrgRecord<JsonObject>[]>
patchField()?
patchField?(
id,
path,
value,
expectedVersion,
updatedAt
): Promise<SetResult<OrgRecord<JsonObject>>>;
Replace the value at path inside the record's state slice. Equivalent
to a shallow merge of { [path[0]]: value } into state for depth-1
paths. The remainder of the record (other state fields, metadata,
top-level columns) is preserved unchanged.
Parameters
id
string
path
string[]
value
unknown
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<OrgRecord<JsonObject>>>
Inherited from
DeltaStoreOps.patchField
pushToArray()?
pushToArray?(
id,
path,
values,
expectedVersion,
updatedAt
): Promise<SetResult<OrgRecord<JsonObject>>>;
Append values (in order) to the array at path inside state. Treats
a missing key as an empty array; throws via the adapter's normal error
surface if a value is already present and is not an array, including
null. Other record fields are preserved unchanged.
Parameters
id
string
path
string[]
values
unknown[]
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<OrgRecord<JsonObject>>>
Inherited from
DeltaStoreOps.pushToArray
set()
set(
id,
value,
expectedVersion
): Promise<SetResult<OrgRecord<JsonObject>>>;
See SessionStore.set for CAS semantics.
Parameters
id
string
value
expectedVersion
ExpectedVersion
Returns
Promise<SetResult<OrgRecord<JsonObject>>>
ParsedHmacSignature
Parsed signature components. timestamp is the UNIX seconds value when
the header carries one (Stripe-style); signatures lists every candidate
signature found, all of which are checked.
Properties
signatures
signatures: string[];
timestamp?
timestamp?: number;
Principal
The principal a run runs as. Built on core's ResolvedPrincipal.
resolvedBy names the resolver that produced it, with the host settings
applied to its answer (requireUser, defaultUserId): a value, so it rides
a runner's envelope. Absent on a principal no resolver produced (a
schedule's named person, a record stored before the field), and an absent
value matches nothing.
Extends
ResolvedPrincipal
Extended by
Properties
kind
readonly kind: PrincipalKind;
orgId
orgId: string;
Inherited from
ResolvedPrincipal.orgId
resolvedBy?
readonly resolvedBy?: string;
tenantId?
readonly tenantId?: string;
userId
userId: string;
Inherited from
ResolvedPrincipal.userId
ProcessingHandle
Handle for a started processing side; close() drains and stops it.
Methods
close()
close(): Promise<void>;
Returns
Promise<void>
RequestStore
Extends
DeltaStoreOps<RequestRecord>
Methods
countItems()
countItems(requestId): Promise<number>;
Count the items persisted for a request without materializing them.
Matches what get(id) would surface as items.length — including the
legacy dual-read union of pre-migration blob items with child-table
rows — but adapters with a dedicated items table answer with an indexed
COUNT instead of loading item payloads. Returns 0 for an
unknown request. Reflects flushed writes only; callers that just
persisted items should flushItems first.
Parameters
requestId
string
Returns
Promise<number>
delete()
delete(id): Promise<void>;
Delete the request and everything stored under its id: the record, its items, its stream events and its runOnce results. Request ids can be caller-supplied, so a later request may take a deleted id, and anything left under it would be replayed to that request's owner.
Remove the record last, and only after every child delete has finished and succeeded: a failure then leaves a retryable delete, and nothing is left without an owner. Wait out event and item writes already in flight for the id, so none of them lands after the delete.
Parameters
id
string
Returns
Promise<void>
deleteField()?
deleteField?(
id,
path,
expectedVersion,
updatedAt
): Promise<SetResult<RequestRecord<JsonObject>>>;
Remove the value at path inside the record's state slice. For a
depth-2 path ["field", "key"] this deletes state.field.key, leaving
sibling keys intact. A missing key is a no-op (version still bumps).
Parameters
id
string
path
string[]
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<RequestRecord<JsonObject>>>
Inherited from
DeltaStoreOps.deleteField
deleteIfStatus()
deleteIfStatus(id, allowedStatuses): Promise<ConditionalWriteResult>;
RequestStore.delete, only while the request's status is one of
allowedStatuses: the status check and the delete are one atomic step
inside the adapter, the way RequestStore.setFieldsIfStatus gates
a write. A caller that judged a record by its status (retention judging a
past turn evictable) deletes it only if it is still in that status, so a
request that started running in between (a re-driven interrupted one)
keeps its record, items, events and runOnce results.
Writes already in flight for the id are waited out but not dropped first: when the predicate fails they belong to a run that is still going.
Returns the status found under the same step, with the outcomes of ConditionalWriteResult: an absent record is never a match.
Parameters
id
string
allowedStatuses
readonly RequestStatus[]
Returns
Promise<ConditionalWriteResult>
flushEvents()
flushEvents(requestId): Promise<void>;
Wait for all pending event persistence writes to complete. Called before the terminal patchRequestRecord.
Parameters
requestId
string
Returns
Promise<void>
flushItems()
flushItems(requestId): Promise<void>;
Wait for all pending item persistence writes to complete, so none lands
after a later write. Draining these is all it does: a settling set
lands its own items and does not depend on a flush before it.
Parameters
requestId
string
Returns
Promise<void>
get()
get(id): Promise<RequestRecord<JsonObject> | undefined>;
Parameters
id
string
Returns
Promise<RequestRecord<JsonObject> | undefined>
getEvents()
getEvents(requestId, fromSequence?): Promise<RequestStreamEvent[]>;
Retrieve persisted stream events for a request.
Returns events sorted by sequence_number. When fromSequence is
provided, only events with sequence_number > fromSequence are
returned; omitting it returns the full log (used by the
completed-request replay path).
Parameters
requestId
string
fromSequence?
number
Returns
Promise<RequestStreamEvent[]>
getRunOnceResult()
getRunOnceResult(requestId, key): Promise<{
found: boolean;
value?: unknown;
}>;
Lookup the memoized result of a ctx.runOnce(key, fn) call.
Returns { found: false } when no record exists for this (requestId, key) pair. The stored value is opaque JSON — the caller is responsible
for any type coercion. Implementations should treat misses as cheap
and not allocate on miss.
Parameters
requestId
string
key
string
Returns
Promise<{
found: boolean;
value?: unknown;
}>
incField()?
incField?(
id,
path,
delta,
expectedVersion,
updatedAt
): Promise<SetResult<RequestRecord<JsonObject>>>;
Atomically add delta to the numeric value at path inside state.
Treats a missing key or null as 0; throws via the adapter's normal
error surface, writing nothing, if a value is already present and is not
a number. Other record fields are preserved unchanged.
Parameters
id
string
path
string[]
delta
number
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<RequestRecord<JsonObject>>>
Inherited from
DeltaStoreOps.incField
isAbortRequested()
isAbortRequested(requestId): Promise<boolean>;
Whether cancellation has been requested for this request.
The narrow read behind the running process's abort poll: it answers the one question the poll asks without materializing the request. Same motivation and same obligation as RequestStore.countItems — a question about a request that adapters answer with a primary-key lookup rather than by loading payloads.
Required, and O(1) in item count on every adapter. This runs on the
heartbeat tick for the life of every request, so an implementation that
reads the record — and therefore deserializes a monotonically growing item
array — turns a long detached run into quadratic work, on exactly the
workload the poll exists to serve. get() is not an acceptable
implementation on any adapter whose get() carries items.
Returns false for an unknown request: a request that is gone is not
abort-requested, and the caller's timer is about to be cleared anyway.
Parameters
requestId
string
Returns
Promise<boolean>
list()
list(options?): Promise<RequestRecord<JsonObject>[]>;
Parameters
options?
Returns
Promise<RequestRecord<JsonObject>[]>
patchField()?
patchField?(
id,
path,
value,
expectedVersion,
updatedAt
): Promise<SetResult<RequestRecord<JsonObject>>>;
Replace the value at path inside the record's state slice. Equivalent
to a shallow merge of { [path[0]]: value } into state for depth-1
paths. The remainder of the record (other state fields, metadata,
top-level columns) is preserved unchanged.
Parameters
id
string
path
string[]
value
unknown
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<RequestRecord<JsonObject>>>
Inherited from
DeltaStoreOps.patchField
persistEvents()
persistEvents(requestId, events): void;
Persist a stream event for a request. Non-blocking — the backend handles async flushing. Events are stored in sequence order for cursor-based replay.
Parameters
requestId
string
events
RequestStreamEvent[]
Returns
void
persistItems()
persistItems(requestId, items): void;
Persist the current items for an in-progress request. Non-blocking from the caller's perspective — the backend handles async flushing. The write that settles a request carries its final items itself (see RequestStore.set); this is the path for items while it runs.
Merge-by-id contract: persisting items MUST union the supplied
items into the stored set by id (last-write-wins per id), never replacing
the full set. Order is preserved — existing items keep their position, new
ids append. This lets a same-request continuation (suspend → resume under
the same id) persist only its post-resume items while a get still returns
the full pause→continue history. The in-memory and filesystem adapters
merge onto the record (mergeItemsById); the SQL adapters UPSERT. Items
persisted while the request runs are readable before it settles.
Content-update contract: "last-write-wins per id" is by item
CONTENT, not object reference. The runtime mutates a single item object in
place across its lifecycle (e.g. a block_trace in_progress → completed),
so an adapter that diffs incrementally by object reference would drop the
later write and leave stale content persisted — defeating resume
memoization. Re-persisting an id whose fields changed MUST write the
latest content. Enforced by the cross-store conformance suite.
Parameters
requestId
string
items
RuntimeItem[]
Returns
void
pushToArray()?
pushToArray?(
id,
path,
values,
expectedVersion,
updatedAt
): Promise<SetResult<RequestRecord<JsonObject>>>;
Append values (in order) to the array at path inside state. Treats
a missing key as an empty array; throws via the adapter's normal error
surface if a value is already present and is not an array, including
null. Other record fields are preserved unchanged.
Parameters
id
string
path
string[]
values
unknown[]
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<RequestRecord<JsonObject>>>
Inherited from
DeltaStoreOps.pushToArray
releaseItemTracking()?
releaseItemTracking?(requestId): Promise<void>;
The request's run has finished writing under requestId, however it
ended: drop what the store keeps in memory to make that request's item
writes incremental (the persistent adapters remember the content they
last wrote per item). Item writes still queued for the request land
first, so none is lost and none puts the memory back afterwards.
The runtime calls it once the last live attempt of the request in this
process has ended, after everything that attempt writes past its
terminal status (request.onFinished, side-chain drains, request-end
hooks). A write under the id after this still lands, in full.
Optional: a store that keeps no per-request item state omits it.
Parameters
requestId
string
Returns
Promise<void>
set()
set(
id,
value,
expectedVersion
): Promise<SetResult<RequestRecord<JsonObject>>>;
See SessionStore.set for CAS semantics.
set ignores RequestRecord.abortRequested in both directions:
the stored value survives a full record that omits it, and a
full record that carries it cannot set one. Adapters must hold this
themselves — the compiler will not, because the field is still on the
record type for reading. An adapter that "helpfully" honours the field on
set reintroduces the hazard the rule exists to remove: every full-record
writer builds { ...heldRecord, ...patch } from a snapshot that predates
the flag, so honouring it means erasing a cancellation nobody intended to
touch. Write it with RequestStore.setFieldsIfStatus.
A set whose record leaves items off keeps the stored items.
The request-state write is a full-record write built from the
snapshot the run took when it started, so it leaves items off rather
than hand back that snapshot's. An adapter that keeps items on the record
and replaces the whole record on set would drop every item persisted
since: carry the stored items through when value.items is absent
(the in-memory and filesystem adapters use withHeldItems). A record
that carries items may still replace them.
A set that settles a request lands the items it carries in the same
write as its status, so no reader sees a final status
without the items it settled with. An adapter that keeps items apart from
the record row writes them in the row write's transaction, and only if
that write lands. A set with a non-terminal status may leave items to
RequestStore.persistItems, as the SQL pair does: it is built from
a record read earlier, so its items can be older than ones persisted
since.
Parameters
id
string
value
expectedVersion
ExpectedVersion
Returns
Promise<SetResult<RequestRecord<JsonObject>>>
setFieldsIfStatus()
setFieldsIfStatus(
id,
fields,
allowedStatuses,
updatedAt,
expectedIncarnation?
): Promise<ConditionalWriteResult>;
Apply fields to a request only while its status is one of
allowedStatuses, evaluating the predicate and the write as one atomic
step inside the adapter.
The verb RequestStore was missing. Two things make it necessary rather
than convenient:
setcannot express it.settakes a whole record, so writing one field means read-modify-write, and every full-record writer already carries fields it never intended to touch.expectedVersioncannot express it either. The predicate that matters is about status, and terminal transitions go through asetwith"any"that persistsversionunchanged. A version-checked write therefore still validates after a terminal commit and resurrects a dead record. No amount of version arithmetic reaches a status.
Deliberately general — the predicate and the field set are parameters, not
an abort-shaped markAborted() — because the same shape is
"change these fields only if the record is still in this state."
fields may also move the status (a ConditionalStatusTransition): the record moves from an allowed status to fields.status in
the same atomic step, with the paired result. This is how the
stale-request sweep marks a request interrupted without overwriting one
that finished between its read and its write. The returned status is
still the status found, before the move.
Distinct from DeltaStoreOps.patchField, which addresses the
record's state slice under a version predicate. This addresses
top-level record fields under a status predicate; the two sit beside
each other rather than one generalizing the other.
An empty allowedStatuses matches nothing, and an absent record is never
a match — see ConditionalWriteResult for the three outcomes.
expectedIncarnation, when given, fences the write to the request a
caller already read: a record at id whose incarnation differs is a
different request (the id was deleted and taken again), and is reported
exactly as an absent one, { applied: false, status: undefined }, with
nothing written. A caller that checked who owns the record passes that
record's resolveRequestIncarnation(record), so the write cannot land on a
record that check never saw.
The store compares it with the stored record's incarnation resolved the
same way — its incarnation, or legacy_<createdAt> when that is absent or
null — inside the same atomic step as the status check. Never compare
createdAt: two requests under one id can share a millisecond, and a
same-owner hand-off rewrites it while keeping the incarnation.
Parameters
id
string
fields
allowedStatuses
readonly RequestStatus[]
updatedAt
number
expectedIncarnation?
string
Returns
Promise<ConditionalWriteResult>
setRunOnceResult()
setRunOnceResult(
requestId,
key,
value
): Promise<void>;
Persist the result of a ctx.runOnce(key, fn) call. The
value replaces any prior record for this (requestId, key) pair —
callers serialize execution per key so a late writer overwriting an
earlier success is benign (they computed the same fn).
Parameters
requestId
string
key
string
value
unknown
Returns
Promise<void>
subscribeToEvents()
subscribeToEvents(requestId, options): AsyncIterableIterator<RequestStreamEvent>;
Yields events for a request as they are persisted. Catch-up replay
covers events with sequence_number > options.fromSequence; the live
phase yields events as they arrive until the iterator aborts, sees a
terminal request status, or hits the liveness timeout. The "close"
path is signal.abort(); there is no separate .close() method.
Backends without a cross-process push primitive (SQLite, filesystem,
Postgres-without-liveTailPool) poll. Memory uses an in-process bus
shared with the persistence path.
Parameters
requestId
string
options
Returns
AsyncIterableIterator<RequestStreamEvent>
ResourceStateIndexes
The index verbs a store may implement. A store implements all four or none; without them the engine answers a lookup by scanning the scope's rows.
The rule every verb keeps
Entries are a superset: every live row the collection covers has its entries once the index is built, and an entry may outlive the value that made it. The engine re-checks each hit against its row, so a stale entry is never returned, and a missing one could never be recovered. So:
- A successful
setmakes the key's entries exactly the ones it lists, in the row's own commit. Asetthat conflicts changes no entry. - A successful
setalso clears the build marker of every index in the scope whose collection pattern matches the key and that the call does not list: a writer that does not know an index cannot keep it whole, so the next lookup rebuilds it. Asetthat conflicts clears nothing. delete,deleteAllandpurgeTombstonesremove the entries of the rows they tombstone or reclaim. They leave markers alone: a row that is not live needs no entry.- A build only adds entries. It never replaces them, because a live write may land while it scans.
Scopes are isolated: nothing here reads or clears another scope's entries or markers.
Methods
beginBuild()
beginBuild(
scopeType,
scopeId,
collection,
index
): Promise<string>;
Record that a build of index has begun in this scope (its state becomes
building). Returns the build's token, which completeBuild must pass
back: a later beginBuild replaces the marker with a new token.
Parameters
scopeType
scopeId
string
collection
string
index
string
Returns
Promise<string>
completeBuild()
completeBuild(
scopeType,
scopeId,
collection,
index,
build,
entries
): Promise<boolean>;
Add entries and mark the index built, in one commit, only if the
building marker build began is still there. Returns whether it did.
When a write cleared that marker during the scan, nothing is written,
even if a later build has begun since; the next lookup builds again.
Parameters
scopeType
scopeId
string
collection
string
index
string
build
string
entries
Returns
Promise<boolean>
findKeys()
findKeys(
scopeType,
scopeId,
collection,
index,
value
): Promise<string[]>;
The keys with an entry of value for index, in this scope, in ascending key order.
Parameters
scopeType
scopeId
string
collection
string
index
string
value
string
Returns
Promise<string[]>
state()
state(
scopeType,
scopeId,
collection,
index
): Promise<ResourceIndexBuildStatus>;
Whether index of collection is built in this scope. unbuilt when nothing was recorded.
Parameters
scopeType
scopeId
string
collection
string
index
string
Returns
Promise<ResourceIndexBuildStatus>
ResourceStateStore
Separates resource state persistence from scope record persistence.
State is addressed by (scopeType, scopeId, resourceKey) — the same scheme as
ContentStore, and covers both single-resource and collection-instance
state uniformly. Each resource's state is a JsonObject written under its
own key, so a mutation to one resource never rewrites the whole scope
record. It shares ContentStore's keyed storage pattern, but the
two stores deliberately diverge on concurrency — see below.
Concurrency: compare-and-swap, not last-write-wins
Every write carries an ExpectedVersion and returns a
SetResult, so a caller can tell whether its write actually landed.
This is the one place this store differs from ContentStore, and the
difference is deliberate: LWW is right for content, because nothing merges
a document body against a prior read. It is wrong for structured state that
concurrent workers read-modify-write, which is what resource state became
when it started backing task boards. One addressing scheme, two access
patterns, two concurrency models.
Two semantics diverge from the scope stores that share these types, and both are deliberate:
expectedVersion: 0means "no live row" — it is create-if-absent, and it is satisfied by a tombstoned key as well as a never-existed one."absent"is the stricter form and is refused by a tombstone, which is how a write that never observed the key is kept from undoing a delete.- Some conflicts are terminal, not retryable. A conflict against a
tombstone must not be retried into a resurrection, and a losing
create-if-absent must not be retried into an overwrite. Callers drive
this store through the resource CAS driver, not
runWithCAS.
Lifecycle and version semantics
| Rule | Behaviour |
|---|---|
| Lifecycle | live (visible) or deleted (tombstone: invisible, version retained) |
| Reads | get / getAll / getByPrefix return live rows only. A tombstone reads exactly like an absent key |
| Snapshots | Every state crossing the boundary is a deep copy, both ways: what a read returns, what a caller passed to set, and a conflict's currentValue. Mutating any of them never changes the stored row — the version has to witness the value, so no path may change a value without bumping a version |
| Snapshot timing | set captures its value before it yields — on the synchronous run-up to the adapter's first await, never behind a lock or a microtask. A mutation the caller makes while the returned promise is still in flight must not be the one that commits. Serializing eventually is not enough: by the time a deferred body runs, the caller has had control back |
| Version | First create writes 1; each committed write bumps by 1; never reused. A recreate continues from the tombstone's version + 1 |
delete | Retains the version, drops the payload (stores {}), marks deleted. The version is the only thing a tombstone carries |
deleteAll | Bulk-marks every live key in the scope deleted. A scope operation, so it takes no expected version |
purgeTombstones | Removes the scope's tombstoned rows outright and touches no live one. The only operation that reclaims a tombstone, and the one a scope's re-creation performs |
| Retention | The store never reclaims a tombstone on its own — no sweep, no TTL, in any scope. Only an explicit purgeTombstones removes one |
| Legacy rows | A row written before versioning reads as live at version 1 — never as absent |
| Version domain | A numeric expectedVersion must be a non-negative integer. Negative, fractional, NaN and Infinity throw — a programming error, not a lost race, so it is never folded into a conflict |
Retention is what closes the delete/recreate ABA within one incarnation of a scope id: because a tombstone keeps its version, an observer holding a pre-delete version never matches the row that replaces it. Nothing ages a tombstone out, so that guarantee does not weaken with time.
It is purgeTombstones — and only that — which gives those versions back,
which is why it is not something teardown does. See its own doc for the
trade it makes and why a scope's re-creation is the one caller entitled to
make it.
Per-adapter guarantee
Real CAS on memory, SQLite and Postgres. The filesystem adapter compares under a per-key mutex held on the store instance, so it closes the in-process race but does not protect two OS processes over one directory. Stated rather than implied.
Properties
indexes?
indexes?: ResourceStateIndexes;
The index verbs, when this store keeps index entries. Absent on a store that does not (memory, filesystem): the engine answers a lookup there by scanning, with the same result.
Methods
delete()
delete(
scopeType,
scopeId,
resourceKey,
expectedVersion
): Promise<SetResult<JsonObject>>;
Tombstone a single resource's state if expectedVersion still holds.
Takes a version like every other write, so a delete chosen from a stale
snapshot conflicts instead of tombstoning a newer generation.
The row keeps its version and drops its payload. Deleting an absent or
already-tombstoned key is an idempotent success — an absent key reports
version: 0, consistent with 0 meaning "no live row" everywhere else in
this contract. That is not a version any row holds, so never carry it
forward as the basis for a later write.
"any" and a positive version part company when a delete finds nothing to
remove and a live row appears before it can say why. "any" asserts
nothing about versions, so "there was no live row" is already the whole
answer to what it asked: the call linearizes there, a recreate that lands
afterwards belongs to a later story, and the result is an idempotent
success reporting version: 0 — never the recreated row's version, which
names a live row this delete did not remove. A positive expectedVersion
asserted something that did not hold at that same point, so it conflicts,
carrying the version now stored. Both halves matter: collapsing them into
"always succeed" hides a real lost race, and collapsing them into "always
conflict" reports one to a caller that opted out of versions entirely.
Parameters
scopeType
scopeId
string
resourceKey
string
expectedVersion
ExpectedVersion
Returns
Promise<SetResult<JsonObject>>
deleteAll()
deleteAll(scopeType, scopeId): Promise<void>;
Tombstone all live state for a scope instance, retaining each key's version. Used during scope record deletion. A scope operation rather than a key operation, so it carries no expected version.
Note the limit this honestly does not close: a create of a key that never
existed can still land after this returns, because a bulk mark only
touches rows that already exist and expectedVersion: 0 is satisfied by
a never-existed key. Closing that needs a scope generation, not a per-key
predicate.
Parameters
scopeType
scopeId
string
Returns
Promise<void>
get()
get(
scopeType,
scopeId,
resourceKey
): Promise<VersionedResourceState | undefined>;
Read a single resource's live state and its version, or undefined when
there is no live row. A tombstoned key returns undefined, exactly like
a key that never existed.
Parameters
scopeType
scopeId
string
resourceKey
string
Returns
Promise<VersionedResourceState | undefined>
getAll()
getAll(scopeType, scopeId): Promise<Record<string, VersionedResourceState>>;
Read all live state for a scope instance, each entry carrying its
version. Used by full-scope reads (/state, debug snapshot).
Parameters
scopeType
scopeId
string
Returns
Promise<Record<string, VersionedResourceState>>
getByPrefix()
getByPrefix(
scopeType,
scopeId,
keyPrefix
): Promise<Record<string, VersionedResourceState>>;
Read every live state entry in a scope whose resourceKey starts with
keyPrefix, each carrying its version. The match is on the start of the
key string: whole path segments (notes/shared/) or part of a name
(notes/sh); / is not special. An empty keyPrefix returns all
live keys in the scope (equivalent to getAll). Used during context
initialization to load only the state a flow declares — fixed resources
by exact key, collections by their pattern prefix.
Parameters
scopeType
scopeId
string
keyPrefix
string
Returns
Promise<Record<string, VersionedResourceState>>
listAcrossSessions()?
listAcrossSessions?(query): Promise<AcrossSessionsStoredRow[]>;
One collection's live rows across every session one owner has, a page at a time (AcrossSessionsQuery). Absent on a store built without the session store it joins to: the engine then refuses the read.
Parameters
query
Returns
Promise<AcrossSessionsStoredRow[]>
purgeTombstones()
purgeTombstones(scopeType, scopeId): Promise<void>;
Remove a scope instance's tombstoned rows outright, so each of those keys reads as one that was never written. Live rows are not touched, and a scope with no tombstones is unchanged.
This is not teardown; deleteAll is. This is what a scope's
re-creation calls, and the two differ on exactly what "absent"
tests for. After deleteAll a deleted key is still a row, so a write from
a context that never saw it live is refused and a delete stays deleted.
After this, there is no row, so such a write creates the key.
Both are needed because scope ids are caller-supplied and reusable. A
session id like chat-42 can be deleted and used again, and the session
store keeps no tombstone of its own, so the id really is free. Without
this at that point the dead incarnation's tombstones outlive it and make
every static resource in the new one permanently unwritable — a static
ResourceRef has no create-if-absent verb to escape through, unlike a
collection instance.
Why tombstones only, rather than the whole scope: a tombstone's only effect is to refuse writes, so removing one when it has stopped applying costs nothing. A live row is data. State written under a scope id before that scope's record exists is a real pattern — pre-seeding, and a partially-failed teardown — and a blanket purge would silently delete it on the next create.
The trade, stated rather than implied: a purged key's version restarts at
1, so a straggler from the previous incarnation holding version N can
match a row in the new one. Two things keep that narrow. It opens only
once a scope has been deliberately re-created under a reused id — never
during the delete itself, where retention still holds. And it is the same
residual deleteAll already documents: separating incarnations rather
than merely detecting them needs a scope generation, not a per-key
predicate.
Callers own the ordering, and it matters: a caller that reclaims on scope creation must reclaim first and create second. There is no transaction across the two stores, so a create that commits ahead of a reclamation which then fails leaves a live scope over intact tombstones with nothing left to retry it — the permanent version of the very bug this closes. Reclaiming first commits nothing until it has succeeded, and reclaiming twice is a no-op.
That order has its own known limit, and it is not a small one. A caller
that reclaims and then loses the create has removed tombstones under a
scope somebody else owns, and a later ordinary write at "absent" — which
is what every fresh context sends for a key it holds no version for — then
finds no row and recreates the key. Checking for an existing record first
narrows this to a true create race but cannot close it; only a scope
generation can, which is tracked separately ("A create
racing session deletion lands in a purged, caller-reusable scope — fence
the scope generation"). Callers must know they are choosing between that
and the permanent brick the other order causes.
Parameters
scopeType
scopeId
string
Returns
Promise<void>
set()
set(
scopeType,
scopeId,
resourceKey,
state,
expectedVersion,
options?
): Promise<SetResult<JsonObject>>;
Write a single resource's state if expectedVersion still holds.
- A number writes only when the current live version equals it.
0is create-if-absent: it succeeds when there is no live row (never existed, or tombstoned) and conflicts against a live one."absent"is the stricter create: it succeeds only when there is no row at all, so a tombstone conflicts. Pass it when the write must not be the thing that brings a deleted key back."any"writes unconditionally — the opt-out, and the posture every caller that has not adopted CAS passes explicitly.
A number outside that domain — negative, fractional, NaN, Infinity —
throws rather than conflicting. The type admits it; the contract does not.
On conflict, conflict.currentValue is the current live state or
undefined when the row is tombstoned, and conflict.currentVersion is
the version now stored. A caller must treat an undefined current value
as "deleted" and stop — never as "reuse what I had cached".
options.indexEntries carries the row's index entries. A store with
indexes commits them with the row (see
ResourceStateIndexes for the rule); one without ignores them.
Parameters
scopeType
scopeId
string
resourceKey
string
state
JsonObject
expectedVersion
ExpectedVersion
options?
Returns
Promise<SetResult<JsonObject>>
RunnerHandle
Handle returned by FlowRunner.dispatch(). Exposes the request id and a promise that resolves when execution finishes, plus an abort hook.
Properties
accepted?
readonly accepted?: Promise<void>;
Resolves once the request is accepted — registered and discoverable — without waiting for the run. Rejects with the run's own error when it dies before getting that far.
Optional because a runner is free not to distinguish the two, but the
in-process one does: dispatchLocal returns as soon as runAction reaches
its first await, which is before the registration write has landed, so the
handle alone is not evidence the request exists.
finished
readonly finished: Promise<ExecutionResult>;
requestId
readonly requestId: string;
Methods
abort()
abort(): void;
Returns
void
RuntimeConfig
Properties
defaultSseHeartbeatMs?
defaultSseHeartbeatMs?: number;
Default SSE wire-level heartbeat interval in milliseconds applied to
every live stream when the per-flow request.sseHeartbeatMs is unset.
durabilityProvider?
durabilityProvider?: DurabilityProvider;
Durable execution provider for checkpoint-based resume and HITL suspend.
durabilityRetention?
durabilityRetention?: DurabilityRetentionConfig;
Retention policy for the durability sweeper. When set alongside
durabilityProvider, the router constructs a periodic sweeper that
enforces suspension expiry and prunes aged-out suspensions, leases, and
orphaned checkpoints. Absent → no sweeper.
errorCapture?
errorCapture?: ErrorCaptureHandler;
Opt-in error-capture sink. Routes runtime block failures to an
external observability service (Sentry, Datadog, ...). Forwarded to
createExecutionContext; absent → no capture.
hostResolver?
hostResolver?: ResolvePrincipalFn;
The host-level resolver this runtime's host is given. Set by the router
and the queue worker, never by an app: the framework's own flows read it
off the context they run in (built-in-host.ts), so a built-in instance
held once per registry never answers to another host's resolver.
logger?
logger?: RuntimeLogger;
maxChildSessionListLimit?
maxChildSessionListLimit?: number;
Largest limit the child-session listing route accepts. Absent →
DEFAULT_MAX_CHILD_SESSION_LIST_LIMIT.
The list a client reads is all-time history — finished child sessions stays listed — so a deployment running large orchestrations outgrows the default. Raising it is a deliberate act because the cost is per row and per read: each row resolves its status from the request store, and clients re-read this list on every interaction. A bigger ceiling therefore buys completeness with read amplification on every turn, which is why this is an operator's decision rather than a caller's.
maxDebtAgeMs?
maxDebtAgeMs?: number;
How long past its due time a debt may stay outstanding before a pass
ends it, settled undeliverable and logged. Read by the wake
verb (RequestHost.wakes.maxDebtAgeMs). Absent → 24 hours.
maxRecordedValueBytes?
maxRecordedValueBytes?: number;
Largest block output or tool result, in serialized bytes, recorded whole in an item. Forwarded to every response emitter the runtime builds. Absent → the emitter's own 256 KiB default.
maxResponseBufferSize?
maxResponseBufferSize?: number;
Maximum buffered SSE bytes per request — see createLiveRequestStream.
modelResolver?
modelResolver?: ModelResolver;
noticeIds?
noticeIds?: NoticeIdScopes;
Which topic scopes' notices may name what changed, read by every push
edge. On by default; { org: false } turns ids off for the org scope: no
notice there reaches a browser with ids, and a collection entry's
notice reaches a scope-wide subscription on the bare scope topic. A
subscription narrowed to that exact entry still hears its path, since its
client named it.
onBackgroundWork?
onBackgroundWork?: (promise) => void;
Forwarded to runAction so serverless platforms can keep work alive.
Parameters
promise
Promise<unknown>
Returns
void
publicReentrySources?
publicReentrySources?: readonly string[];
Transport sources this deployment adds to the public re-entry allow-list.
Carried here for the same reason as queuedGraceMs: three
routes consult the list — retry, continue and resume — and this
bundle is the only thing that reaches all of them from both public entry
points. Absent → only the built-in sources are re-enterable.
queuedGraceMs?
queuedGraceMs?: number;
Resolved queued grace, carried here because three shipped paths
sweep and only this bundle reaches all of them: the router's periodic
sweeper, startup detection in createFlowRouteHandlers, and the
client-poked check-interrupted route. Absent → detectInterruptedRequests
applies DEFAULT_QUEUED_GRACE_MS.
requestHost?
requestHost?: RequestHostConstructionInputs;
Construction inputs for the request-host seam, forwarded to
createExecutionContext. A host that executes requests but wires
none leaves capabilities unable to reach the runtime — requireRequestHost
then throws by name rather than failing as undefined is not a function.
sealingSecret?
sealingSecret?: string;
The host's secret for sealing values it hands a client to send back
unread: today the cursor of a read across sessions
(ctx.resources.acrossSessions()). Each use derives its own key from it
(HKDF, under a label of its own), so one secret serves every use without
one key serving two. Default: process.env.FSD_SEALING_SECRET. Unset, each
process seals under a random key of its own, which is right for one
process; a host that runs more than one process behind one address (a
serverless deployment, a cluster) must set the same secret on every one,
or a cursor one process hands out is refused by the next.
settings?
settings?: FlowStateSettings;
Instance-level settings threaded onto every block as ctx.settings.
tracingLevel?
tracingLevel?: TracingLevel;
Tracing verbosity for observability snapshots.
userDeadlineMs?
userDeadlineMs?: number;
The deadline a stop that waits for a user gets when it names none, in
milliseconds from the stop: every ctx.suspendForUser
without a deadline, and every held question. Unset by default: such
a stop waits until it is answered, stopped or cancelled. Separate from
waitDeadlines, which bounds waits on work. Between
MIN_USER_DEADLINE_MS and MAX_USER_DEADLINE_MS. A raw
ctx.suspend never reads it: its own timeoutMs is its only deadline.
Read by ctx.suspendForUser with or without a request host, and exposed as RequestHost.userDeadlineMs.
voiceProvider?
voiceProvider?: VoiceProvider;
Voice provider for TTS and STT. Already merged by the host (per-flow
voice.provider wins over the router-level provider), so layers below the
host receive the effective value and never re-merge.
waitDeadlines?
waitDeadlines?: object;
A wait's deadline bounds, in milliseconds from the call: the
deadline a wait that names none gets (default five minutes), and the
shortest and longest one may name (default the sweep's resolution, one
second, and 24 hours). Read by RequestHost.waits.deadlines.
defaultMs?
defaultMs?: number;
maxMs?
maxMs?: number;
minMs?
minMs?: number;
SchedulerAdapter
Decides when the app's schedule tick runs. createFlowState calls start
once, at construction; dispose() calls the handle's stop before the
stores close.
Methods
start()
start(ticker): object;
Run ticker.tick() when the schedules should be checked.
Parameters
ticker
Returns
object
stop()
stop(): Promise<void>;
Returns
Promise<void>
ScheduleTicker
Fires what is due: the app's one schedule tick, handed to a SchedulerAdapter. Every caller (the built-in local cron, a host's cron route) goes through it, and it is the one writer of the last-tick record.
Methods
tick()
tick(options?): Promise<ScheduleTickReport>;
Fire what is due now, static and dynamic, every flow, each for its latest
due time. Builds the runtime when it hasn't been, so a cold function's
first request can be the tick. baseUrl: dispatch over the network to
this deployment (each fire its own request) instead of through the
app's router in this process. secret: the bearer each fire carries
(default process.env.CRON_SECRET), so an adapter that authenticates its
own caller with a configured secret sends that same secret on. Rejects
when a schedule index's claim does, after firing everything else.
Parameters
options?
baseUrl?
string
secret?
string
Returns
Promise<ScheduleTickReport>
SessionStore
Extends
DeltaStoreOps<SessionRecord>
Methods
delete()
delete(id): Promise<void>;
Parameters
id
string
Returns
Promise<void>
deleteField()?
deleteField?(
id,
path,
expectedVersion,
updatedAt
): Promise<SetResult<SessionRecord<JsonObject>>>;
Remove the value at path inside the record's state slice. For a
depth-2 path ["field", "key"] this deletes state.field.key, leaving
sibling keys intact. A missing key is a no-op (version still bumps).
Parameters
id
string
path
string[]
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<SessionRecord<JsonObject>>>
Inherited from
DeltaStoreOps.deleteField
get()
get(id): Promise<SessionRecord<JsonObject> | undefined>;
Parameters
id
string
Returns
Promise<SessionRecord<JsonObject> | undefined>
incField()?
incField?(
id,
path,
delta,
expectedVersion,
updatedAt
): Promise<SetResult<SessionRecord<JsonObject>>>;
Atomically add delta to the numeric value at path inside state.
Treats a missing key or null as 0; throws via the adapter's normal
error surface, writing nothing, if a value is already present and is not
a number. Other record fields are preserved unchanged.
Parameters
id
string
path
string[]
delta
number
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<SessionRecord<JsonObject>>>
Inherited from
DeltaStoreOps.incField
list()
list(options?): Promise<SessionRecord<JsonObject>[]>;
Parameters
options?
Returns
Promise<SessionRecord<JsonObject>[]>
patchField()?
patchField?(
id,
path,
value,
expectedVersion,
updatedAt
): Promise<SetResult<SessionRecord<JsonObject>>>;
Replace the value at path inside the record's state slice. Equivalent
to a shallow merge of { [path[0]]: value } into state for depth-1
paths. The remainder of the record (other state fields, metadata,
top-level columns) is preserved unchanged.
Parameters
id
string
path
string[]
value
unknown
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<SessionRecord<JsonObject>>>
Inherited from
DeltaStoreOps.patchField
pushToArray()?
pushToArray?(
id,
path,
values,
expectedVersion,
updatedAt
): Promise<SetResult<SessionRecord<JsonObject>>>;
Append values (in order) to the array at path inside state. Treats
a missing key as an empty array; throws via the adapter's normal error
surface if a value is already present and is not an array, including
null. Other record fields are preserved unchanged.
Parameters
id
string
path
string[]
values
unknown[]
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<SessionRecord<JsonObject>>>
Inherited from
DeltaStoreOps.pushToArray
set()
set(
id,
value,
expectedVersion
): Promise<SetResult<SessionRecord<JsonObject>>>;
Write value when the stored record's version matches expectedVersion.
Returns the new version on success or the current stored value/version on
conflict. The version field on value is the NEW version to persist.
expectedVersion accepts three things, and the scope stores' reading of
0 is the one that differs from ResourceStateStore (see
ExpectedVersion):
| Value | Writes when |
|---|---|
"any" | Always. Last write wins |
| a number | The stored version equals it. 0 means "stored at version 0" — scope records are created at 0, so a v0 record is live, not absent |
"absent" | No record exists at this id. An existing record at any version, 0 included, is a conflict carrying it |
"absent" is how a caller wins or loses a create race rather than
silently overwriting: a get-then-set cannot, because nothing stops a
second writer between the two calls.
delete is a hard delete with no tombstone, so a recreated id may reuse
versions. An observer holding a pre-delete version can therefore match
the record that replaces it — stated rather than defended, and the reason
this store's versions are not a substitute for identity.
Parameters
id
string
value
expectedVersion
ExpectedVersion
Returns
Promise<SetResult<SessionRecord<JsonObject>>>
SharedSchemasDescription
Properties
org
org: SharedScopeDescription;
participants
participants: object;
org
org: string[];
user
user: string[];
user
user: SharedScopeDescription;
SharedScopeDescription
Properties
resources
resources: Record<string, ZodTypeAny>;
stateSchema?
stateSchema?: ZodTypeAny;
SlackWebhookVerifierOptions
Properties
now?
now?: () => number;
Clock used for the timestamp check. Test seam.
Returns
number
toleranceSeconds?
toleranceSeconds?: number;
Max age (seconds) of the signed timestamp. Default 300. Infinity disables.
StreamBridge
Bridges events between a remote worker and a local SSE consumer. The worker writes events to the bridge; the web process reads them and forwards to SSE. Redis pub/sub is the BullMQ implementation; future adapters implement the same interface.
Key invariant: stores persist, bridges push. The bridge is best-effort live push. Late/reconnecting clients recover from the store.
Methods
createPublisher()
createPublisher(requestId): StreamPublisher;
Parameters
requestId
string
Returns
createSubscriber()
createSubscriber(requestId): StreamSubscriber;
Parameters
requestId
string
Returns
StreamBridgeEvent
Single event published through the bridge. Matches the shape of SSE events emitted by the response emitter so the web process can forward them to SSE clients without transformation.
Properties
data
data: string;
event
event: string;
id?
id?: string;
StreamPublisher
Publisher side of the bridge — used by the worker to push events.
Methods
close()
close(): Promise<void>;
Returns
Promise<void>
publishEvent()
publishEvent(event): Promise<void>;
Parameters
event
Returns
Promise<void>
publishTerminal()
publishTerminal(result): Promise<void>;
Parameters
result
Returns
Promise<void>
StreamSubscriber
Subscriber side of the bridge — used by the web process to receive events.
Properties
completed
completed: Promise<ExecutionResult>;
Methods
abort()
abort(): void;
Returns
void
close()
close(): Promise<void>;
Returns
Promise<void>
events()
events(): AsyncIterable<StreamBridgeEvent>;
Returns
AsyncIterable<StreamBridgeEvent>
SubscribeToEventsOptions
Options for RequestStore.subscribeToEvents. fromSequence is required
— a subscriber that has seen nothing passes 0. Optionality would
invite the bug where a reconnecting client with a stale Last-Event-ID
accidentally re-receives the entire log.
Properties
followThroughSuspend?
followThroughSuspend?: boolean;
When true, a request.suspended event is treated as a checkpoint, not
a stream terminal: the iterator yields it and keeps following the request.
Set by the attach route only when a continuation lease is held,
so a same-request continuation (resume / crash-recovery continue) can be
streamed through to its real terminal. The true terminals
(completed/failed/incomplete/aborted) still end the iterator, and
the route closes the wire if a later suspension lands with the lease gone
(the continuation re-suspended). Default false — a paused request's
stream still ends at suspended.
fromSequence
fromSequence: number;
Subscriber's last-seen sequence number; 0 means no events seen.
isStillAuthorized?
isStillAuthorized?: () => Promise<boolean>;
The caller's fence against a request id changing hands mid-stream. Ids
are caller-supplied, so between authorizing this stream and any read the
iterator makes after an await, the request can be deleted and another
owner's request take the id. An adapter calls this after every read that
returned events and before yielding any of them; when it resolves
false (or throws) the iterator yields none of that batch and ends, as
for a request that is gone. Absent means no fence. The route passes one
that compares the record's incarnation with the one it authorized.
Returns
Promise<boolean>
livenessTimeoutMs?
livenessTimeoutMs?: number;
If no events arrive in this window AND no terminal status is observed
in the store, the iterator yields a synthetic request.interrupted
event (not persisted) and closes. Default 30000. Ignored for the
in-memory store, where there is no cross-process death scenario.
maxPendingEvents?
maxPendingEvents?: number;
Per-subscription bounded queue capacity. On overflow the iterator
throws StoreSubscriptionError("backpressure_overflow"). Default
1000.
signal?
signal?: AbortSignal;
Aborts the subscription cleanly when the SSE client disconnects.
SuspensionStore
Suspension record persistence. Stores suspension metadata created by ctx.suspend() for later resolution via the resume endpoint.
Properties
persists?
readonly persists?: boolean;
false when this store keeps nothing past the process. Absent means it persists.
Methods
deleteForRequest()
deleteForRequest(requestId): Promise<void>;
Delete all suspensions for a request.
Parameters
requestId
string
Returns
Promise<void>
get()
get(requestId, suspensionId): Promise<SuspensionRecord | null>;
Get a suspension by (requestId, suspensionId).
Parameters
requestId
string
suspensionId
string
Returns
Promise<SuspensionRecord | null>
list()
list(filter?): Promise<SuspensionRecord[]>;
List suspensions matching a filter.
Parameters
filter?
SuspensionFilter
Returns
Promise<SuspensionRecord[]>
listPendingForUser()
listPendingForUser(query): Promise<PendingUserSuspension[]>;
One user's pending suspensions that wait on them, in one query that
joins each suspension to its request: the request's user and the
suspension's both query.userId; the request's tenant and organization
exactly query.tenantId and query.orgId, NULL-safe (an unbound
principal matches only unbound requests); its flow kind in
query.flowKinds; status pending; expiresAt absent or after
query.now; a reason in USER_SUSPENSION_REASONS. A suspension whose
request is missing is not returned. Oldest first by
(createdAt, requestId, suspensionId), strictly after query.after, at most
query.limit. Each row is built with projectUserSuspension from the
fields it names, never from a spread record. A SQL store runs this as one
statement; nothing is read back and filtered.
Parameters
query
PendingUserSuspensionQuery
Returns
Promise<PendingUserSuspension[]>
pruneTerminalBefore()
pruneTerminalBefore(cutoffMs, limit): Promise<number>;
Delete suspensions in a TERMINAL status (approved | rejected | timed_out |
expired) whose resolvedAt is non-null and strictly less than cutoffMs,
up to limit rows. Pending suspensions are never touched. Returns the
number of rows actually deleted so a sweeper can loop until it observes a
partial batch (deleted < limit). Idempotent — nothing matching returns 0.
Parameters
cutoffMs
number
limit
number
Returns
Promise<number>
set()
set(record): Promise<void>;
Create or update a suspension record.
Parameters
record
SuspensionRecord
Returns
Promise<void>
TraceStore
Per-request trace event log. Implementations are responsible for bounded retention — callers should not assume unbounded history.
appendEvent is logically append-only per request. flush lets adapters
with batched I/O guarantee durability before a read. getEvents supports
cursor reads via fromSequence (exclusive lower bound). listRequestIds
returns the request IDs currently retained, in insertion order.
TODO: cross-process live tail.
Methods
appendEvent()
appendEvent(requestId, event): Promise<void>;
Parameters
requestId
string
event
Returns
Promise<void>
flush()
flush(requestId): Promise<void>;
Parameters
requestId
string
Returns
Promise<void>
getEvents()
getEvents(requestId, fromSequence?): Promise<TraceEvent[]>;
Parameters
requestId
string
fromSequence?
number
Returns
Promise<TraceEvent[]>
listRequestIds()
listRequestIds(): Promise<string[]>;
Returns
Promise<string[]>
TransportBindings
Outputs returned from adapter.createBindings. The host's outer factory
wires routes into the public method dispatcher.
Properties
routes?
routes?: TransportRoute[];
HTTP routes for HTTP-shaped transports.
start?
start?: () => void | Promise<void>;
Optional async setup hook called by the host after all adapters' bindings are collected. Errors abort host startup.
Returns
void | Promise<void>
stop?
stop?: () => void | Promise<void>;
Optional teardown hook called when the host is torn down.
Returns
void | Promise<void>
TransportRoute
Single HTTP route exposed by an adapter. The host wires these into the
outer { GET, POST, PATCH, DELETE } dispatcher.
Properties
handler
handler: (req, ctx) => Promise<Response>;
Parameters
req
Request
ctx
params
Record<string, string>
Returns
Promise<Response>
method
method: "GET" | "POST" | "PATCH" | "DELETE" | "PUT";
path
path: string;
Path pattern; framework normalizes leading slash.
UserStore
Extends
DeltaStoreOps<UserRecord>
Methods
delete()
delete(id): Promise<void>;
Parameters
id
string
Returns
Promise<void>
deleteField()?
deleteField?(
id,
path,
expectedVersion,
updatedAt
): Promise<SetResult<UserRecord<JsonObject>>>;
Remove the value at path inside the record's state slice. For a
depth-2 path ["field", "key"] this deletes state.field.key, leaving
sibling keys intact. A missing key is a no-op (version still bumps).
Parameters
id
string
path
string[]
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<UserRecord<JsonObject>>>
Inherited from
DeltaStoreOps.deleteField
get()
get(id): Promise<UserRecord<JsonObject> | undefined>;
Parameters
id
string
Returns
Promise<UserRecord<JsonObject> | undefined>
incField()?
incField?(
id,
path,
delta,
expectedVersion,
updatedAt
): Promise<SetResult<UserRecord<JsonObject>>>;
Atomically add delta to the numeric value at path inside state.
Treats a missing key or null as 0; throws via the adapter's normal
error surface, writing nothing, if a value is already present and is not
a number. Other record fields are preserved unchanged.
Parameters
id
string
path
string[]
delta
number
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<UserRecord<JsonObject>>>
Inherited from
DeltaStoreOps.incField
list()
list(options?): Promise<UserRecord<JsonObject>[]>;
Parameters
options?
Returns
Promise<UserRecord<JsonObject>[]>
patchField()?
patchField?(
id,
path,
value,
expectedVersion,
updatedAt
): Promise<SetResult<UserRecord<JsonObject>>>;
Replace the value at path inside the record's state slice. Equivalent
to a shallow merge of { [path[0]]: value } into state for depth-1
paths. The remainder of the record (other state fields, metadata,
top-level columns) is preserved unchanged.
Parameters
id
string
path
string[]
value
unknown
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<UserRecord<JsonObject>>>
Inherited from
DeltaStoreOps.patchField
pushToArray()?
pushToArray?(
id,
path,
values,
expectedVersion,
updatedAt
): Promise<SetResult<UserRecord<JsonObject>>>;
Append values (in order) to the array at path inside state. Treats
a missing key as an empty array; throws via the adapter's normal error
surface if a value is already present and is not an array, including
null. Other record fields are preserved unchanged.
Parameters
id
string
path
string[]
values
unknown[]
expectedVersion
ExpectedVersion
updatedAt
number
Returns
Promise<SetResult<UserRecord<JsonObject>>>
Inherited from
DeltaStoreOps.pushToArray
set()
set(
id,
value,
expectedVersion
): Promise<SetResult<UserRecord<JsonObject>>>;
See SessionStore.set for CAS semantics.
Parameters
id
string
value
expectedVersion
ExpectedVersion
Returns
Promise<SetResult<UserRecord<JsonObject>>>
WakeStore
Wake persistence. Optional on the store registry: an adapter written before it still type-checks and loads, and a host whose stores keep no wakes logs once and pays debts on its fast paths only.
- owe writes or coalesces: one wake per key (resolver identity
included), keeping the EARLIER due time and the LATER
landBy, and bumping the version. - move and clear are conditional on the version a pass read, so a wake written during the pass survives it. Neither bumps the version.
Methods
clear()
clear(key, version): Promise<boolean>;
Delete the wake, if it is still at version. true when cleared.
Parameters
key
version
number
Returns
Promise<boolean>
earliestDueAt()
earliestDueAt(): Promise<number | null>;
The earliest due time of any wake, or null when none is kept.
Returns
Promise<number | null>
get()
get(key): Promise<WakeRecord | null>;
The wake kept under key, or null.
Parameters
key
Returns
Promise<WakeRecord | null>
listDue()
listDue(now, limit): Promise<WakeRecord[]>;
Wakes due at or before now, earliest first, at most limit.
Parameters
now
number
limit
number
Returns
Promise<WakeRecord[]>
move()
move(
key,
version,
dueAt
): Promise<boolean>;
Move the wake to dueAt, if it is still at version. true when moved.
Parameters
key
version
number
dueAt
number
Returns
Promise<boolean>
owe()
owe(input): Promise<WakeRecord>;
Write the wake, or coalesce into the one already kept under its key.
Parameters
input
Returns
Promise<WakeRecord>
WebhookProviderDefinition
How to speak one provider's webhook protocol. Supplied by the host at
adapter mount, keyed by the provider name that matches the flow's
webhooks[provider] declaration.
Properties
acknowledge?
acknowledge?: (event) => BodyInit | null;
Optional handshake. When it returns a non-null body, the adapter responds
200 with that body and does NOT dispatch — used for Slack's
url_verification challenge.
Parameters
event
WebhookInboundEvent
Returns
BodyInit | null
deliveryId?
deliveryId?: (payload, headers) => string | undefined;
Extract a stable per-delivery id for provenance / downstream dedup.
Parameters
payload
unknown
headers
Headers
Returns
string | undefined
eventType?
eventType?: (payload, headers) => string | null;
Extract the event-type discriminator used to match the flow's on keys.
Required when any subscribed flow uses on. Provider-specific: Stripe
payload.type, GitHub headers.get("x-github-event"), etc.
Parameters
payload
unknown
headers
Headers
Returns
string | null
parse?
parse?: (rawBody, headers) => unknown;
Parse the raw body to a payload. Default: JSON.parse(utf8(rawBody)).
Parameters
rawBody
Uint8Array
headers
Headers
Returns
unknown
verify
verify: (rawBody, headers) => boolean | Promise<boolean>;
Verify the request is authentically from the provider over its raw bytes.
Returning false (or throwing) rejects the delivery with 401. Compose
stripeWebhookVerifier / githubWebhookVerifier / slackWebhookVerifier
/ createWebhookVerifier, or supply your own.
Parameters
rawBody
Uint8Array
headers
Headers
Returns
boolean | Promise<boolean>
Type Aliases
AcrossSessionsOwner
type AcrossSessionsOwner = object;
The owner a read across sessions is scoped to: the same user, tenant and organization, each exact, absent matching only absent.
Properties
orgId
orgId: string | undefined;
tenantId
tenantId: string | undefined;
userId
userId: string;
AcrossSessionsQuery
type AcrossSessionsQuery = object;
One page of ResourceStateStore.listAcrossSessions: the live
session-scoped rows under keyPrefix in every session owner holds (any
parentage), ordered by the session's storage key, then the row's key, both
in byte (code-point) order. Rows strictly after after, at most limit.
A SQL store answers it in one statement joined to the sessions table on the
full owner; a store that keeps records in JavaScript walks the owner's
sessions. Rows are a superset: the engine checks each against the
collection's pattern, the owner's per-row admission and, for an index
filter, the declared index, after the read.
Properties
after?
after?: object;
The last row of the previous page, by session storage key and row key.
key
key: string;
sessionKey
sessionKey: string;
index?
index?: object;
Only rows with an entry of value for the stored index index of
collection, plus every row of a session whose index is not built there
(a store without index verbs ignores it and answers every row).
collection
collection: string;
index
index: string;
value
value: string;
key?
key?: string;
Only the row at this exact key in each session.
keyPrefix
keyPrefix: string;
The collection's storage prefix: "" or ending in /.
limit
limit: number;
owner
owner: AcrossSessionsOwner;
AcrossSessionsStoredRow
type AcrossSessionsStoredRow = object;
One row ResourceStateStore.listAcrossSessions answers.
Properties
indexBuilt?
indexBuilt?: boolean;
With an index filter, on a store with index verbs: whether the row's
session has that index built, read in the same statement. The engine
builds a session's index the first time a read meets it unbuilt.
key
key: string;
session
session: Pick<SessionRecord, "flowKind" | "flowId" | "userId" | "orgId" | "tenantId">;
The session's owner and flow, as its record holds them, read in the same statement: what the engine's per-row admission judges, so a page costs no session read of its own.
sessionKey
sessionKey: string;
The session's storage key (resolveSessionStorageKey).
state
state: JsonObject;
version
version: number;
ActiveRequestEntry
type ActiveRequestEntry = object;
Properties
actionName
actionName: string;
flowId?
flowId?: string;
The owning flow instance's id. See SessionRecord.flowId.
flowKind
flowKind: string;
input?
input?: unknown;
lastHeartbeatAt
lastHeartbeatAt: number;
metadata?
metadata?: Record<string, unknown>;
orgId?
orgId?: string;
queuedAt?
queuedAt?: number;
When the entry was registered at enqueue time for an EXTERNAL runner and no worker has claimed it yet.
Present means "accepted into a queue, not yet being worked on". For such an
entry lastHeartbeatAt measures how long the job has waited, not how long
ago a worker died — nothing is beating for it because nothing is running
it. Reading that age as death is how a valid queued job gets marked
interrupted and re-dispatched alongside the job the queue still holds.
Absent means claimed (or in-process), which is the legacy shape. An
entry written before this field existed, and every entry runAction
writes, omits it and is governed by lastHeartbeatAt exactly as before.
Guard with != null, never truthiness — 0 is a valid instant.
The claim transition needs no separate write: runAction re-registers the
whole entry when the worker picks the job up, and that replacement simply
has no queuedAt.
requestId
requestId: string;
sessionId?
sessionId?: string;
source
source: string;
Inbound transport provenance — see RequestRecord.source.
startedAt
startedAt: number;
tenantId?
tenantId?: string;
Bare tenant id this request runs under. Carried so recovery can re-dispatch the retry within the same tenant's session. Undefined for single-tenant requests.
userId
userId: string;
BlobClaimResult
type BlobClaimResult = "claimed" | "already-owned" | "not-found" | "owned-elsewhere";
The outcome of a claim.
claimed: it was held for this uploader and now belongs to the owner.already-owned: the same owner already holds it (a retried send).not-found: no such file, or it was uploaded by someone else. One answer for both, so an id is not a way to learn about another person's upload.owned-elsewhere: this uploader's file, already claimed by another owner.
BlobPut
type BlobPut = object;
A new file for BlobStore.put. The id is the caller's: the engine generates it.
Properties
bytes
bytes: Uint8Array;
filename?
filename?: string;
id
id: string;
mediaType
mediaType: string;
uploader
uploader: BlobUploader;
BlobRecord
type BlobRecord = object;
What the store keeps about one file, beside its bytes.
Properties
admitted?
admitted?: boolean;
true once a send that named it was admitted: no later refusal hands it back.
createdAt
createdAt: number;
Epoch ms of the upload.
filename?
filename?: string;
id
id: string;
The blob id (b_…), the part of fsd-blob:<id> after the scheme.
mediaType
mediaType: string;
owner?
owner?: string;
The owner a message claimed it into. Absent while it is held for its uploader.
pendingSends?
pendingSends?: string[];
The sends that named it into owner and are not yet admitted or refused.
A refused send hands the file back only when no other send is pending and
none was admitted. Absent on a record written before sends were tracked,
which reads as admitted.
size
size: number;
Bytes in the file.
uploader
uploader: BlobUploader;
BlobUploader
type BlobUploader = object;
Who uploaded a file: the verified caller at upload time.
Properties
orgId
orgId: string;
userId
userId: string;
BusTopic
type BusTopic = object;
A topic as the server names it: a scope, the scope's id (the bare session
id, the user id or the org id), the tenant, and optionally one resource
under the scope. tenantId is required, so no subscriber hears another
tenant's notices; a single-tenant app's tenant is "". Adapters derive
their channel names from it.
owner is the bus's own scope for an owner's change topics, the topics a
read across sessions is heard on (owner-topic.ts): its id names a user
and an organization. A client names one as a user topic.
Properties
id
id: string;
resource?
resource?: string;
scope
scope: TopicScope | "owner";
tenantId
tenantId: string;
ChangeListener
type ChangeListener = (notice) => void;
Called with each notice a subscription hears.
Parameters
notice
Returns
void
ChangeNotice
type ChangeNotice = object;
One change: the topic it happened under, its kind, and optionally the request that made it and the ids of what changed. Never the rows that changed.
Properties
ids?
ids?: string[];
The ids of what changed, when the publisher holds them (WireNotice.ids).
Absent means read everything, and no ids beats ids: a fold of a notice
with ids and one without carries none.
kind
kind: ChangeKind;
origin?
origin?: object;
The request that made the change, when a request made it.
requestId
requestId: string;
partition?
partition?: string;
On a board notice, the ledger partition the row was added to, raw: the
bus is the server's own, and the push edge sends it to a browser only as
an opaque key (WireNotice.partition, push/partition-key.ts). Absent:
any partition. A fold of notices in two partitions carries none.
topic
topic: BusTopic;
ConditionalRequestFields
type ConditionalRequestFields =
| ConditionalRequestBodyFields & object
| ConditionalRequestBodyFields & ConditionalStatusTransition;
Fields RequestStore.setFieldsIfStatus may write.
Derived from RequestRecord rather than hand-listed, minus the fields that are not a plain part of the record body:
id/version/createdAt— identity and CAS bookkeeping, owned byset.incarnation— identity, written once when the record is created.state— has its own versioned verbs (patchField/incField/pushToArray).items— lives in a child table on the persistent adapters, written viapersistItems.updatedAt— supplied as an explicit argument, mirroring the delta verbs.- The indexed access-path fields (
flowKind,flowId,userId,sessionId,orgId,tenantId) — denormalized into columns by the SQL adapters.
status and result are writable only together, as a
ConditionalStatusTransition: a final status always lands with the
result built for it, so a write carries both or neither.
ConditionalStatusTransition
type ConditionalStatusTransition = object;
A status change a RequestStore.setFieldsIfStatus write may carry:
the record moves to status only while its current status is
one the predicate allows, decided in the same atomic step.
Build it with settledRecordFields, which pairs a status with its result.
A result of undefined removes any stored result, the same as a
whole-record final-status write does. Adapters that index status in a
column update the column in the same write.
Properties
result
result: RequestActionResult | undefined;
status
status: RequestStatus;
ConditionalWriteResult
type ConditionalWriteResult = object;
Outcome of RequestStore.setFieldsIfStatus.
status is the status the adapter found under the same atomic step that
evaluated the predicate, so a caller can pick its own error without a second
read that could observe a different record.
applied | status | Meaning |
|---|---|---|
true | the matched status | The predicate held and the fields were written |
false | the status found | A record exists but its status is outside the predicate |
false | undefined | No record exists at this id |
Properties
applied
applied: boolean;
status?
status?: RequestStatus;
ContentScopeType
type ContentScopeType = "session" | "user" | "org";
Scope discriminator for content storage. Excludes "request" since request-scoped resources are not supported.
CreateExecutionContextOptions
type CreateExecutionContextOptions<TRequestState, TSessionState, TUserState, TOrgState> = object & CreateExecutionContextSession;
Type Parameters
TRequestState
TRequestState extends JsonObject = JsonObject
TSessionState
TSessionState extends JsonObject = JsonObject
TUserState
TUserState extends JsonObject = JsonObject
TOrgState
TOrgState extends JsonObject = JsonObject
Type Declaration
actionName
actionName: string;
durabilityEnabled?
durabilityEnabled?: boolean;
Whether a DurabilityProvider is configured. Guards ctx.suspend().
effectiveRuntimeConfig?
effectiveRuntimeConfig?: RuntimeConfig;
The runtime config THIS request is actually running under.
Deliberately not folded into requestHost above: that bag rides the shared
runtimeConfig.requestHost object, which is process-wide, and this value is
per-request. A caller may hand runAction a derived config — fsdev run
builds { ...appConfig, modelResolver, logger } so --model applies — and
a detached child is that request's own work continued in the background, so
it inherits this rather than whatever the host was constructed with. Without
it a --model run's background work silently resolved the app's default
model, which is precisely what --model exists to control.
Absent → a detached child falls back to the dispatching host's own config, which is the correct answer when no caller derived one.
errorCapture?
errorCapture?: ErrorCaptureHandler;
Opt-in error-capture sink. When set, runtime block failures are delivered to it with provider-neutral context. Absent → no capture.
flow
flow: FlowInstance;
input?
input?: unknown;
logger?
logger?: RuntimeLogger;
metadata?
metadata?: Record<string, unknown>;
modelResolver?
modelResolver?: ModelResolver;
orgId
orgId: string;
The organization this execution runs under. Required —
runAction validates it before building a context, so every context is
built from an identity that already names one.
orgState?
orgState?: TOrgState;
principalKind?
principalKind?: PrincipalKind;
The kind of the principal this run runs as, as its door set it
(context/principal.ts). Absent → the request record's, then the
session's; a run that creates its session with none is a machine's.
recordRead?
recordRead?: (read) => void;
Called with each scope state and resource a block of this run reaches. Set by the view runner.
Parameters
read
RecordedRead
Returns
void
refuseModelCalls?
refuseModelCalls?: boolean;
Refuse every model call with ViewModelCallError. Set by the view runner (D2).
requestHost?
requestHost?: RequestHostConstructionInputs;
Construction inputs for the request-host seam. Hosts supply the
inputs; createExecutionContext builds the bundle once and every nested
scope inherits the same reference.
Absent → no seam is attached, and requireRequestHost(ctx) throws by name.
That is the correct state for a caller that does not execute requests
through a host (a unit test, a hand-built context).
requestId
requestId: string;
requestState?
requestState?: TRequestState;
requestTaskId?
requestTaskId?: string;
The task the request is for, from the action's taskOf. Every scope
that no nearer _markTaskScope mark covers stamps it as taskId on the
items it emits. Set by runAction from the parsed input, never from
metadata.
resolvedBy?
resolvedBy?: string;
The resolver identity that produced the principal (Principal.resolvedBy). Absent → the request record's, or none.
response?
response?: ResponseEmitterHandle;
resumeContext?
resumeContext?: ResumeContext;
The suspension resolution ctx.suspend() returns at the gate named by its
pendingBlockLogicalId. Set by runAction on a same-request continuation
only; never read from metadata, which callers control.
runsCarriedCore?
runsCarriedCore?: boolean;
Whether the run's handler was carried on its dispatch rather than found on the flow (a dynamic schedule's fire). Such a run never parks: whatever continued it would re-run it from its record, which holds no handler.
sessionState?
sessionState?: TSessionState;
settings?
settings?: FlowStateSettings;
Instance-level settings exposed on every block as ctx.settings.
sideChainSignal?
sideChainSignal?: AbortSignal;
Background-work abort signal. Attached to every context as
_requestSideChainSignal and substituted for ctx.signal inside
.sideChain() task trees. Fires only on explicit user-requested abort, not
on transport-level teardown. Absent for non-server callers.
signal?
signal?: AbortSignal;
source?
source?: string;
Inbound transport provenance written to the initial RequestRecord.
Defaults to "http" for callers that don't supply one.
stores
stores: StoreRegistry;
tenantId?
tenantId?: string;
Optional tenant the request runs under.
tracingLevel?
tracingLevel?: TracingLevel;
Tracing verbosity for observability snapshots. Threaded onto
every block context as _tracingLevel. Unset → the runtime falls back to
resolveTracingLevel() (env / observability default).
userId?
userId?: string;
userState?
userState?: TUserState;
view?
view?: ViewRunContext;
ctx.view on every block of the run. Set by the view runner.
viewScope?
viewScope?: "session" | "user" | "org";
The scope of the view this run is, which decides the session reads it may
make: a session or user view reads the caller's sessions, an org view
none. Set by the view runner. Absent → a user view when noSession.
CreateFlowApiRouterOptions
type CreateFlowApiRouterOptions = object;
Public router adapter options.
Properties
adapters?
adapters?: InboundTransportAdapter[];
Additional inbound transport adapters mounted alongside the built-in
HTTP adapter and scheduled endpoint. Routes from every adapter merge into the returned
{ GET, POST, PATCH, DELETE } dispatcher; path collisions throw a
TransportRouteCollisionError at construction time.
arbiter?
arbiter?: ConcurrencyArbiter;
Concurrency arbiter for this router's host. Defaults to a fresh one.
Passed by createFlowState when it also built a host for detached
dispatch, so a declared queue/reject policy is enforced once across the
process rather than once per host.
debugAllowAnonymousLocal?
debugAllowAnonymousLocal?: boolean;
Permit requests with no Origin header (e.g. curl, server-side fetches,
same-origin browser GETs) to reach debug endpoints when the gate is
enabled. Default false; when unset, falls back to the
FSDEV_DEBUG_ALLOW_ANONYMOUS_LOCAL=1 env flag. fsdev dev opts in,
since it binds 127.0.0.1 and its DevTool's same-origin GETs send no
Origin.
Security note: the origin gate is light defense-in-depth, not strong auth. With this on, any headerless client that can reach the server reaches the surface regardless of physical location, so only turn it on for a server bound to loopback.
debugAllowedOrigins?
debugAllowedOrigins?: string[];
Additional origins permitted to reach debug endpoints. Loopback
(http://localhost*, http://127.0.0.1*, http://[::1]*) is allowed
by default. Matching is by origin prefix.
debugCountLimit?
debugCountLimit?: number;
Cap on the number of keys enumerated when computing collection counts
for the debug tree. Counts beyond this are reported as truncated: true.
Default 1000 — bounds cost on org/flow-scope collections without
starving the tree response.
debugEndpointsEnabled?
debugEndpointsEnabled?: boolean;
Enable the privileged read-only debug endpoint surface under
/api/flows/sessions/:id/debug/resources*. Fail-closed: default
false. Explicit true always wins over the env flag. When
undefined, falls back to process.env.FSDEV_DEBUG_ENDPOINTS === "1".
The DevTool consumes this surface; fsdev dev opts in automatically.
Production deployments must opt in deliberately.
defaultSseHeartbeatMs?
defaultSseHeartbeatMs?: number;
Default SSE wire heartbeat interval in milliseconds. Applied to every
live and GET-attach SSE response when the per-flow
request.sseHeartbeatMs is unset. The heartbeat keeps NAT/proxy idle
timeouts from closing the connection and gives clients a robust
inactivity signal.
Default: 15000 (15 seconds). Set to 0 to disable.
detectInterruptedOnStartup?
detectInterruptedOnStartup?: boolean;
Whether to detect interrupted requests from previous runs on startup. Disable on serverless platforms where background queries on init can exhaust the Postgres pool before actual requests are served. Default: true.
errorCapture?
errorCapture?: ErrorCaptureHandler;
Opt-in error-capture sink. Block-aware: routes runtime block failures to an external observability service with the failing block's identity. Forwarded verbatim into the runtime config. Off by default.
maxChildSessionListLimit?
maxChildSessionListLimit?: number;
Largest limit the child-session listing route accepts. Default 100.
Raise it for deployments whose conversations start more child sessions than that: the list a client reads is all-time history, so any fixed ceiling eventually hides the oldest finished work. Raise it deliberately — each row resolves its status from the request store and clients re-read the list on every interaction, so a larger ceiling costs more per turn.
maxRecordedValueBytes?
maxRecordedValueBytes?: number;
Largest block output or tool result, in serialized bytes, that a request
records whole in its items. Larger values are recorded as an omitted
placeholder with their size and a preview; the run keeps the full value.
Default 256 KiB.
maxResponseBufferSize?
maxResponseBufferSize?: number;
modelResolver?
modelResolver?: ModelResolver;
noticeIds?
noticeIds?: NoticeIdScopes;
Which topic scopes' notices may name what changed. On by default; pass
{ org: false } where even an org's change timing is sensitive: no org
notice then reaches a browser with ids or a collection entry's key, and
every org resource watcher reads whole on any entry's change. Read by
every push edge of this router.
onBackgroundWork?
onBackgroundWork?: (promise) => void;
Called with a promise that must complete for background action execution
to finish. On serverless platforms, pass this promise to waitUntil()
so the function instance stays alive after the 202 response is sent.
Without this, fire-and-forget runAction may be killed before persisting
results, causing stream 404s and lost data.
Parameters
promise
Promise<unknown>
Returns
void
onError?
onError?: (error, context) => void;
Parameters
error
Error
context
method
string
path
string
Returns
void
publicReentrySources?
publicReentrySources?: readonly string[];
Transport sources this deployment adds to the public re-entry allow-list.
retry, continue and resume admit http, mcp and scheduled
and refuse everything else with a not-found. That default is
right for a source nobody named, but InboundTransportAdapter.source is an
open string: a transport you wrote stamps a source the framework cannot
know about, and its requests would lose re-entry with no way to get it
back. Name those sources here.
Only your own transports. webhook and the framework's detached-dispatch
source are refused at construction — a webhook handler is reachable only
behind signature verification and a detached dispatch is not caller-
addressed at all, so re-entering either from a public route would run it
with caller-supplied input.
queuedGraceMs?
queuedGraceMs?: number;
How long a request handed to an external runner may sit unclaimed in the queue before a sweep treats it as lost (milliseconds).
A queued request has no executor heartbeat — nothing is running it yet — so
its age measures queue wait rather than worker death, and
staleSweepThresholdMs cannot answer for it. Raise this when a legitimate
backlog can exceed the default; too low and a valid queued job is marked
interrupted and re-dispatched while the queue still holds it.
Must be finite and non-negative; the host throws at construction otherwise.
This is the only bound on a queued entry — a value nothing can exceed would
leave a lost job reported live indefinitely. 0 reaps a queued request as
soon as it is stale.
Default: 600000 (10 minutes).
registry
registry: FlowRegistry;
resolvePrincipal?
resolvePrincipal?: PrincipalResolver;
Host-level fallback principal resolver, called when an inbound flow has
no authentication.resolvePrincipal of its own. Defaults to
defaultBodyUserIdPrincipalResolver, which reads body.userId from
the parsed HTTP body. Per-flow defineFlow({ authentication }) always
wins over this fallback.
runner?
runner?: FlowRunner;
Controls where flow actions execute. Default: in-process via runAction. Set to a FlowRunner implementation to route execution to an external worker (e.g., BullMQ WorkerRunner).
sealingSecret?
sealingSecret?: string;
The host's sealing secret (RuntimeConfig.sealingSecret). Default: process.env.FSD_SEALING_SECRET.
settings?
settings?: FlowStateSettings;
Instance-level settings threaded onto every block as ctx.settings.
shutdownDrainMs?
shutdownDrainMs?: number;
How long disposing the router waits for the requests its due wakes
started, and for any request in the process that still owes
its request-end hooks, before it goes on (aborting the wakes'
requests). One budget for both. Default 10 s. An
aborted pass leaves its wake, which the sweeper had already moved on, so
the next host fires it again. disposeFlowApiRouter(router, { drainMs })
overrides it per call, for a host whose shutdown grace is partly spent.
staleSweepIntervalMs?
staleSweepIntervalMs?: number;
How often the server-internal stale-request sweeper runs (milliseconds).
The sweeper marks in_progress requests whose registry heartbeat has
stopped as interrupted, releasing session locks for the next action.
Default: 30000 (30 seconds). Set to 0 to disable.
staleSweepThresholdMs?
staleSweepThresholdMs?: number;
Heartbeat-age threshold (milliseconds) used by the stale-request sweeper to decide that an active request has gone stuck. Should be at least 2× the executor's registry heartbeat (default 10s) to avoid false positives. Default: 60000 (60 seconds).
stores?
stores?: Partial<StoreRegistry>;
tenantIdHeader?
tenantIdHeader?: string;
HTTP header carrying the tenant id. Default x-tenant-id.
The extracted value is exposed on request/session/block context identities
(ctx.request.identity.tenantId). Optional — single-tenant apps ignore it.
Note: tenant-scoped store-key isolation is a separate, deferred change;
this only threads the axis through context.
tracingLevel?
tracingLevel?: TracingLevel;
Tracing verbosity for observability (non-durable) state snapshots:
"verbose" (per-step, for DevTool), "normal" (block
boundaries only), or "minimal" (none). Durable resume checkpoints are
unaffected. Unset → the runtime falls back to resolveTracingLevel()
(FSDEV_TRACING_LEVEL, else "verbose" in dev / "minimal" in prod).
Recommended: "normal" for production servers, "verbose" for fsdev dev.
voiceProvider?
voiceProvider?: VoiceProvider;
Voice provider for TTS and STT. Optional. If omitted, flows requesting TTS
silently skip synthesis (text continues), and the transcribe endpoint
returns 501. A per-flow voice.provider on the flow definition overrides
this at dispatch time.
CreateInboundTransportHostOptions
type CreateInboundTransportHostOptions = object;
Properties
arbiter?
arbiter?: ConcurrencyArbiter;
Concurrency arbiter to enforce policy through. Defaults to a fresh one.
Supplied when more than one host serves the same process, so a declared
queue/reject policy is enforced ONCE rather than once per host — two
arbiters hold two independent keyed gates, and a request admitted by one
knows nothing about a key the other is holding.
An arbiter over a backend shared across processes
(arbitratesAcrossProcesses) also arbitrates work this host hands to an
external runner.
registry
registry: FlowRegistry;
resolvePrincipal
resolvePrincipal: PrincipalResolver;
runner?
runner?: FlowRunner;
Controls where flow actions execute. Default: in-process via runAction. Set to a FlowRunner implementation to route execution to an external worker (e.g., BullMQ WorkerRunner).
runtimeConfig
runtimeConfig: RuntimeConfig;
Instance-level options forwarded verbatim through the execution chain.
The host reads maxResponseBufferSize / defaultSseHeartbeatMs /
onBackgroundWork for live-stream wiring, exposes the resolvers /
logger on the returned host, and passes the bundle to
runAction. See RuntimeConfig.
stores
stores: StoreRegistry;
CreateResponseEmitterOptions
type CreateResponseEmitterOptions = object;
Properties
maxBufferSize?
maxBufferSize?: number;
maxRecordedValueBytes?
maxRecordedValueBytes?: number;
Largest block output or tool result, in serialized UTF-8 bytes, that the
emitter records whole. Larger values are recorded as an
omitted placeholder; the producer keeps the real value. Defaults to
256 KiB, so an emitter built without the option is still limited.
now?
now?: () => number;
Returns
number
onEvent?
onEvent?: (event) => Promise<void> | void;
Parameters
event
Returns
Promise<void> | void
requestId
requestId: string;
startItemIndex?
startItemIndex?: number;
Starting item index for this emitter — the next item it assigns gets
startItemIndex + (items emitted so far). A same-request continuation
seeds this from the suspended request's last persisted item
index so re-entry items (suspension_resume + post-resume items) continue
after the pre-suspension log instead of restarting at 0. Without it,
persistent stores that order items by index (e.g. SQLite ORDER BY sequence ASC) would interleave the re-entry items ahead of the prior log
and break the pre + suspension + suspension_resume + post ordering.
startSequenceNumber?
startSequenceNumber?: number;
DeferWaitStep
type DeferWaitStep =
| {
kind: "claim-if-free";
patienceLeftMs: number;
retryInMs: number;
}
| {
kind: "line-up";
};
One step of a defer run that has not claimed its key yet.
Union Members
Type Literal
{
kind: "claim-if-free";
patienceLeftMs: number;
retryInMs: number;
}
Claim the key if nothing holds or waits on it (take with ifEmpty).
If something does, check again in retryInMs, or sooner when a wake
says the key emptied, but not past patienceLeftMs.
Type Literal
{
kind: "line-up";
}
Out of patience: take a place at the back of the key's line and wait for
its turn with no budget (planQueueWait with budgetMs: Infinity), so
newer hold runs no longer delay it.
EnablePushDeliveryOptions
type EnablePushDeliveryOptions = object;
Options for enablePushDelivery.
Properties
secret?
secret?: string | (() => string);
The key tickets are signed with. Every process behind one address needs the same one, so a ticket minted on one is accepted by another. Read on each sign and check. Default: a random key for this router.
ErrorCaptureHandler
type ErrorCaptureHandler = (event) => void | Promise<void>;
Operator-supplied error sink. Opt-in; omit for no capture. Fires once per
failing block (deduped to the leaf), and once more, marked final, for a
request that settles failed. Read-only: the return value is ignored.
May be async; the runtime awaits it inside a guard so a throw or rejection
can never affect the request. Keep it fast (enqueue-and-return).
Parameters
event
Returns
void | Promise<void>
ExecuteBlockResult
type ExecuteBlockResult<TOutput> = ExecutionResult<TOutput>;
Type Parameters
TOutput
TOutput = unknown
ExecutionContext
type ExecutionContext<TRequestState, TSessionState, TUserState, TOrgState> = BlockContext<TRequestState, TSessionState, TUserState, TOrgState> & Omit<InternalBlockContext, keyof BlockContext> & object;
Type Parameters
TRequestState
TRequestState extends JsonObject = JsonObject
TSessionState
TSessionState extends JsonObject = JsonObject
TUserState
TUserState extends JsonObject = JsonObject
TOrgState
TOrgState extends JsonObject = JsonObject
Type Declaration
actionName
actionName: string;
flow
flow: FlowInstance;
requestRuntime
requestRuntime: RequestRuntime;
stores
stores: StoreRegistry;
ExecutionResult
type ExecutionResult<TOutput> = object;
Type Parameters
TOutput
TOutput = unknown
Properties
durationMs
durationMs: number;
error?
error?: FlowError;
items
items: RuntimeItem[];
output
output: TOutput | undefined;
requestId?
requestId?: string;
Id of the dispatched request. Set by runAction (request-level execution)
so non-HTTP callers can correlate logs or attach a stream by it without
pre-generating an id. Absent for standalone block-level executions
(executeBlock), which have no request context.
FlowApiRouter
type FlowApiRouter = object;
Returned by createFlowApiRouter. The four method properties are the
canonical { GET, POST, PATCH, DELETE } dispatcher for the catch-all
route. The shape matches what Next.js / Vercel / Hono catch-all routes
expect; it is intentionally backward-compatible with the earlier
router so consumers indexing by HTTP method (router[method],
keyof typeof router) keep working.
For teardown of registered transport adapters, call
disposeFlowApiRouter(router) — keeping it off the router shape avoids
widening keyof for index-call consumers.
Properties
DELETE
DELETE: (req, ctx) => Promise<Response>;
Parameters
req
Request
ctx
NextRouteContext
Returns
Promise<Response>
GET
GET: (req, ctx) => Promise<Response>;
Parameters
req
Request
ctx
NextRouteContext
Returns
Promise<Response>
PATCH
PATCH: (req, ctx) => Promise<Response>;
Parameters
req
Request
ctx
NextRouteContext
Returns
Promise<Response>
POST
POST: (req, ctx) => Promise<Response>;
Parameters
req
Request
ctx
NextRouteContext
Returns
Promise<Response>
HmacAlgorithm
type HmacAlgorithm = "sha256" | "sha1" | "sha512";
HmacEncoding
type HmacEncoding = "hex" | "base64" | "base64url";
HmacSignatureParser
type HmacSignatureParser = (headerValue) => ParsedHmacSignature | null;
Parameters
headerValue
string
Returns
ParsedHmacSignature | null
HmacVerifier
type HmacVerifier = (rawBody, signatureHeader) => boolean;
Returned verifier. Returns true when at least one parsed signature
matches the computed HMAC over the canonical signed payload.
Parameters
rawBody
Uint8Array
signatureHeader
string | null | undefined
Returns
boolean
Hs256JwtVerifier
type Hs256JwtVerifier = (token) => JwtPayload | null;
HS256 JWT verifier. Returns the verified payload on success, null on
any verification failure (bad signature, malformed, expired, audience
mismatch). Use the returned payload to construct your ResolvedPrincipal.
Parameters
token
string | null | undefined
Returns
JwtPayload | null
InProcessFetch
type InProcessFetch = (input, init?) => Promise<Response>;
A fetch-shaped function over the engine in this process. Its signature is
the client's ClientFetch, so it is passed straight to a client's
fetcher option. Only the URL's path is read; its origin is ignored.
Parameters
input
RequestInfo | URL
init?
RequestInit
Returns
Promise<Response>
JobQueueMode
type JobQueueMode = "colocated" | "enqueue-only" | "process-only";
Which sides of a job queue this process runs.
"colocated"— enqueue and process in one process. The local-dev default: actions route through the queue and are processed in the same process against the same resolved runtime."enqueue-only"— enqueue only (the web process in a separated deployment). A dedicated processing process consumes the queue."process-only"— process only (a dedicated processing container). Build the samecreateFlowState(...)from shared config and callready(); no runner is installed and the router is typically never served.
LeaseTakeResult
type LeaseTakeResult =
| {
place: LeasePlace;
}
| {
heldBy: string;
};
take's answer: a place in the line, or (with ifEmpty) who holds the key.
LeaseTurn
type LeaseTurn =
| {
kind: "now";
}
| {
key: string;
kind: "when-free";
};
How a queued job reaches its turn on its concurrency key; see DispatchEnvelope.leaseTurn.
LiveRequestStream
type LiveRequestStream = object;
Properties
emitter
readonly emitter: ResponseEmitter;
readable
readonly readable: ReadableStream<Uint8Array>;
requestId
readonly requestId: string;
Methods
close()
close(): void;
Returns
void
OrgListOptions
type OrgListOptions = object;
Properties
limit?
limit?: number;
offset?
offset?: number;
userId?
userId?: string;
OrgRecord
type OrgRecord<TState> = ScopeRecordBase<TState> & object;
Type Parameters
TState
TState extends JsonObject = JsonObject
Type Declaration
orgId
orgId: string;
resources?
resources?: Record<string, JsonObject>;
userId?
userId?: string;
OwnedRecord
type OwnedRecord = object;
The two owner facts every owned record carries. flowId is absent on legacy rows.
Properties
flowId?
flowId?: string | null;
null and undefined both mean "written before the field existed".
flowKind
flowKind: string;
ParsedFlowRoute
type ParsedFlowRoute =
| {
kind: "list_flows";
}
| {
kind: "capabilities";
}
| {
actionName: string;
flowKind: string;
kind: "execute_action";
sessionId?: string;
}
| {
key: string;
kind: "read_scope_resource";
scope: string;
}
| {
key: string;
kind: "list_scope_entries";
scope: string;
}
| {
entry: string;
key: string;
kind: "read_scope_entry";
scope: string;
}
| {
actionName: string;
key: string;
kind: "send_resource";
scope: string;
}
| {
flowKind: string;
kind: "flow_identity";
}
| {
flowKind: string;
kind: "run_view";
sessionId?: string;
viewName: string;
}
| {
flowKind: string;
kind: "request_stream";
requestId: string;
}
| {
kind: "list_sessions";
}
| {
kind: "get_session";
sessionId: string;
}
| {
kind: "list_session_requests";
sessionId: string;
}
| {
kind: "list_session_children";
sessionId: string;
}
| {
kind: "get_session_state";
sessionId: string;
}
| {
kind: "session_stream";
sessionId: string;
}
| {
flowKind: string;
kind: "create_session";
}
| {
kind: "delete_session";
sessionId: string;
}
| {
kind: "patch_session_metadata";
sessionId: string;
}
| {
kind: "user_stream";
userId: string;
}
| {
kind: "user_stream_mint";
userId: string;
}
| {
kind: "transcribe";
}
| {
flowKind?: string;
kind: "upload_blob";
}
| {
blobId: string;
kind: "get_blob";
}
| {
flowKind: string;
kind: "retry_request";
requestId: string;
sessionId: string;
}
| {
flowKind: string;
kind: "continue_request";
requestId: string;
sessionId: string;
}
| {
kind: "active_requests";
}
| {
kind: "check_interrupted_requests";
userId: string;
}
| {
kind: "list_interrupted_requests";
userId: string;
}
| {
kind: "get_resource_content";
ref: string;
sessionId: string;
}
| {
kind: "get_collection_item_content";
ref: string;
sessionId: string;
topic: string;
}
| {
kind: "create_collection_item";
ref: string;
sessionId: string;
}
| {
kind: "update_resource_content";
ref: string;
sessionId: string;
topic: string;
}
| {
kind: "delete_collection_item";
ref: string;
sessionId: string;
topic: string;
}
| {
kind: "list_collection_state";
ref: string;
sessionId: string;
}
| {
kind: "get_collection_item_state";
ref: string;
sessionId: string;
topic: string;
}
| {
kind: "get_resource_manifest";
sessionId: string;
}
| {
flowKind: string;
kind: "abort_request";
requestId: string;
}
| {
flowKind: string;
kind: "resume_suspension";
requestId: string;
}
| {
flowKind: string;
kind: "answer_suspension";
requestId: string;
}
| {
flowKind: string;
kind: "request_status";
requestId: string;
}
| {
kind: "debug_storage";
}
| {
kind: "debug_list_resources";
sessionId: string;
}
| {
kind: "debug_list_suspensions";
sessionId: string;
}
| {
kind: "debug_list_collection_items";
ref: string;
sessionId: string;
}
| {
kind: "debug_get_resource_content";
ref: string;
sessionId: string;
}
| {
kind: "debug_get_collection_item_content";
ref: string;
sessionId: string;
topic: string;
}
| {
kind: "not_found";
};
PrincipalKind
type PrincipalKind = "person" | "machine";
Who a principal names: a person, or a machine (a schedule's gateway, the system user, a delivery).
PrincipalResolver
type PrincipalResolver = ResolvePrincipalFn;
Principal resolver hook. The framework owns the wiring; adapters never
implement auth themselves — they construct a PrincipalResolutionContext
and call host.resolvePrincipal. The host applies per-flow resolvers,
defaultUserId fallback, and requireUser enforcement around the value
returned by this function.
Re-exported under the historical PrincipalResolver name for backward
compatibility; ResolvePrincipalFn (in @flow-state-dev/core/types) is
the canonical name shared by defineFlow's authentication.resolvePrincipal.
PushDelivery
type PushDelivery = object;
A router's push delivery, as a host that serves the socket holds it.
Properties
transport
readonly transport: "websocket";
Methods
openSocket()
openSocket(userId, io): PushSocket;
Start the session for a socket that just opened on
/users/:userId/stream, for the userId its path names.
Parameters
userId
string
io
Returns
PushSocket
type PushSocket = object;
What a host tells the session about its socket.
Methods
closed()
closed(): void;
The socket closed, from either side. Idempotent.
Returns
void
receive()
receive(data): void;
A text message the client sent.
Parameters
data
string
Returns
void
PushSocketIO
type PushSocketIO = object;
How a session talks to its socket. The host moves frames; nothing else.
Methods
close()
close(code, reason): void;
Parameters
code
number
reason
string
Returns
void
send()
send(frame): void;
Parameters
frame
PushServerFrame
Returns
void
QueueWaitStep
type QueueWaitStep =
| {
delayMs: number;
kind: "wait";
}
| {
error: ConcurrencyQueueTimeoutError;
kind: "timeout";
};
One step of a waiting queue run: wait this long and check again, or give up.
ReadEventsFn
type ReadEventsFn = (requestId, fromSequence?) => Promise<RequestStreamEvent[]>;
Parameters
requestId
string
fromSequence?
number
Returns
Promise<RequestStreamEvent[]>
RequestActionResult
type RequestActionResult = object;
A request's action result, as its record stores it.
Carries the same keys as ExecutionResult's output and error. The
values can differ: the record stores a JSON copy of the output (a Date
becomes its ISO string, an object key whose value is undefined is left
out), while an in-process caller of runAction receives the live value. An
output JSON would otherwise change (NaN, ±Infinity, a function or symbol,
an undefined array slot, a Map, Set or Error) is not stored at all:
outputNotRecorded.
| Request ended | result |
|---|---|
completed / incomplete | { output }; {} when the action returned nothing |
failed | { error }, plus output when the action answered before a completion hook failed the request; {} when the writer had no cause |
| any of those, output not storable as JSON | outputNotRecorded: true in place of output |
aborted / interrupted / suspended | absent |
Properties
error?
error?: object;
Why the request failed, normalized as FlowError's code and message.
code
code: string;
message
message: string;
output?
output?: unknown;
The action block's own return value, stored as JSON.
outputNotRecorded?
outputNotRecorded?: true;
The action returned a value that cannot be stored as JSON (a BigInt, a
cycle), one JSON would silently change (NaN, ±Infinity, a function or
symbol, an undefined array slot, a Map, Set, Error or other
built-in container).
The status still landed; only the value was dropped.
Distinct from {}, which means the action returned nothing.
RequestListOptions
type RequestListOptions = object;
Properties
flowId?
flowId?: string;
Exact-owner filter; see SessionListOptions.flowId.
flowKind?
flowKind?: string;
Broad administrative grouping by definition kind. Not ownership.
limit?
limit?: number;
offset?
offset?: number;
orderBy?
orderBy?: "startedAtMs" | "updatedAt" | "none";
Sort key for the returned (and limited) set, descending. "updatedAt"
(default) preserves prior behavior. "startedAtMs" orders by
(request start time, id) so a limit-windowed read selects the
most-recently-started requests regardless of later out-of-order metadata
writes, and resolves an exact start-time tie deterministically. Adapters
that persist startedAtMs only inside the record blob order by the
equivalent created_at column (set to startedAtMs at creation, never
mutated).
"none" returns the matching set unordered. It is a
correctness bound rather than an optimisation: an existence check
(limit: 1 over a status set) that sorts is unbounded in the one
dimension it selects on — a session accumulates non-terminal records
whenever an approval gate expires, and those are exactly the rows such a
check selects, so a trailing sort on an uncovered column grows without
bound. Unordered, limit: 1 stops at the first matching row however many
exist. The returned order is the adapter's own and must not be relied on.
orgId?
orgId?: string;
Org filter. Same present-vs-absent NULL-safe exact-match
semantics as tenantId; see SessionListOptions.orgId for why the
column needed an option at all.
sessionId?
sessionId?: string | readonly string[];
Session filter. A single id matches by equality; an array matches set membership, so a question asked of many sessions at once (which of a session's child runs are unfinished) is one read rather than one read per session. An empty array matches nothing.
status?
status?: RequestStatus | readonly RequestStatus[];
Status filter. A single status matches by equality (unchanged); an array matches set membership, so "is any run of this session non-terminal" is one read rather than one read per member.
An empty array matches nothing — it is a filter that excludes everything, not an absent filter.
tenantId?
tenantId?: string;
Tenant filter. Exact-match isolation with deliberate
present-vs-absent semantics, because tenant records and no-tenant records
can share a bare sessionId:
- When the
tenantIdkey is present on the options object (including an explicitundefined), the store exact-matches it —undefinedmatches only records with no tenant. This is what isolates cross-turn history. - When the key is absent, no tenant filtering is applied (admin/debug "list everything" callers keep working).
createExecutionContext and the tenant-isolated routes always pass the key
(carrying the current request's tenant, possibly undefined).
userId?
userId?: string;
withItems?
withItems?: boolean;
If true, populate record.items for each returned record. Default
false. Adapters that store items separately (Postgres) avoid an
extra query per list when this is false; adapters that store items
inline ignore the flag.
RequestRecord
type RequestRecord<TState> = ScopeRecordBase<TState> & object;
Type Parameters
TState
TState extends JsonObject = JsonObject
Type Declaration
abortedAt?
abortedAt?: number;
abortRequested?
abortRequested?: boolean;
Whether cancellation has been requested for this request.
Readable here, but NOT writable through RequestStore.set. A
full record handed to set cannot change the stored value in either
direction — it can neither set the flag nor clear one. The only write path
is RequestStore.setFieldsIfStatus; the only cheap read path is
RequestStore.isAbortRequested.
The field is carried as a passenger by every full-record writer (they all
build { ...heldRecord, ...patch } from a snapshot taken before the flag
existed, the longest-lived being the execution context's run-lifetime
requestRef). Taking it off set's write surface is what makes those
writers harmless without changing a single call site.
boolean | undefined — read it with === true, never truthily.
actionName
actionName: string;
attachments?
attachments?: FileContent[];
The files the person's message carried, in reference form, as the parse
step checked them. What ctx.request.attachments reads, so a resumed or
queued run sees the same files. == null → none: records written before
the field have none.
completedAtMs?
completedAtMs?: number;
failedAtMs?
failedAtMs?: number;
finalizedAtMs?
finalizedAtMs?: number | null;
When the request's run finished writing under this id: set as the run's
last write, after onFinished, which follows the terminal status.
null: written by a version that stamps it, and the run has not finished (it is still running, or died before stamping; the stale-request sweep stamps a dead one).- absent: written before this field existed, so whether the run
finished is unknown. Tell the two apart with
=== null, never truthiness.
Session retention deletes a request only once this is set, so a run's late writes cannot land under an id that has been freed and reused.
flowId?
flowId?: string;
The owning flow instance's id. See SessionRecord.flowId.
flowKind
flowKind: string;
heartbeatsUntilFinalized?
heartbeatsUntilFinalized?: boolean;
Whether the run keeps heartbeating from its terminal write until it
stamps finalizedAtMs. Only then does a stale active-request entry mean
the run died in its tail, so only then may the stale-request sweep stamp
the record for it. false when heartbeats are off
(request.heartbeatIntervalMs: 0) or on a failure path, which stops
beating before onFinished; such a record is stamped only by its own run.
Absent on records from before the field: never stamped by the sweep.
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. A
screen draws its divider before that request and says the turns above it
are out of view. Absent when every earlier turn was in the window, and on
records written before this field existed (guard with == null).
historyStart.requestId
requestId: string;
incarnation?
incarnation?: string;
Which request this record is, among every request that has held its id.
Minted, not derived, like SessionRecord.lineageId: a random
token stamped once, when the record is first created
(createInitialRequestRecord), and carried unchanged by every later write.
The same-owner hand-off in claimRequestRecord keeps the stored value
rather than writing its own. A request id is the caller's to choose and
can be reused once retention deletes its record; the record created in its
place gets a new token, so anything keyed on it (a run workspace) does not
carry over. createdAt cannot do this job: two records can share a
millisecond.
Absent on records written before this field existed. Read it through
resolveRequestIncarnation (stores/scope-keys.ts), which derives a
stable value for those from createdAt, under a prefix no minted token
uses. Surfaced to blocks as ctx.request.incarnation.
input?
input?: unknown;
interruptedAt?
interruptedAt?: number;
items?
items?: RuntimeItem[];
The request's item log, trace rows included. Adapters that store items
separately may leave this undefined on list() results unless
RequestListOptions.withItems is true.
metadata?
metadata?: Record<string, unknown>;
orgId?
orgId?: string;
principalKind?
principalKind?: PrincipalKind;
The kind of the principal this request runs as, as its door set it
(context/principal.ts). A run started from this record (a continuation,
a queued job, a recovery) reads it, never a payload. == null on a
record written before the field.
resolvedBy?
resolvedBy?: string;
The resolver identity that produced the request's principal
(Principal.resolvedBy). == null → none: a run from this record
reaches no target whose flow has a resolver of its own.
result?
result?: RequestActionResult;
What the action came to, written in the same record write as the final
status. Built only by buildRequestActionResult
(execution/request-action-result.ts), so every writer of a final status
fills it the same way.
Read absence by status (guard with == null):
completed,incompleteorfailedwith noresult— no result was recorded: a record written before this field existed.abortedorinterrupted— never carries one; the status says it.in_progressorsuspended— not finished yet.
The engine stores the value; it never interprets it (a refusal convention
such as { ok: false } belongs to whoever reads it).
sessionId?
sessionId?: string;
source
source: string;
Provenance of the inbound transport that produced this request.
Set from InboundRequestEnvelope.source. Open string —
documented known-set: http | mcp | webhook | scheduled |
notification. Reads of records persisted before this field existed
default to "http" in the store implementations.
spentByModel?
spentByModel?: Record<string, ModelUsageEntry>;
What the request's model calls spent before it last suspended, by model.
Written by the engine when the request suspends, or when its
client went away and that run's ending has handed the spend on; a resume or
continuation starts its spend ledger from it, so
ctx.request.tokenUsage and the action's token budget count the whole
request, while a request-end hook is still handed only what each run spent.
spentHarnessRuns?
spentHarnessRuns?: HarnessRunSpend[];
The harness runs the request had spent when RequestRecord.spentByModel was written, as each was last reported. A resume or continuation starts its ledger's total from them, so a reader of the whole request's spend still counts a run an earlier ending handed on. Absent on a record written before it existed: no earlier harness run is carried.
spentThroughItemIndex?
spentThroughItemIndex?: number;
The last item index RequestRecord.spentByModel accounts for. A continuation after the process died counts the model usage its log's block traces carry past this index, since that run settled none. Absent: no settlement counted any, so every trace in the log counts.
startedAtMs
startedAtMs: number;
status
status: RequestStatus;
tenantId?
tenantId?: string;
Bare tenant id this request ran under. sessionId stays bare;
isolation of cross-turn history comes from filtering request.list by
the session's request scope (sessionRequestScope: sessionId,
tenantId, owner, organization and flow) rather than from namespacing the
sessionId field — which keeps request recovery a clean pass-through. Undefined for
single-tenant requests.
userId
userId: string;
RequestRuntime
type RequestRuntime = object;
Properties
actionName
actionName: string;
completedAtMs?
completedAtMs?: number;
failedAtMs?
failedAtMs?: number;
metadata?
metadata?: Record<string, unknown>;
requestId
requestId: string;
startedAtMs
startedAtMs: number;
status
status: RequestStatus;
RequestStreamEventWithId
type RequestStreamEventWithId = RequestStreamEvent & object;
Type Declaration
id
id: string;
ResourceIndexBuildEntry
type ResourceIndexBuildEntry = object;
One row's entries, as a build found them.
Properties
key
key: string;
The row's resource key.
values
values: string[];
The row's canonical value strings for the index being built.
ResourceIndexBuildStatus
type ResourceIndexBuildStatus = "unbuilt" | "building" | "built";
Whether a scope's index can answer a lookup. unbuilt: no build has
finished, or a write cleared it. building: a build has begun and nothing
has cleared it since. built: the index holds an entry for every live row
the collection covers.
ResourceIndexEntry
type ResourceIndexEntry = object;
One declared index's values for one row, as a set carries them.
Index entries let a collection be looked up by a field outside its key. The engine computes them from the app's declared indexes; a store only keeps them in step with the row and answers lookups. See ResourceStateIndexes.
Properties
collection
collection: string;
The collection's full declared pattern (not its storage prefix). Opaque to the store, except that it decides which keys the index covers.
index
index: string;
The index's stored name, its version included. Opaque to the store.
values
values: string[];
The row's canonical value strings for this index. Empty: the row has no value for it.
ResourceStateRow
type ResourceStateRow = VersionedRow<JsonObject>;
A stored row as every adapter models it internally.
ResourceStateSetOptions
type ResourceStateSetOptions = object;
The optional last argument of ResourceStateStore.set.
Properties
indexEntries?
indexEntries?: ResourceIndexEntry[];
The row's entries for each index the writer declares. A store with ResourceStateStore.indexes commits them with the row, or not at all. A store without index verbs ignores them.
RunActionOptions
type RunActionOptions<TFlow, TActionName> = object;
Type Parameters
TFlow
TFlow extends FlowInstance = FlowInstance
TActionName
TActionName extends keyof TFlow["actions"] & string = keyof TFlow["actions"] & string
Properties
abortHandoff?
abortHandoff?: object;
An abort controller the caller registered under requestId before the
run started, with the incarnation it was tagged with. The run registers
it as its own instead of a fresh one, so a cancel that landed on it is
not lost in the handoff. A cancel that was aimed at another incarnation
than the one the run executes as is dropped, the same way the run treats
its own controller. signal is not a substitute: a signal carries a fire
but not whom it was for.
controller
controller: AbortController;
incarnation?
incarnation?: string;
actionName
actionName: TActionName;
attachments?
attachments?: FileContent[];
The files the person's message carries, in reference form. Written as a
file part per file after the text on the line userMessage writes,
recorded on the request, and shown to blocks as ctx.request.attachments.
Over HTTP the action route checks and claims them first; a direct caller
passes only files already claimed into the session.
flow
flow: TFlow;
input
input: unknown;
metadata?
metadata?: Record<string, unknown>;
Caller-supplied request metadata. Treated as caller-controlled: the
resumeContext and resumeOf keys are stripped before the run starts and
never resolve a suspension. Resuming goes through
RunActionOptions.resumeContext.
onItem?
onItem?: (item, kind) => void;
Live-subscription convenience for callers that run a flow outside the HTTP
transport (jobs, cron, queue consumers) and want to observe items as they
happen without assembling their own ResponseEmitter. Called for every
item as it is added / updated / done — the same live fan-out that feeds
connected SSE clients, so transient items (live-only, absent from the
persisted log) appear here too; do not re-filter them. Listener exceptions
are isolated and never break the run.
Parameters
item
OutputItem
kind
"added" | "updated" | "done"
Returns
void
onRegistered?
onRegistered?: () => void;
Fired once this run's activeRequests entry has committed — the point the
request becomes discoverable to a stream read, the stale-request sweeper
and recovery.
Exists because starting a run and having a run are different facts, and
only runAction knows when the second one becomes true. runAction is
async, so a caller holding its promise has a run that may still fail during
registration; a caller that wants "it exists" without waiting for "it
finished" has nothing else to await. The in-process runner turns this
into its handle's accepted, which is what a detached spawn awaits before
it lets go of the task it handed over.
Fires at most once, and never at all for a run that dies before registration — that failure surfaces on the returned promise, which is the signal a consumer pairs this with.
Registration is discoverability, not safety, and the difference is smaller than it looks. Setup after this point can still fail without recording anything — but a caller handing over durable work is protected by that work's own lease, not by this signal: if the run dies at any point, the lease lapses and the owner recovers the row. What this buys is that the failure is visible rather than silent, which is what a fire-and-forget caller has no other way to learn.
Returns
void
orgId
orgId: string;
The organization this run belongs to. Required.
runAction is the trusted direct-execution seam: it runs BELOW principal
resolution, so there is no resolver here to validate a caller and no
verified identity to fall back on. A caller that reached this function has
already decided who is running — the organization is part of that decision,
not something the framework can infer afterwards.
Pass the verified organization for an authenticated caller, or
DEFAULT_ORG_ID from @flow-state-dev/core for deliberate
single-organization development and system wiring.
principalKind?
principalKind?: PrincipalKind;
The kind of the principal this run runs as, as its door set it
(Principal.kind). Server-set, never a payload. Absent → the request
record's, then the session's; a run that creates its session with none is
a machine's, and reaches no other session.
replayMode?
replayMode?: boolean;
Same-request continuation flag. Set by continueRequest when a
suspended/interrupted request re-enters under its OWN id. Triggers replay
mode: prior persisted items are loaded into a ReplayLog so completed
blocks are injected (not re-run), a suspension_resume audit item is
emitted, and the terminal write merges prior + re-entry items. Inferred as
true when RunActionOptions.resumeContext is present and the
existing record is suspended.
requestId?
requestId?: string;
resolvedActionCore?
resolvedActionCore?: ActionCore;
Pre-resolved action core, set only by adapters for an event dispatch with
no static coordinate (the dynamic schedule). When present, runAction
runs it directly instead of resolving from flow. See
InboundRequestEnvelope.resolvedActionCore for the full contract and why
it adds no caller-addressed attack surface.
resolvedBy?
resolvedBy?: string;
The resolver identity that produced the principal (Principal.resolvedBy). Absent → none, which matches nothing.
responseEmitter?
responseEmitter?: ResponseEmitter;
resumeContext?
resumeContext?: ResumeContext;
The suspension resolution a same-request continuation injects — which
gate, approve/reject/skip, payload, resolver. Set by continueRequest
after the resume endpoint has validated the suspension; never derived from
metadata, which callers control.
Honoured only in replay mode, and only at the gate the replay log names as
pending: the runtime overwrites pendingBlockLogicalId from the log, so a
supplied value is ignored. On a run that is not a continuation it has no
effect and the gate suspends as usual.
retry?
retry?: RetryPolicy;
runtimeConfig
runtimeConfig: RuntimeConfig;
Instance-level options forwarded verbatim through the execution chain (resolvers, settings, logger, tracing). See RuntimeConfig.
sessionId
sessionId: string;
The session the run lands in. Required: every run names its session,
and its request record names it from the first write. A run that belongs
to no conversation passes oneOffSessionId() from
@flow-state-dev/core/helpers. Missing at run time (an untyped caller),
runAction throws SessionRequiredError before anything is written.
signal?
signal?: AbortSignal;
source?
source?: string;
Inbound transport provenance, propagated to RequestRecord.source and
ActiveRequestEntry.source. Defaults to "http" to preserve behavior
for callers that pre-date the transport adapter contract.
startItemIndex?
startItemIndex?: number;
Starting item index for the internally-created ResponseEmitter — the next
emitted item gets startItemIndex + (items so far). A same-request
continuation passes the suspended request's last persisted item
index so re-entry items continue after the prior log instead of restarting
at 0 (which would mis-order them on stores that sort by item index).
Ignored when responseEmitter is provided — the caller's emitter owns
index assignment.
startSequenceNumber?
startSequenceNumber?: number;
Starting sequence number for the internally-created ResponseEmitter —
the first emitted event gets startSequenceNumber + 1. Queue consumers
that re-run an action under the same requestId (e.g. a BullMQ retry
attempt) pass the last persisted sequence number so the per-request
event log stays strictly increasing across attempts; tailing clients
filter on sequence_number > cursor and would otherwise never see the
retry's events. Ignored when responseEmitter is provided — the
caller's emitter owns numbering.
stores
stores: StoreRegistry;
tenantId?
tenantId?: string;
userId
userId: string;
RuntimeLogger
type RuntimeLogger = object;
Properties
debug?
debug?: (message, context) => void;
Parameters
message
string
context
Record<string, unknown>
Returns
void
error?
error?: (message, context) => void;
Parameters
message
string
context
Record<string, unknown>
Returns
void
info?
info?: (message, context) => void;
Parameters
message
string
context
Record<string, unknown>
Returns
void
warn?
warn?: (message, context) => void;
Parameters
message
string
context
Record<string, unknown>
Returns
void
RuntimeLoggerLevel
type RuntimeLoggerLevel = "debug" | "info" | "warn" | "error";
ScheduleTickReport
type ScheduleTickReport = object;
What one tick did: each fire it sent and the endpoint's answer (0 when the dispatch threw).
Properties
dispatched
readonly dispatched: ReadonlyArray<ScheduleDispatch & object>;
ScopeChange
type ScopeChange = object;
Which scope changed, under which tenant, and which request changed it.
Properties
id
id: string;
The bare session id, the user id or the org id.
ids?
ids?: string[];
A collection entry's storage key, beside the path that names it (entryNotice). Never without resource.
kind
kind: Extract<ChangeKind, "state" | "resource">;
requestId?
requestId?: string;
The request that made the change, when one did.
resource?
resource?: string;
The resource's storage path, for a resource change.
scope
scope: TopicScope;
tenantId
tenantId: string | undefined;
SessionCreateRequest
type SessionCreateRequest = object;
What a create is checked against, and from.
Properties
flow
flow: BirthFlow;
fromCaller
fromCaller: boolean;
Whether state came from a caller (the create route's state, fsdev run --seed-session, an action's seed) rather than from flow code (a
dispatcher's child state). A caller's state may not set a serverOwned
field.
principal
principal: SessionCreatePrincipal;
principalKind?
principalKind?: PrincipalKind;
The kind of the principal creating the session: the run's, as its door
set it. Written on the record as principalKind, after the caller's
seed, so no request input can set it. Absent → a machine's (fail closed).
sessionId
sessionId: string;
The bare session id being created.
state?
state?: Record<string, unknown>;
The state the session starts with, before the flow's stateSchema parses
it. Absent is {}.
via
via: SessionCreatePath;
SessionListOptions
type SessionListOptions = object;
Properties
flowId?
flowId?: string;
Exact-owner filter: only records stamped with this flow instance id. A
legacy row with no flowId never matches, so a caller narrowing by owner
sees attributed history only.
flowKind?
flowKind?: string;
Broad administrative grouping by definition kind. Not ownership.
limit?
limit?: number;
offset?
offset?: number;
orderBy?
orderBy?: "updatedAt" | "createdAt";
Sort key for the returned (and limited) set, descending.
"updatedAt"(default) — today's behaviour, byte for byte."createdAt"— orders by(createdAt, id), both immutable, so a record that is written while a caller pages does not move.
The distinction is a paging correctness bound, not a preference: a session
record's updatedAt is rewritten whenever a run starts on it
(runAction.ts stamps latestRequestId and updatedAt together), so
under updated_at DESC a row can jump to the front of the order between
two pages — one record crosses the offset boundary and is never returned,
another is returned twice, and the caller cannot detect either. A
tie-breaker cannot repair a sort key that mutates.
Insertion is still not closed: a record created mid-walk lands at the front and shifts later pages by one. Closing that needs keyset paging.
orgId?
orgId?: string;
Org filter. Same present-vs-absent exact-match semantics as
tenantId: present (including an explicit undefined) exact-matches
NULL-safely, absent applies no filter.
The column has been written and indexed on all four adapters since org
scope shipped, but nothing could query it until this option existed — so
an enumerator would return rows the runtime treats as a different identity
(createExecutionContext throws OrgBindingMismatchError on a cross-org
adoption). Additive: every existing caller omits the key and is unchanged.
parentage?
parentage?: SessionParentage;
Parentage filter. Omitting this narrows to "top-level" —
a caller that asks for nothing gets only the sessions a person started.
Note the asymmetry with tenantId in this same object, which is the thing
a reader pattern-matching the two will get backwards: an absent tenantId
widens (every record passes), an absent parentage narrows. It is
deliberate. An un-tenanted list is an admin read, whereas an un-parented
list is the common read and has to be safe by default — otherwise every
caller written before parented sessions existed silently starts showing
internal machinery beside the user's own sessions.
Pass "all" to opt back into the unrestricted behaviour explicitly.
state?
state?: Readonly<Record<string, string>>;
Exact-match filter on top-level session-state fields: a record matches
when, for every entry, its state[field] is that string. Absent applies
no filter. The list route admits only the flow's readonly state fields,
which are fixed for a session's life; an adapter filters in its query,
never after it. Field names are plain identifiers.
tenantId?
tenantId?: string;
Tenant filter. See RequestListOptions.tenantId for the present-vs-absent exact-match semantics — they are identical here.
userId?
userId?: string;
SessionParentage
type SessionParentage =
| "top-level"
| "all"
| {
parentOf: string;
};
Which sessions a listing returns, by parentage. Three modes, each a named value so none is reachable only by omission or by a sentinel:
"top-level"— only sessions with no parent, i.e. the ones a person started. The default (see SessionListOptions.parentage)."all"— every session, parented or not. Reproduces the unrestricted behaviour listing had before this option existed; for admin, debug and recovery callers that genuinely want everything.{ parentOf }— only the children of that one session.
SessionRecord
type SessionRecord<TState> = ScopeRecordBase<TState> & object;
Type Parameters
TState
TState extends JsonObject = JsonObject
Type Declaration
coordinate?
coordinate?: string;
Which entry a child was dispatched for, as <type>:<target>, absent on a
session nothing dispatched. Same writer, same server-derived source, and the same
no-authority rule: see SessionRecord.topic, which carries the whole
contract for both fields.
description?
description?: string;
flowId?
flowId?: string;
The flow instance this record belongs to — the exact id of the instance
it was created under. Every new framework write stamps it; a record
persisted before the field existed reads back undefined (or null from
a store that nulls absent keys). Readers resolve it through
context/record-owner.ts, which is also where a legacy row's compatibility
rule lives: only known singleton history is attributed without a migration.
Distinct from SessionRecord.flowKind, which stays the definition's kind — descriptive metadata and a grouping filter, never an address that decides routing, authorization or which instance's declarations apply.
flowKind
flowKind: string;
incarnationToken?
incarnationToken?: string;
A random token minted once per birth (birthSession): what tells two
incarnations of one session id apart when their birth time (millisecond
resolution) and lineage (inherited or derived) match. set keeps the
stored value whatever a later write carries, as for principalKind.
== null on a record written before the field: compared by its birth
time and lineage instead (sameSessionIncarnation).
journal
journal: JournalEntry[];
latestRequestId?
latestRequestId?: string;
lineageId?
lineageId?: string;
The lineage this session belongs to — the address every resource
it declares sharedToLineage stores under.
Minted, not derived. A root session mints one when its record is created; every descendant inherits that same literal value at spawn. The address is therefore a value that is written once and read back, rather than something reconstructed at each read out of session identity — which is mutable, reusable, concurrently creatable, and has a legacy shape.
That is what makes the hard cases go away instead of needing handling. A deleted session id recreated by anyone gets a NEW record and therefore a new lineage, so a surviving descendant of the old lineage keeps its own address with no owner or incarnation conjoined into it.
Absent on records written before this field existed. Those are read as their own lineage keyed by their session storage key — safe because a recreated session always gets a record that carries the field, so two records can never both fall back to one id.
metadata?
metadata?: Record<string, unknown>;
orgId?
orgId?: string;
parentIncarnation?
parentIncarnation?: string;
The incarnation of the session that dispatched this one
(sessionIncarnation), recorded by the dispatch seam at the child's birth.
Binds the child to that parent record, not to its reusable bare id.
== null on a top-level session and on a child born before the field.
parentSessionId?
parentSessionId?: string;
Bare id of the session this session belongs to. Undefined for a
top-level session — one a person started — which is every session that
exists today. A record persisted before this field existed reads back as
undefined, and a store that nulls absent keys hands back null; both
mean top-level, so readers must guard with == null.
Bare, not tenant-namespaced, matching RequestRecord.sessionId:
isolation comes from conjoining tenantId in the list filter, not from
namespacing this field.
principalKind?
principalKind?: PrincipalKind;
The kind of the principal that created this session (context/principal.ts):
a person's, or a machine's (a schedule's gateway, the system user, a
delivery). A run in a machine's session reaches no session but its own.
Written once, by the birth (birthSession), from the creating run's
principal, never from a caller's input. set keeps the stored value
whatever a later write carries, so a stale whole-record write can't
change it.
== null on a record written before the field existed: classified from
its first request record instead (context/session-kind.ts).
resources?
resources?: Record<string, JsonObject>;
tags?
tags?: string[];
tenantId?
tenantId?: string;
Bare tenant id this session belongs to. The session record's
id is already tenant-namespaced (${tenantId}:${sessionId}); this field
keeps the bare tenant for cross-reference and SessionListOptions.tenantId
filtering. Undefined for single-tenant sessions.
title?
title?: string;
topic?
topic?: string;
Human-readable name for the body of work a child session was
dispatched for. Stamped by the dispatch seam
(context/create-request-host.ts) from the key the child was
derived from — never from SessionRecord.metadata, which is the
caller's own free-form bag and can say anything.
This field carries no authority, and neither does
SessionRecord.coordinate. evaluateAdoption together with the
key-occupied refusal (context/dispatch-run.ts) is the sole
discriminator for "is this session ours" — routing, authorization,
adoption and identity are decided there and nowhere else. Nothing may read
these two fields to make any of those decisions; they exist to put a
readable name on a row in a UI instead of an opaque derived id.
That restriction is exactly what makes keeping them safe. A second
discriminator could disagree with evaluateAdoption and hand a session to
the wrong owner; a display-only field has nothing to disagree with. Adding
a read of these fields to any decision path reintroduces that hazard and
is the change this note exists to stop.
Optional and additive. A child written before this field existed
reads back undefined, a store that nulls absent keys hands back null,
and an adopted legacy child is never backfilled — all three mean
unlabelled, which is a row a UI shows without a name, not an error. Guard
with == null.
userId
userId: string;
SessionRecordSeed
type SessionRecordSeed = Omit<SessionRecord, "lineageId" | "state"> & object;
A session record as a birth's caller builds it: everything but its state, which the birth parses and checks from the request, and the lineage id, which is minted unless the caller derives it.
Type Declaration
lineageId?
lineageId?: string;
Supplied by a caller that derives the lineage (a cross-flow child); minted otherwise.
SetResult
type SetResult<TRecord> =
| {
ok: true;
record?: TRecord;
version: number;
}
| {
conflict: {
currentValue: TRecord | undefined;
currentVersion: number;
};
ok: false;
};
Outcome of a CAS-aware Store.set. Encodes conflict as data rather than
throwing so retry loops stay on the hot path. On conflict the store returns
the current value and version so the caller can refresh its cache and
re-apply the mutator.
Type Parameters
TRecord
TRecord
StorageScopeType
type StorageScopeType = ContentScopeType | "lineage";
The scope kind a resource row is STORED under.
Wider than ContentScopeType, which is the scope a resource is
DECLARED at. The two differ for exactly one case: a session-scoped resource
marked sharedToLineage stores in the lineage space, addressed by the
lineage rather than by a session.
They are separate types rather than one widened type because they answer
different questions, and because a lineage bucket must not be expressible
where a declared scope is expected. Keeping the lineage space out of
session is the whole point: session scope ids are caller-chosen, so a
lineage bucket sharing that space is one a caller can occupy by picking a
session id.
Adapters treat this as an opaque string — it is a plain TEXT column with no
constraint — so widening it needs no schema change and no migration.
StorageSize
type StorageSize = object;
One reading of a store's size, as StoreRegistry.storageSize gives it.
kind names the backend ("sqlite", "filesystem", "postgres", or a
third-party adapter's own name). location says what was measured, for a
person to read: a file or folder path, or a database name. Never a
credential.
Properties
bytes
bytes: number;
Bytes the store's files or tables take.
kind
kind: string;
location?
location?: string;
StoreSubscriptionErrorCode
type StoreSubscriptionErrorCode = typeof STORE_SUBSCRIPTION_ERROR_CODES[number];
TraceEvent
type TraceEvent = object;
A single trace event captured by the runtime. Carries the originating
request, a monotonically-increasing per-request sequenceNumber for
cursor-based reads, the wall-clock timestamp, the event type, and the
inner debug item.
Properties
item
item: BlockTraceItem | RouterDecisionItem | StateSnapshotItem;
requestId
requestId: string;
sequenceNumber
sequenceNumber: number;
ts
ts: number;
type
type: "trace.item.added" | "trace.item.done";
UnstartedRequestEnding
type UnstartedRequestEnding =
| {
cause: unknown;
status: "failed";
}
| {
status: "aborted";
};
How an unstarted request ends: failed, with its cause, or aborted.
UserListOptions
type UserListOptions = object;
Properties
limit?
limit?: number;
offset?
offset?: number;
UserRecord
type UserRecord<TState> = ScopeRecordBase<TState> & object;
Type Parameters
TState
TState extends JsonObject = JsonObject
Type Declaration
resources?
resources?: Record<string, JsonObject>;
userId
userId: string;
VersionedResourceState
type VersionedResourceState = object;
A live resource state row together with the CAS version it was read at.
The version is what makes a read usable as the basis for a conditional
write: pass it back as set's expectedVersion and the write lands only
if nobody moved the key in between. undefined from a read means "no live
row" — an absent key and a tombstoned one are indistinguishable to readers
by design (see ResourceStateStore).
Why this type is branded
Structurally, { state, version } is a perfectly good JsonObject. That
made every missed unwrap a silent bug rather than a compile error — handing
{ state, version } where the state itself was expected typechecked
cleanly and produced the wrong value downstream. The phantom brand below
breaks that assignability: its declared type is a unique symbol, which is
not a JsonValue, so VersionedResourceState (and any Record of them) is
no longer assignable to JsonObject. Use toBareState / toBareStates
to project down; forgetting to is now a type error.
The property is optional and never written, so constructing a versioned read
stays a plain object literal — adapters pay nothing for the brand. It does
not defend against an explicit as cast, which remains the caller's
assertion to make.
Properties
__versionedResourceState?
readonly __versionedResourceState?: typeof versionedResourceStateBrand;
Phantom. Never present at runtime — see the note above. The key is a
string rather than the symbol itself on purpose: a JsonObject's index
signature only constrains string keys, so a symbol-keyed brand would be
ignored by the assignability check this exists to fail.
state
state: JsonObject;
The stored state. A tombstone is never returned, so this is always live.
version
version: number;
Monotonic per key, never reused — see ResourceStateStore.
WakeInput
type WakeInput = WakeKey & object;
What a writer owes a wake: the key, its owner and its due time, all server-written.
Type Declaration
dueAt
readonly dueAt: number;
When the debt is due (epoch ms).
flowKind
readonly flowKind: string;
The flow instance the session belongs to: its exact id.
landBy
readonly landBy: number;
When the write the wake guards must have landed by (epoch ms): the writer's request lease. A pass that finds nothing owed before this time moves the wake here rather than clearing it.
orgId
readonly orgId: string;
userId
readonly userId: string;
The session's owner, as the wake's dispatch runs as.
WakeKey
type WakeKey = object;
Where a wake is kept: one per session, internal entry and resolver identity.
tenantId is part of the key, so two tenants' sessions under one id never
share a wake; so is resolvedBy, so writers under two resolvers never
share one either, and a wake's resolver never changes while it is kept.
Properties
entry
readonly entry: string;
The internal entry the wake dispatches in that session.
resolvedBy?
readonly resolvedBy?: string;
The resolver identity that produced the writer's principal
(Principal.resolvedBy), which the woken run carries, so it reaches the
own-resolver sessions that resolver admits. Absent is a key value of its
own: the wake of writers that hold none (and every wake stored before the
field), whose run admits no own-resolver session.
sessionId
readonly sessionId: string;
The session the wake runs its entry in (the session id, not its storage key).
tenantId?
readonly tenantId?: string;
WakeRecord
type WakeRecord = WakeInput & object;
A wake: a debt's due time the engine keeps, fired by the durability sweeper until a pass in its session clears it. Written before the write that owes, so a crash between the two leaves a wake that pays nothing, never a debt with no wake.
Type Declaration
createdAt
readonly createdAt: number;
updatedAt
readonly updatedAt: number;
version
readonly version: number;
Bumped by every WakeStore.owe, so a pass clears only what it read.
WebhookVerifier
type WebhookVerifier = (rawBody, headers) => boolean;
A webhook verify function: authentic request → true.
Parameters
rawBody
Uint8Array
headers
Headers
Returns
boolean
Variables
LEGACY_SESSIONLESS_REQUEST
const LEGACY_SESSIONLESS_REQUEST: "legacy-sessionless-request";
The reason a legacy session-less record is refused, shared with the route layer's 409 body.
STORE_SUBSCRIPTION_ERROR_CODES
const STORE_SUBSCRIPTION_ERROR_CODES: readonly ["backpressure_overflow", "listen_unrecoverable"];
Functions
abortableSleep()
function abortableSleep(ms, signal?): Promise<void>;
Abort-aware sleep used by polling subscription loops.
Parameters
ms
number
signal?
AbortSignal
Returns
Promise<void>
abortRequest()
function abortRequest(requestId, expectedIncarnation?): boolean;
Signal abort for a request: every live attempt's controller under the id. Returns true if at least one was found and aborted, false if none was.
With expectedIncarnation, fires only the controllers that belong to that
incarnation; a controller of another request under the same id, or one not
yet tagged, is left alone.
Parameters
requestId
string
expectedIncarnation?
string
Returns
boolean
createFilesystemContentStore()
function createFilesystemContentStore(rootDir): ContentStore;
Create a filesystem-backed ContentStore rooted at rootDir/content.
Parameters
rootDir
string
Returns
createFilesystemOrgStore()
function createFilesystemOrgStore(options): OrgStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Parameters
options
FilesystemOrgStoreOptions
Returns
createFilesystemRequestStore()
function createFilesystemRequestStore(options): RequestStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Parameters
options
FilesystemRequestStoreOptions
Returns
createFilesystemResourceStateStore()
function createFilesystemResourceStateStore(rootDir, options?): ResourceStateStore;
Create a filesystem-backed ResourceStateStore rooted at
rootDir/state.
Parameters
rootDir
string
options?
FilesystemResourceStateStoreOptions
Returns
createFilesystemSessionStore()
function createFilesystemSessionStore(options): SessionStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Parameters
options
FilesystemSessionStoreOptions
Returns
createFilesystemStores()
function createFilesystemStores(options): StoreRegistry;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Parameters
options
FilesystemStoreRegistryOptions
Returns
createFilesystemTraceStore()
function createFilesystemTraceStore(options): TraceStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Parameters
options
FilesystemTraceStoreOptions
Returns
createFilesystemUserStore()
function createFilesystemUserStore(options): UserStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Parameters
options
FilesystemUserStoreOptions
Returns
createFilesystemWakeStore()
function createFilesystemWakeStore(rootDir): WakeStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Parameters
rootDir
string
Returns
createInboundTransportHost()
function createInboundTransportHost(options): InboundTransportHost;
Parameters
options
CreateInboundTransportHostOptions
Returns
createInMemoryBus()
function createInMemoryBus(): ChangeBus;
Create a bus that delivers each notice to this process's subscribers, in
one microtask after publish (one per publish, however many subscribe).
crossesProcesses is always true: the app it serves runs as one process.
Returns
createInMemoryContentStore()
function createInMemoryContentStore(): ContentStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Returns
createInMemoryLeaseStore()
function createInMemoryLeaseStore(): LeaseStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Returns
createInMemoryOrgStore()
function createInMemoryOrgStore(): OrgStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Returns
createInMemoryRequestStore()
function createInMemoryRequestStore(): RequestStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Returns
createInMemoryResourceStateStore()
function createInMemoryResourceStateStore(options?): ResourceStateStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Parameters
options?
InMemoryResourceStateStoreOptions
Returns
createInMemorySessionStore()
function createInMemorySessionStore(): SessionStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Returns
createInMemoryStores()
function createInMemoryStores(options?): StoreRegistry;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Parameters
options?
CreateStoreOptions
Returns
createInMemorySuspensionStore()
function createInMemorySuspensionStore(options?): SuspensionStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Parameters
options?
InMemorySuspensionStoreOptions
Returns
createInMemoryTraceStore()
function createInMemoryTraceStore(options?): TraceStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Parameters
options?
InMemoryTraceStoreOptions
Returns
createInMemoryUserStore()
function createInMemoryUserStore(): UserStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Returns
createInMemoryWakeStore()
function createInMemoryWakeStore(): WakeStore;
The registry factories and per-store constructors behind inMemoryStores and filesystemStores.
Returns
createLocalBlobStore()
function createLocalBlobStore(options): BlobStore;
Build a blob store over a folder on this server's disk.
Parameters
options
Returns
createNetworkAuthGuard()
function createNetworkAuthGuard(allowUnauthenticated?): (router) => Promise<Response | undefined>;
Request guard for a network-exposed host. Refuses an unauthenticated app on
every call, independent of NODE_ENV: an unset environment is how Lambda
serves, and a development flag must not put the default resolver on the
network. Loopback exemption belongs to the host that can see the bind
(serve skips this guard). allowUnauthenticated is the explicit override.
The pass/fail result is not cached. FlowState.register can add a flow
after the first request, and a cached pass would serve it. The diagnostic
is logged once per guard; the response body stays generic.
Parameters
allowUnauthenticated?
boolean
Returns
(router) => Promise<Response | undefined>
createResponseEmitter()
function createResponseEmitter(options): ResponseEmitter;
Creates a public response emitter with default seam behavior.
Parameters
options
Returns
decideClaim()
function decideClaim(record, claim): object;
Decide a claim against the stored record. Returns the result and, when it changes the record, the record to write.
Parameters
record
BlobRecord | undefined
claim
owner
string
send
string
uploader
Returns
object
next?
next?: BlobRecord;
result
result: BlobClaimResult;
declareEphemeralDisk()
function declareEphemeralDisk(router): boolean;
Declare that the host serving router does not keep its disk between
requests. Called by a host adapter, never by an app: uploads to a blob store
that keeps bytes on this host are then refused with attachments_unavailable.
Returns false, and changes nothing, for a router createFlowApiRouter
did not build: such a router serves no upload route, so there is nothing
to refuse. A host adapter can call it on whatever router it is handed.
Parameters
router
Returns
boolean
dispatchDedicatedRoute()
function dispatchDedicatedRoute(
router,
req,
hostBasePath?
): Promise<Response | null>;
Dispatch req against ONLY the router's dedicated custom-adapter routes —
the ones a transport adapter registers OUTSIDE the canonical mount (e.g. the
MCP adapter's /mcp/:kind under dedicatedBasePath: true). Returns the
route's Response on a match, or null when no dedicated route matches. It
never touches the canonical flow-API handler, so a host can serve dedicated
endpoints without exposing the flow API (list-flows, actions, sessions)
outside its mount prefix.
hostBasePath is where the host mounted the canonical flow API (default
/api/flows). A custom adapter route under it — or under the framework's
/api/flows namespace, where non-dedicated adapter routes live — is NOT
served here: the former is reachable via the canonical mount, and the latter
must not be exposed at its raw path when the host mounted canonical elsewhere.
Long-lived hosts (@flow-state-dev/node's createServerApp) call this from
their not-found fallback so dedicated routes work with no per-adapter wiring;
catch-all hosts that mount the router under basePath don't need it.
Parameters
router
req
Request
hostBasePath?
string
Returns
Promise<Response | null>
enablePushDelivery()
function enablePushDelivery(router, options?): PushDelivery;
Turn push delivery on for router: it then reports
{ transport: "websocket" } in GET /capabilities and answers the mint.
Call it from a host that serves the socket on /users/:userId/stream,
and hand each socket that opens there to the returned delivery.
Parameters
router
options?
Returns
Throws
When router was not built by createFlowApiRouter.
endsRequestStream()
function endsRequestStream(event, options?): boolean;
Whether an event ends a subscribeToEvents iterator, honoring
followThroughSuspend. When set, request.suspended is a
checkpoint rather than a terminal, so a same-request continuation can be
streamed through to its real terminal — the true terminals still end the
iterator. Every backend's subscription loop uses this instead of
isTerminalRequestStreamEvent directly so the behavior is uniform
(enforced by the request-store conformance suite).
Parameters
event
RequestStreamEvent
options?
followThroughSuspend?
boolean
Returns
boolean
ensureSessionRecord()
function ensureSessionRecord(
stores,
storageKey,
request,
build
): Promise<SessionRecord>;
Return the session record at storageKey, creating it through
birthSession if absent. The action, webhook and fsdev run paths'
caller: a lost create race adopts the winner.
The returned record is authoritative: on a lost create race it is the
winner's, not the one this caller built. Callers that go on to read
lineageId (or anything else) must use what comes back rather than what they
passed in, or they are back to two answers for one question.
Parameters
stores
SessionBirthStores
storageKey
string
request
build
() => SessionRecordSeed
Returns
Promise<SessionRecord>
Throws
SessionCreateRefusedError when the create is refused.
Throws
when the key is tombstoned — the store contract requires a caller to treat that as deleted and stop, never as "reuse my copy".
holdLeasePlace()
function holdLeasePlace(
backend,
place,
onLost
): LeasePlaceHold;
Keep a place alive for as long as this process holds it, and say when it cannot be kept.
Renews every 2 seconds, or every quarter of the backend's leaseMs when
that is shorter. onLost is called once, with a ConcurrencyLeaseLostError,
when a renewal answers that the place is gone, or, on a backend that
declares leaseMs, when no renewal has landed for half the lease: the
other half is the holder's time to stop before another process can take
the key. A renewal that throws is otherwise ignored. Renewal stops after
onLost. The holder gives the place back itself.
Parameters
backend
place
onLost
(error) => void
Returns
installBuiltIns()
function installBuiltIns(registry): void;
Hold the framework's own flows (the default write flow) in registry. Every
runtime entry that resolves flows from a registry calls it: the inbound host
and a queue worker, so a write never depends on which process runs it. The
flows capture nothing of a host: they read the stores and host resolver of
the runtime running them off their context (built-in-host.ts), so one
instance serves every host that shares the registry. Idempotent.
Parameters
registry
Returns
void
isBatchStillAuthorized()
function isBatchStillAuthorized(options): Promise<boolean>;
Whether a batch of events just read may be yielded: the subscription's
isStillAuthorized fence, where a throw counts as false (a stream that
cannot prove it still belongs to its caller ends).
Parameters
options
Pick<SubscribeToEventsOptions, "isStillAuthorized">
Returns
Promise<boolean>
isDefaultBodyUserIdPrincipalResolver()
function isDefaultBodyUserIdPrincipalResolver(resolver): boolean;
Whether resolver is the framework default body-userId resolver — i.e. it
trusts a caller-supplied body.userId with no real authentication. Checks the
package-instance-stable brand (not function identity), so it holds even when
the resolver came from a different @flow-state-dev/engine instance. Callers
that treat "no resolver configured" as unauthenticated must handle undefined
separately — this predicate is about an actual default-resolver value.
A hand-written resolver that merely delegates to the default is NOT detected (it is a distinct, unbranded function); that is out of scope for this check.
Parameters
resolver
unknown
Returns
boolean
isFlowState()
function isFlowState(value): value is FlowState<FlowStateSettings>;
Structural check for a FlowState handle. Deliberately structural
rather than instanceof InternalFlowState: a config file or consumer repo
may resolve @flow-state-dev/engine to a duplicated package instance
(workspace symlinks, double installs), so an identity check would reject a
valid handle built by a different copy of the class. Checks the four methods
that define the off-transport contract (getRuntime/getRouter) plus the
lifecycle pair (ready/dispose), which together separate a FlowState from
a raw FlowApiRouter.
Parameters
value
unknown
Returns
value is FlowState<FlowStateSettings>
isOrgAttributed()
function isOrgAttributed(record): boolean;
Whether this record carries a usable organization.
The predicate every list, sweep and index scan filters on, so an unattributed row is omitted rather than refused where refusing would stop a whole listing for one bad row.
Parameters
record
OrgAttributedRecord | undefined
Returns
boolean
isSweepable()
function isSweepable(record, now): boolean;
True when a sweep at now takes record: held by no owner for at least the unclaimed lifetime.
Parameters
record
now
number
Returns
boolean
isTerminalRequestStatus()
function isTerminalRequestStatus(status): boolean;
Whether a request status is past the in-flight phase.
Parameters
status
RequestStatus | undefined
Returns
boolean
networkAuthenticationError()
function networkAuthenticationError(router, target): Promise<string | undefined>;
The shared network safety rail. A flow is unauthenticated when the resolver
the routes would pick for it (pickPrincipalResolver: the flow's own, else
the router's host-level resolver) is the framework default that trusts
body.userId. It does not judge whether a custom resolver verifies
credentials. Hand-written routers have no framework flows to inspect.
Callers pass the router the routes will use. Reading the live registry means a flow registered after the router was built is visible on the next call.
Parameters
router
target
string
Returns
Promise<string | undefined>
ownsRecord()
function ownsRecord(flow, record): boolean;
Whether flow is the instance a stored record belongs to. The comparison
side of resolveRecordOwner: a request that already holds its
resolved instance asks this before touching a record it loaded.
A legacy row (no flowId) belongs to the singleton of its kind and to
nothing else — never to a collection member, and never to a different kind
whose instance id happens to equal the stored kind.
Parameters
flow
OwnerIdentity
record
Returns
boolean
parseFlowRoute()
function parseFlowRoute(method, path): ParsedFlowRoute;
Parses a catch-all method/path tuple into a typed flow route shape.
Empty segments are dropped so request paths that come
in as ["", "sessions", "abc"] from a Next.js catch-all match the same
way as ["sessions", "abc"].
path holds decoded segments, the shape a framework catch-all (Next's
params.path) hands over: each URL segment percent-decoded exactly once.
The segments are re-encoded before matching and the matcher decodes once,
so each segment reaches the route as given: a literal %5F or / inside
one stays in it. A host that only has the raw URL decodes it with
decodePathSegments first.
Parameters
method
string
path
string[] | undefined
Returns
pinRejectsCaller()
function pinRejectsCaller(pin, caller): boolean;
Whether caller is outside pin.
Parameters
pin
InstanceOwnerPin | undefined
caller
Returns
boolean
false when there is no pin. Organization is compared first.
planDeferWait()
function planDeferWait(input): DeferWaitStep;
Decide what a defer run that has not claimed its key does next. The one
definition of the defer wait: the engine's arbiter waits by it in
process, and a queue worker that waits by requeueing its job reaches the
same decisions from the wait it carries on the job.
waitedMs counts from the run's first claim attempt, and attempt counts
attempts made so far, from 0, as in planQueueWait. patienceMs defaults
to DEFER_PATIENCE_MS.
Parameters
input
attempt
number
patienceMs?
number
random?
() => number
waitedMs
number
Returns
planQueueWait()
function planQueueWait(input): QueueWaitStep;
Decide what a queue run whose turn has not come does next.
Backs off exponentially from a short base to a cap of a few seconds, with full jitter so waiters on one key spread out, and clamps the wait to what is left of the budget so the last check lands at the budget's end and fails there with the error an in-process wait fails with.
waitedMs counts only time spent waiting on the key, from the run's first
turn check: time queued behind unrelated work never consumes the budget.
attempt counts turn checks made so far, from 0, and must grow by one per
check — a caller that restarts it keeps the backoff at its base. A worker
that waits by requeueing its job carries both on the job. random defaults
to Math.random.
budgetMs defaults to the queue budget. Infinity is the wait of a
defer run that ran out of patience and lined up behind the runs on its
key: it backs off the same way and never times out.
Parameters
input
attempt
number
budgetMs?
number
key
string
random?
() => number
waitedMs
number
Returns
pollEvents()
function pollEvents(
readEvents,
requestId,
options,
pollIntervalMs
): AsyncIterableIterator<RequestStreamEvent>;
Shared polling subscription loop for the SQLite, filesystem, and
Postgres-without-liveTailPool backends. Yields the catch-up phase via
readEvents, then polls on pollIntervalMs until aborted, terminal,
or stalled past livenessTimeoutMs (synthesizes a request.interrupted).
Parameters
readEvents
requestId
string
options
pollIntervalMs
number
Returns
AsyncIterableIterator<RequestStreamEvent>
publishScopeChange()
function publishScopeChange(bus, change): void;
Publish change on its scope's topic. A missing bus publishes nothing;
a failed publish never fails the write (epic ER-6).
Parameters
bus
ChangeBus | undefined
change
Returns
void
refuseReadonlyStateChange()
function refuseReadonlyStateChange(
flowKind,
sessionId,
readonlyFields,
createdWith,
next
): void;
Refuse a proposed session state that changes a readonly field from what the session was created with.
Parameters
flowKind
string
sessionId
string
readonlyFields
readonly string[]
createdWith
Readonly<Record<string, unknown>>
next
Readonly<Record<string, unknown>>
Returns
void
Throws
ReadonlySessionStateError naming the first field that changed.
refuseServerOwnedState()
function refuseServerOwnedState(
flow,
sessionId,
callerState
): void;
Refuse a caller-seeded state field the flow declares server-owned.
Parameters
flow
Pick<BirthFlow, "kind" | "session">
sessionId
string
callerState
Record<string, unknown> | undefined
Returns
void
Throws
SessionCreateRefusedError naming the first such field.
resolveInProcessPrincipal()
function resolveInProcessPrincipal(options, question): Promise<InProcessPrincipal>;
Who an in-process caller is, answered by the same resolution every inbound
transport's host uses: a flow's own resolver before resolvePrincipal, the
user fallback, and the organization rules. fsdev run and fsdev chat ask
this before they write anything.
The resolver sees source: "cli", no request, and metadata.body as an
HTTP action body: { userId, input } from the question. The context is
frozen. That source is reserved: only this function can produce a
context the host accepts it on. Refusals are the host's own
PrincipalResolutionErrors (or whatever the resolver threw), unchanged — a
resolver that needs a credential refuses here exactly as it refuses an HTTP
caller without one.
In-process only. No route, header, query or environment variable reaches it.
FlowState.resolveInProcessPrincipal calls it with the app's own registry
and host resolver; pass a bare registry for flows with no host resolver.
Parameters
options
registry
resolvePrincipal?
ResolvePrincipalFn
question
Returns
Promise<InProcessPrincipal>
resolveSharedUserCellKey()
function resolveSharedUserCellKey(
userId,
orgId,
flowKind
): string;
The cell a user-scoped collection that is shared across flows (one with
flowIsolation: false) keeps a user's rows in, for a request that starts
from outside any run: <userId>:~org:<orgId>. The one derivation the
scheduled-dispatch endpoint hands its resolver and the host's owner-run
check reads, so the two can't drift apart.
Parameters
userId
string
orgId
string
flowKind
string
Named in the OrgRequiredError a malformed org throws.
Returns
string
settleUnstartedRequest()
function settleUnstartedRequest(
stores,
requestId,
ending,
expectedIncarnation?
): Promise<void>;
End a request whose run never started. With expectedIncarnation, only
that request is ended: a record another request put under the id since is
left alone. Without it, whatever holds the id is ended. A missing or
already-terminal record is left as it is.
The read and the write are separate calls, so a record replaced between
them is still overwritten. The conditional store write cannot close that:
it does not write status.
Best effort: a store failure is swallowed, because the caller's own error is what it reports.
Parameters
stores
requestId
string
ending
expectedIncarnation?
string
Returns
Promise<void>
synthesizeRequestInterrupted()
function synthesizeRequestInterrupted(requestId, sequenceNumber): RequestStreamEvent;
Build an in-iterator request.interrupted event for liveness-timeout
surfacing. Not persisted — this represents the subscriber's view of an
apparent originating-process death, not durable state.
Caller must pass the last real sequence_number yielded (or 0 if
nothing has been yielded yet). Reusing the last-seen sequence is
deliberate: SSE clients echo this id back as Last-Event-ID on
auto-reconnect, and the resume cursor returns events strictly greater
than that. If the writer was actually still alive and persisted a real
event at lastSeen + 1, advancing the synthetic past it would cause
the reconnecting subscriber to skip that real event (the synthetic is
never persisted, so it can't collide in catch-up).
This is the one exception to the rule for a synthetic terminal event
(docs/architecture/streaming.md): one that nothing can follow takes the
log's last sequence number plus one (the stream route's replay of a log left
without a terminal event). A liveness timeout can still be followed by a
live writer's events, so it keeps the last seen one. A client that already
saw that event drops this synthetic as a repeat.
Parameters
requestId
string
sequenceNumber
number
Returns
RequestStreamEvent
withChangeBus()
function withChangeBus<T>(stores): T & object;
Give stores its bus and make its request and session writes publish to
it. The bus is the registry's own bus; else the one its stores already
publish to; else a new in-memory bus. Idempotent: a registry this returned
comes back unchanged.
Type Parameters
T
T extends StoreRegistry
Parameters
stores
T
Returns
T & object
The registry with bus set and its request, session and
suspensions stores wrapped: stores itself when nothing changed,
otherwise a copy.
Throws
FlowStateConfigError when the registry's bus differs from the one
its stores already publish to.
withStoredAbortRequested()
function withStoredAbortRequested<T>(value, stored): T;
Force a request record's abortRequested to the value already stored,
whatever the incoming record says.
The single helper behind RequestStore.set's rule that the flag is off its
write surface in both directions. Adapters call it on the value they are
about to persist, passing the stored flag they just read; undefined drops
the key so a record that never carried it does not gain one.
Kept here rather than inlined per adapter so the four implementations cannot drift into three subtly different readings of "ignores".
Type Parameters
T
T extends RequestRecord
Parameters
value
T
stored
boolean | undefined
Returns
T