@flow-state-dev/engine
Classes
AcrossSessionsCursorError
A cursor that this read did not hand back, or that this process can't open.
Extends
Error
Constructors
Constructor
new AcrossSessionsCursorError(options?): AcrossSessionsCursorError;
Parameters
options?
cause?
unknown
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
stack?
stack?: string;
Inherited from
Error.stack
ConcurrentModificationError
Thrown when a version-checked write loses a race — either because a CAS
driver spent its whole retry budget without landing, or because a
version-checked resource delete conflicted. The class is retryable: true,
which on the CAS paths means a fresh attempt can win once contention
subsides. What sets the delete apart is that it has no internal retry loop
behind it at all: it passes the literal attempts: 1 where both drivers pass
maxRetries + 1. That is a statement about the loop, not a claim about what
a caller's own retry policy can do.
Three raise sites, not one. Both CAS drivers raise it when their retry
budget exhausts — runWithCAS (../stores/cas.ts) for scope state,
runResourceCAS (../stores/resource-cas.ts) for resource state — and the
version-checked resource delete in createExecutionContext raises it
terminally on the first conflict, with no retry loop behind it (attempts
is 1 there). Prose that names only the scope-state driver, or only budget
exhaustion, is describing one of the three. Three paths, four throws:
the delete path holds two, one for the conflict it exists to catch (a live
row at an unexpected version, which refreshes the cached value and version
from the winner's row before it throws) and one for a store adapter that has
broken idempotent delete, which no retry can fix.
The ops below are examples, not a closed list. On the scope-state
driver a call reaches the retry loop when the scope has a durable persist
and its CASMutationHint is non-commutative (isCommutativeHint,
../stores/cas.ts) — setState, atomicState, multi-field patchState,
updater-form patchState and multi-field incState qualify today, the last
because its mutator recomputes from the current field value on every retry.
An in-memory scope has no persist, no version, and never throws this. Note
what that does not say: a commutative op is still version-checked when the
adapter doesn't advertise the matching delta verb, because
createScopePersist then falls back to a full set at the held numeric
version — that refusal returns false instead of raising, which is a
different report, not an exemption. The resource driver has no such
store-dependent split — it does no delta-verb feature detection, so what
the adapter advertises never changes its expectedVersion. The caller's
intent decides that instead — runResourceCAS derives expectedVersion from
its intent argument, and the split is four-way rather than three. mutate
sends the held version, or "absent" ("no row at all") when it holds none;
a tombstone is a row, so it refuses "absent" and that write ends
terminally rather than landing on top of a delete. create sends 0, a
version check, but against "no live row" rather than the version this
context holds — which a tombstone satisfies, because recreating a deleted
resource is what the verb is for. And replace, reached by
create(key, state, { replace: true }) on a writable collection, sends
"any" and so is not version-checked at all. A writable: false
collection does not select replace: that call uses create intent, and
a live-row conflict is reported as read-only rather than as an overwrite.
Read the hint routing before restating any of this narrower than it is.
Extends
FlowError
Constructors
Constructor
new ConcurrentModificationError(
message,
attempts,
options?
): ConcurrentModificationError;
Parameters
message
string
attempts
number
options?
SubclassOptions
Returns
Overrides
FlowError.constructor
Properties
attempts
readonly attempts: number;
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
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
PrincipalResolutionError
Thrown by a principal resolver when the caller cannot be authenticated.
Carries an HTTP-shaped status so HTTP adapters can map to a response
directly; non-HTTP transports translate the status to their native form.
Extends
Error
Constructors
Constructor
new PrincipalResolutionError(message, options?): PrincipalResolutionError;
Parameters
message
string
options?
status?
number
Returns
Overrides
Error.constructor
Properties
cause?
cause?: unknown;
Inherited from
Error.cause
message
message: string;
Inherited from
Error.message
name
name: string;
Inherited from
Error.name
stack?
stack?: string;
Inherited from
Error.stack
status
readonly status: number;
SessionNotFoundError
What every verb on a named session answers when admitNamedSession refuses it, and when no one holds the id: one message, naming neither the id nor why, so the two answers are the same bytes.
Extends
Error
Constructors
Constructor
new SessionNotFoundError(): SessionNotFoundError;
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
stack?
stack?: string;
Inherited from
Error.stack
UntrustedReachError
The refusal a turn an outside delivery started meets when it names another session. It names the rule, never the target.
Extends
Error
Constructors
Constructor
new UntrustedReachError(): UntrustedReachError;
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
stack?
stack?: string;
Inherited from
Error.stack
Interfaces
CapabilitySlotMap
Capability slots a profile can declare.
primary— required. The catch-all state slot: backs sessions, requests, users, orgs, active requests, checkpoints, content, and traces.blobs— binary object storage. Reserved: declaring it is a no-op until the attachment store that backs it ships.bus— the change bus: the adapter resolves{ bus }. When the profile names none, the primary backs it if it declaresbus; otherwise the bus is in memory and reaches this process only.
Properties
blobs?
blobs?: StoreAdapter;
bus?
bus?: StoreAdapter;
primary
primary: StoreAdapter;
ErrorCaptureEvent
Provider-neutral context handed to an operator's error-capture callback when
a block fails. Carries no provider vocabulary (tags / severity / fingerprint)
— the adapter derives those from error.code / error.retryable.
Properties
actionName
actionName: string;
attempt?
attempt?: number;
0-indexed retry attempt of the failing block.
blockInstanceId?
blockInstanceId?: string;
Deterministic instance id ${requestId}:${blockPath} (excludes attempt).
blockKind?
blockKind?: BlockKind;
blockName?
blockName?: string;
Failing block (leaf). Absent for errors with no originating block.
blockPath?
blockPath?: string;
Structural path within the request's execution tree, e.g. root/step[0].
error
error: FlowError;
Normalized framework error. The raw thrown value is on error.cause.
final?
final?: true;
Set on the one event a request sends when it settles failed,
after its failed record is written. Its scope is "request", and it
names the leaf that threw when one did. A failure a retry or a rescue
healed never gets one, so a sink that files bugs keys on it; a sink that
forwards every failing block ignores it.
flowKind
flowKind: string;
orgId?
orgId?: string;
requestId
requestId: string;
Correlation IDs shared across all events from one request.
scope?
scope?: FlowErrorScope;
Error scope: "block" | "request" | "sideChain" | "resource".
sessionId?
sessionId?: string;
transient?
transient?: boolean;
True for high-frequency transient blocks (poll loops); lets adapters down-sample.
userId
userId: string;
FlowState
The handle returned by createFlowState. The runtime router is built
lazily on first getRouter() / ready(); adapters open pools then.
Type Parameters
TSettings
TSettings extends object = FlowStateSettings
Properties
activeProfile
readonly activeProfile: string;
The active profile name. Resolved on first ready() / getRouter().
Reading it earlier resolves the profile eagerly and throws
FlowStateConfigError if FSD_ENV names a profile that wasn't declared.
meta
readonly meta: object;
Diagnostic metadata.
declaredSlots
declaredSlots: Record<string, CapabilitySlot[]>;
devtool?
devtool?: DevToolConnectionConfig;
DevTool connection config, forwarded verbatim from the options.
flowKeys
flowKeys: string[];
profileKeys
profileKeys: string[];
settings
readonly settings: TSettings;
The settings bag, typed via TSettings. Read-only at runtime.
Methods
dispose()
dispose(): Promise<void>;
Dispose pooled resources across every declared adapter.
Returns
Promise<void>
getRouter()
getRouter(): Promise<FlowApiRouter>;
Resolve the lazy router. First call triggers async store init.
Returns
Promise<FlowApiRouter>
getRuntime()
getRuntime(): Promise<FlowStateRuntime>;
Resolve the runtime internals for off-transport consumers (background
workers, queue processors, scripts). Triggers async store init like
getRouter() and is idempotent and memoized — it returns the same
{ registry, stores, runtimeConfig } instances the router uses.
Returns
Promise<FlowStateRuntime>
ready()
ready(): Promise<void>;
Eager warmup. Idempotent. Useful in instrumentation.ts / tests.
Returns
Promise<void>
register()
register(flow, options?): void;
Admit one flow instance after construction — the door an app adds a flow through while it is running, with or without an owner pin, and the same door an app's boot-time reload of instances it stored comes through.
Runs exactly the checks construction runs: a duplicate id is refused, so is a singleton under a custom id, and so is a flow whose user- or org-scoped schemas conflict with an already-registered kind's. A refused registration changes nothing — it throws before any registry state is touched.
One instance, never a batch. Admitting a list would have to either roll the whole list back on a refusal or leave the earlier entries admitted, and a caller registering several almost always wants to know which one was refused and keep the rest. Loop, and handle each refusal where it happens.
What is served, and when. The registry is read once per request, so the flow answers from the next request onward — in this process only. A sibling process picks it up when it next starts. If your app runs on more than one instance, plan for a short window rather than an instant one.
Parameters
flow
FlowInstance
options?
pin?
InstanceOwnerPin
Returns
void
Throws
FlowIdentityConflictError or CrossFlowSchemaConflictError.
Also throws when options.pin disagrees with a pin already on the instance,
or, once this app holds an owner-private collection, when the instance
declares another collection in its scope that can reach that collection's rows.
resolveInProcessPrincipal()
resolveInProcessPrincipal(question): Promise<InProcessPrincipal>;
Who an in-process caller is, answered the way this app's HTTP routes
answer a request: the flow's own resolvePrincipal, else the one passed
to createFlowState, held to the same organization rules. The resolver
sees source: "cli" and no request. fsdev run and fsdev chat ask this
before they write anything.
In-process only — no route reaches it. Rejects with the resolver's own refusal, exactly as the route would refuse a caller with no credential.
Parameters
question
Returns
Promise<InProcessPrincipal>
unregister()
unregister(id): boolean;
Release one address, so a request to it is answered the way a process that never had the flow would answer it.
Parameters
id
string
Returns
boolean
true when an instance was holding the address, false when
nothing was. An unknown id is an ordinary answer, not an error.
It cancels nothing. A request already running holds the flow instance it resolved, so unregistering does not abort it, truncate its stream, or discard what it wrote — that run finishes and its items are persisted. Only the next request is affected.
Nothing else is touched. Sessions, scope state and resources the flow wrote stay exactly as they are; removing those is a separate and irreversible operation.
The per-process window is the same one register has, and it is sharper
here: a sibling process serving this address keeps serving it until it
next starts.
StoreAdapter
A tagged value an adapter factory returns. Declares which capability slots
it can back and realizes them on demand (opening pools, running schema
init) when createFlowState resolves the active profile.
Properties
capabilities
readonly capabilities: readonly (keyof CapabilitySlotMap)[];
Slots this adapter is willing to back.
Methods
dispose()?
dispose?(): void | Promise<void>;
Release pooled resources. Called by FlowState.dispose().
Returns
void | Promise<void>
resolve()
resolve(slots): Promise<Partial<StoreRegistry>>;
Realize the adapter for the given slots. Returns the StoreRegistry
sub-stores it provides. Memoize internally so repeated resolution (e.g.
an adapter shared across slots) opens pools once.
Parameters
slots
readonly (keyof CapabilitySlotMap)[]
Returns
Promise<Partial<StoreRegistry>>
Type Aliases
CapabilitySlot
type CapabilitySlot = keyof CapabilitySlotMap;
A single capability slot name.
LocalBlobStoreOptions
type LocalBlobStoreOptions = object;
Options for localBlobStores and createLocalBlobStore.
Properties
now?
now?: () => number;
The clock, for tests that move it.
Returns
number
rootDir
rootDir: string;
The folder the files go in. Made on the first upload.
StoreRegistry
type StoreRegistry = object;
Properties
activeRequests
activeRequests: ActiveRequestRegistry;
blobs?
blobs?: BlobStore;
Where attachment bytes live: the profile's blobs slot. createFlowState
always fills it (on disk when the sessions persist, in memory when they
don't). Optional on a registry you build yourself; without it the upload
and read routes answer attachments_not_configured.
bus?
bus?: ChangeBus;
The change bus: request and session writes publish a notice
on their session's topic, and the session stream wakes on it. Optional
on a registry you build yourself; every entry that takes one
(resolveStores, runAction, BullMQ's job processor, fsdev) fills an
in-memory bus when it has none (withChangeBus).
checkpoints
checkpoints: CheckpointStore;
content
content: ContentStore;
leases
leases: LeaseStore;
org
org: OrgStore;
request
request: RequestStore;
resourceState
resourceState: ResourceStateStore;
session
session: SessionStore;
storageSize?
storageSize?: () => Promise<StorageSize>;
How much space this registry's storage takes, measured now. Optional: a
store that keeps nothing on disk (the in-memory one) or cannot measure
leaves it out (so does an SQLite :memory: database), and so does any
registry built before it existed. Read by the DevTool through the debug
route GET /api/flows/debug/storage.
Returns
Promise<StorageSize>
suspensions
suspensions: SuspensionStore;
traces
traces: TraceStore;
user
user: UserStore;
wakes?
wakes?: WakeStore;
Debts' due times. Optional: a host checks for it once at start, and without it keeps the fast paths only.
StoresConfig
type StoresConfig = Record<string, CapabilitySlotMap>;
Named stores profiles. Each profile maps capability slots to the adapter
that backs them. At least one profile must be declared; single-profile
users typically use { default: ... }.
Variables
defaultBodyUserIdPrincipalResolver
const defaultBodyUserIdPrincipalResolver: PrincipalResolver;
Resolve a principal from a body-shaped object. The HTTP adapter already parses the body for action input, so the resolver looks at:
context.envelope.metadata.body(set by the HTTP adapter)- fall back to
context.envelope.inputwhen metadata is absent
Returns null when no userId is present so the host can apply the
configured fallback (defaultUserId) and requireUser enforcement.
SCHEDULED_TRANSPORT_SOURCE
const SCHEDULED_TRANSPORT_SOURCE: "scheduled" = "scheduled";
Stamped by the scheduled endpoint, the router's built-in. Resolves a schedule entry.
Functions
continueRequest()
function continueRequest(options): Promise<ContinueRequestResult>;
Re-enter a suspended request under its own id and run it to its next terminal
(or re-suspension) state in replay mode. Throws synchronously for a missing
record or an unregistered flow — the caller (resume route) maps these to
404. A failure AFTER the in-progress transition is durable (failed); a
failure before it leaves the record suspended (see runAction's
point-of-no-return ordering).
Parameters
options
Returns
Promise<ContinueRequestResult>
createBearerSecretPrincipalResolver()
function createBearerSecretPrincipalResolver(options): ResolvePrincipalFn;
Build a principal resolver that authenticates via a shared bearer
secret. On match, returns the configured principal. On mismatch,
throws PrincipalResolutionError with status 401. When the header is
absent or the scheme isn't Bearer, returns null so the host can
apply defaultUserId fallback semantics.
Parameters
options
CreateBearerSecretPrincipalResolverOptions
Returns
ResolvePrincipalFn
createCheckpointDurabilityProvider()
function createCheckpointDurabilityProvider(stores): DurabilityProvider;
Parameters
stores
Pick<StoreRegistry, "checkpoints" | "suspensions" | "leases">
Returns
createExecutionContext()
function createExecutionContext<TRequestState, TSessionState, TUserState, TOrgState>(options): Promise<ExecutionContext<TRequestState, TSessionState, TUserState, TOrgState>>;
@flow-state-dev/engine: what an app author imports to run flows on a
server — createFlowState, the store adapters, createFlowApiRouter, the in-process
fetch, runAction, and the auth and webhook helpers an app wires in.
Two more entries split the rest by reader. @flow-state-dev/engine/host is
for host, transport and store adapter authors: the contracts they implement
and the types the root's functions take and return. @flow-state-dev/engine/internal
is for FSD's own packages, with no semver promise. A name is on the entry
its readers import it from; core and contracts names are imported from core.
Type Parameters
TRequestState
TRequestState extends JsonObject = JsonObject
TSessionState
TSessionState extends JsonObject = JsonObject
TUserState
TUserState extends JsonObject = JsonObject
TOrgState
TOrgState extends JsonObject = JsonObject
Parameters
options
CreateExecutionContextOptions<TRequestState, TSessionState, TUserState, TOrgState>
Returns
Promise<ExecutionContext<TRequestState, TSessionState, TUserState, TOrgState>>
createFlowApiRouter()
function createFlowApiRouter(options): FlowApiRouter;
Creates a catch-all route adapter with default no-op internal seam behavior.
Parameters
options
Returns
createFlowRegistry()
function createFlowRegistry(): FlowRegistry;
Creates an empty in-memory flow registry.
Returns
createFlowState()
function createFlowState<TSettings>(options): FlowState<TSettings>;
Assemble a flow-state runtime from declarative config. Returns a
FlowState handle whose router initializes lazily on first request.
Throws FlowStateConfigError synchronously for an empty stores
map or an unknown defaultProfile.
Type Parameters
TSettings
TSettings extends object = FlowStateSettings
Parameters
options
CreateFlowStateOptions<TSettings>
Returns
FlowState<TSettings>
createHmacVerifier()
function createHmacVerifier(options): HmacVerifier;
Build a webhook HMAC signature verifier. Returns a function that hosts
call inside resolvePrincipal with the request's raw body and signature
header value.
Parameters
options
Returns
createHs256JwtVerifier()
function createHs256JwtVerifier(options): Hs256JwtVerifier;
Build a JWT verifier for HS256-signed tokens. Hosts call the returned
function with the token extracted from Authorization. Asymmetric
algorithms are not supported here — they require key resolution
machinery (JWKS) that's a separate concern.
Parameters
options
Returns
createInProcessFetch()
function createInProcessFetch(app, options?): InProcessFetch;
Build a fetch-shaped function that dispatches to app (a FlowState or a
raw FlowApiRouter) in this process.
Per call: wait for the router (a FlowState initializes its stores on
first use; a failed init answers 500 { error: "Server failed to initialize" }), pick the router's handler by HTTP method (405 for any
other, HEAD included: a GET handler would run its side effects to discard
the body), take the path from the URL under basePath (404 outside it), and
call the handler with the Request unchanged, so SSE response bodies stream
and an abort signal on init reaches the route.
Router resolution starts when this is called, as a host's does, so the first request does not pay for store init alone.
Parameters
app
| FlowApiRouter
| FlowState<FlowStateSettings>
options?
Returns
createWebhookTransportAdapter()
function createWebhookTransportAdapter(options): InboundTransportAdapter;
Build an InboundTransportAdapter for inbound webhooks. Pass to
createFlowApiRouter({ adapters: [...] }) / createFlowState.
Parameters
options
CreateWebhookTransportAdapterOptions
Returns
createWebhookVerifier()
function createWebhookVerifier(options): WebhookVerifier;
Build a webhook verifier from an HMAC scheme. Wraps createHmacVerifier,
reading the configured header off the request's Headers. The underlying
verifier is constructed lazily on first call so a getter secret can read
an env var populated after import.
Parameters
options
Returns
decodePathSegments()
function decodePathSegments(rawPath): string[];
Splits a raw, still-encoded URL path (the part beneath the mount prefix)
into the decoded segments parseFlowRoute takes: split on / first,
then decode each segment once, so an encoded %2F stays inside its
segment. A segment that is not valid percent-encoding is kept as written.
Parameters
rawPath
string
Returns
string[]
disposeFlowApiRouter()
function disposeFlowApiRouter(router, options?): Promise<void>;
Tear down a router by invoking each adapter's bindings.stop() in
reverse order. Best-effort — failures are logged but don't abort the
sweep. Idempotent: a second call after dispose is a no-op.
Most callers don't need this: Next.js / Vercel / serverless hosts tear down by killing the process. It's intended for long-running servers (custom Node HTTP, Deno, Bun) and tests.
Parameters
router
options?
drainMs?
number
Returns
Promise<void>
executeBlock()
function executeBlock(options): Promise<ExecuteBlockResult>;
Executes a block and always returns a structured execution result.
Parameters
options
ExecuteBlockInternalOptions
Returns
Promise<ExecuteBlockResult>
extractBearerToken()
function extractBearerToken(headerValue): string | null;
Extract the bearer token from an Authorization header value. The match
is case-insensitive ("Bearer", "bearer", "BEARER" all accepted) and any
surrounding whitespace is trimmed. Returns null for malformed input.
Parameters
headerValue
string | null | undefined
Returns
string | null
filesystemStores()
function filesystemStores(options): StoreAdapter;
Filesystem store adapter for createFlowState. Backs the primary
capability slot with .fsdev/data-style on-disk persistence, and the
blobs slot with attachment files under <rootDir>/blobs, so
everything this store keeps sits under one folder.
Parameters
options
FilesystemStoreRegistryOptions
Returns
githubWebhookVerifier()
function githubWebhookVerifier(secret): WebhookVerifier;
GitHub webhook verifier. Reads X-Hub-Signature-256 (sha256=<hex>) and
signs the raw body. GitHub carries the event type in the X-GitHub-Event
header (read by the provider's eventType extractor, not here).
Parameters
secret
string | (() => string)
Returns
inMemoryStores()
function inMemoryStores(options?): StoreAdapter;
In-memory store adapter for createFlowState. Backs the primary
capability slot with ephemeral stores — the default for local dev and
tests. Memoizes the registry so repeated resolution returns one instance.
Parameters
options?
CreateStoreOptions
Returns
localBlobStores()
function localBlobStores(options): StoreAdapter;
The local-disk blob store as a profile's blobs adapter. The default when a
profile with persistent sessions names none is this, under
.fsdev/blobs/<profile> in the server's working directory; name it to choose
another folder:
stores: { default: { primary: sqliteStores({ filename }), blobs: localBlobStores({ rootDir: "/var/lib/myapp/blobs" }) } }
A database backup does not include these files; back the folder up too.
Parameters
options
Returns
resolveDurabilityProvider()
function resolveDurabilityProvider(options): DurabilityProvider | undefined;
The checkpoint provider over these stores, or none when this host is not durable.
Parameters
options
durable?
boolean
The host's durable setting. Absent: on wherever the stores persist.
stores
Pick<StoreRegistry, "checkpoints" | "suspensions" | "leases">
Returns
DurabilityProvider | undefined
resolveUserStorageKey()
function resolveUserStorageKey(
userId,
orgId,
flow
): string;
The key a user's scope record (ctx.user.state) lives at in one org:
<userId>:~org:<orgId>, or <userId>:~org:<orgId>:<flow.id> when the flow
isolates user state, each part escaped. Resources route per-resource via
resolveResourceScopeId; for a shared resource the two agree by
construction.
Parameters
userId
string
orgId
string
The admitted run's or the stored session's organization. Never
defaulted: a missing, blank or malformed one throws OrgRequiredError, so
no call builds a key that every org would read.
flow
Pick<IsolationFlow, "id" | "isolateUserState">
Returns
string
runAction()
function runAction<TFlow, TActionName>(options): Promise<ExecutionResult>;
Public action execution API using default internal seams.
A caller's metadata never carries a delivery origin: the key is dropped
here. The one origin this entry keeps is the one the host itself recorded
for requestId when it accepted the request and handed it to an external
runner (callerRunMetadata), which is how a queue worker or any other
runner's worker replays a webhook-fired run without the caller being able to
claim one (delivery-origin.ts).
Type Parameters
TFlow
TFlow extends FlowInstance = FlowInstance
TActionName
TActionName extends string = keyof TFlow["actions"] & string
Parameters
options
RunActionOptions<TFlow, TActionName>
Returns
Promise<ExecutionResult>
slackWebhookVerifier()
function slackWebhookVerifier(secret, options?): WebhookVerifier;
Slack (Events API) webhook verifier. Slack's scheme differs from the generic
HMAC helper: the signed base string is v0:<timestamp>:<rawBody> where the
timestamp comes from a separate X-Slack-Request-Timestamp header and the
signature (v0=<hex>) from X-Slack-Signature. The timestamp check rejects
stale requests (default 300s window).
Parameters
secret
string | (() => string)
options?
Returns
stripeWebhookVerifier()
function stripeWebhookVerifier(secret, options?): WebhookVerifier;
Stripe webhook verifier. Reads Stripe-Signature (t=<ts>,v1=<hex>),
signs <ts>.<rawBody>, and rejects timestamps older than toleranceSeconds
(default 300s) to defend against replay.
Parameters
secret
string | (() => string)
options?
toleranceSeconds?
number
Returns
toBareStates()
function toBareStates<T>(entries): Record<string, T>;
Drop the versions from a bulk read, keeping the keys.
Type Parameters
T
T extends JsonObject = JsonObject
The stored state's shape. Asserted, not validated; defaults to JsonObject.
Parameters
entries
Record<string, VersionedResourceState>
Returns
Record<string, T>
voiceContext()
function voiceContext(_input, ctx): string | undefined;
Context function for voice-enabled generators.
When TTS is active or the user spoke, tells the LLM to adapt its output style (shorter sentences, no markdown tables, conversational tone). Re-evaluated before each step of the tool loop via prepareStep, so it reflects the current request's voice metadata.
Add to a generator's context array when the flow declares voice.tts.
Parameters
_input
unknown
ctx
BlockContext
Returns
string | undefined
Example
import { voiceContext } from "@flow-state-dev/engine";
generator({
name: "assistant",
context: [voiceContext],
// ...
});